python-3.x - 如何使我的程序与 Python 3.7 中的 asyncio 异步?
问题描述
我的代码是从 ES 数据库中搜索数据并在数据库中添加一些新数据。我曾经在单个进程中运行,但这太低效了,所以我想在我的代码中添加 asyncio。我该怎么做?基于安全考虑,我删除了我的 ES 数据的 URL。有没有人可以帮助我?
import json
import requests
from elasticsearch import Elasticsearch
import asyncio
class Cited:
def __init__(self):
self.es = Elasticsearch(
[''],
)
async def get_es_item(self):
query_body = {
"from": 0,
"size": 10000
,
"query": {
"bool": {
"must":
{
"exists": {
"field": "extra.S2PaperId"
}
}
, "must_not":
{"exists": {
"field": "extra.citations"
}}
}
}
}
items = self.es.search(index='item', body=query_body, doc_type=None, request_timeout=6000)
items = items['hits']['hits']
for item in items:
item_type = item['_type']
item_id = item['_id']
S2PaperId = item['_source']['extra']['S2PaperId']
self.search_ss(item_id=item_id, paperId=S2PaperId, item_type=item_type)
def search_ss(self, item_id, paperId, item_type):
headers = {
'user-agent': 'Mozilla/5.0 (Macintosh Intel Mac OS X 10_13_4) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'
}
req = requests.get('https://api.semanticscholar.org/v1/paper/' + paperId, headers=headers, timeout=100)
# logging.info(req.url)
if req.status_code == 200:
req = json.loads(req.text)
citations = len(req['citations'])
citationVelocity = req['citationVelocity']
influentialCitationCount = req['influentialCitationCount']
self.es.update(index='item', doc_type=item_type, id=item_id,
body={'doc': {'extra': {'citations': citations, 'citationVelocity': citationVelocity,
'influentialCitationCount': influentialCitationCount}}},
request_timeout=6000)
print(item_id, item_type, citations, citationVelocity, influentialCitationCount)
else:
print('s2paper 出错了 直接补0' + item_id, item_type)
self.es.update(index='item', doc_type=item_type, id=item_id,
body={'doc': {'extra': {'citations': 0, 'citationVelocity': 0,
'influentialCitationCount': 0}}},
request_timeout=6000)
cited = Cited()
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(cited.get_es_item(), cited.get_es_item(), cited.get_es_item(), cited.get_es_item()))
解决方案
推荐阅读
- vue.js - 如何将类应用于 Buefy 表中的特定单元格?
- processing - 如何将带通滤波器应用于处理 3 中绘制的 EEG 数据?
- python - 在 Mayavi 中更改轴的顺序
- windows - 如何在 Windows 上的 git 配置中修复“ssh 权限被拒绝,请重试错误”
- javascript - 我想在 javascript 中计算保修到期日期
- java - Java - 尝试在数组内创建圆形对象
- python - 从键中减去字典值
- puppeteer - 无法在 Puppeteer 中选择每页选项
- reactjs - React - 从组合根中提供全局单例
- r - 网页抓取:如何使用 R 抓取延迟加载的数据