Python 如何将tweepy api调用转换为异步
我有一个98000+的twitter句柄列表。使用tweepy,我想获取一些特定用户的信息,如用户名、描述等。 对于这么多的数据,我采用的方法非常慢。所以我想实现异步IO 我目前正在遍历tweeter句柄列表,并获取每个句柄的数据 我的代码如下Python 如何将tweepy api调用转换为异步,python,asynchronous,Python,Asynchronous,我有一个98000+的twitter句柄列表。使用tweepy,我想获取一些特定用户的信息,如用户名、描述等。 对于这么多的数据,我采用的方法非常慢。所以我想实现异步IO 我目前正在遍历tweeter句柄列表,并获取每个句柄的数据 我的代码如下 # import tweeter API credentials import credentials as c # import tweeter user handles fetched from DB import get_handles # i
# import tweeter API credentials
import credentials as c
# import tweeter user handles fetched from DB
import get_handles
# import required modules
import json
import tweepy
# List of tweeter handles
handles = get_handles.twitter_handles
# authentication
auth = tweepy.OAuthHandler(c.API_KEY, c.API_SECRET_KEY)
auth.set_access_token(c.ACCESS_TOKEN, c.ACCESS_TOKEN_SECRET)
api = tweepy.API(auth, timeout=5)
# open a file inorder to write data fetched from API
with open('userinfo2.json', 'w') as outfile:
for x in range(9508, len(handles)):
user = api.get_user(handles[x])
data = {
'name': user.name, 'description': user.description,
'profile_image_url': user.profile_image_url,
'followers_count': user.followers_count,
}
json.dump(data, outfile, indent=4)
print('%s number of data fetched', (x))
outfile.close()
如何以异步方式转换此代码?我正在使用tweepy.API上的包装器来实现这一点
# atweepy.py
import asyncio
import functools
import tweepy # type: ignore
from tweepy import *
async def acall(f, *args, **kwargs):
return await asyncio.get_running_loop().run_in_executor(
None, lambda: f(*args, **kwargs)
)
def awrap(f):
@functools.wraps(f)
async def wrapper(*args, **kwargs):
return await acall(f, *args, **kwargs)
return wrapper
def create_aproxy_class(cls):
class AsyncProxy:
__name__ = cls.__name__
__doc__ = cls.__doc__
def __init__(self, *args, **kwargs):
self.proxy = cls(*args, **kwargs)
def __getattr__(self, attr):
attr = getattr(self.proxy, attr)
return awrap(attr) if callable(attr) else attr
return AsyncProxy
API = create_aproxy_class(tweepy.API)
并创建API
import atweepy
async def create_twitter(key, secret, access_token, access_token_secret):
try:
auth = atweepy.OAuthHandler(key, secret)
except tweepy.TweepError:
return
auth.set_access_token(access_token, access_token_secret)
api = atweepy.API(
auth,
retry_count=3,
retry_delay=10,
wait_on_rate_limit_notify=True,
wait_on_rate_limit=True,
compression=True,
)
return api
然后要调用任何API方法,必须在其前面放置一个wait
api = create_api(key, secret, access_token, access_token_secret)
me = await api.me()
tweet = await api.get_status(some_id)
tl = await api.mentions_timeline()
这将使用.run\u in\u executor
调用包装API的所有方法。这并不理想,但对我来说很有效。关于这个主题的更多信息,请参阅
致以最诚挚的问候您可以将
userinfo2.json
分块,并在编写时创建一个函数,使用tweepy
发送请求,然后建立几个线程并发/异步调用所述函数。但是,有一个限制:.tweepy。AsyncStream在此PR中是WIP。