如何设置Django函数,使其从按钮onclick在后台运行



我有一个Django项目,其中一个函数当前运行在我的html-的onclick上

def follow(request):
api = get_api(request)
followers = tweepy.Cursor(api.followers_ids, wait_on_rate_limit=True).items()
for x in followers:
try:
api.create_friendship(x)
except Exception:
pass
return render(request, "followed.html")

该功能运行并跟随授权用户的追随者。我的问题是,当部署在我的pythonywhere网络应用程序上时,该功能将在浏览器中加载,然后在大约10分钟后超时。我已经在多达100名粉丝的用户身上进行了测试,一切都很有效。

这很好,但Twitter API有费率限制,因此对于一些拥有大量粉丝的用户来说,这个功能需要很长时间才能完成。

有没有一种方法可以转移到下面的.html并在后台运行该函数直到它完成?

我添加了oauth功能,以防它们也需要——


def auth(request):
# start the OAuth process, set up a handler with our details
oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
# direct the user to the authentication url
# if user is logged-in and authorized then transparently goto the callback URL
auth_url = oauth.get_authorization_url(True)
response = HttpResponseRedirect(auth_url)
# store the request token
request.session['request_token'] = oauth.request_token
return response
def callback(request):
verifier = request.GET.get('oauth_verifier')
oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
token = request.session.get('request_token')
# remove the request token now we don't need it
request.session.delete('request_token')
oauth.request_token = token
# get the access token and store
try:
oauth.get_access_token(verifier)
except tweepy.TweepError:
print('Error, failed to get access token')
request.session['access_key_tw'] = oauth.access_token
request.session['access_secret_tw'] = oauth.access_token_secret
print(request.session['access_key_tw'])
print(request.session['access_secret_tw'])
response = HttpResponseRedirect(reverse('index'))
return response

您应该考虑使用任务队列在后台进行工作。一般来说,做任何";"阻塞";在处理HTTP请求时(例如让服务器等待的事情,例如连接到另一台服务器并获取数据(应该作为后台任务来完成。

常见的(也是好的!(Python任务队列是Celery和rq-rq,它们特别轻,还具有Django包装器Django-rq-

我会花一些时间阅读rq或Celery文档,了解如何将您的Twitter API调用作为后台任务进行,这将避免您的web服务器超时。

您可以为此使用异步任务队列(例如芹菜(。看看这个:https://realpython.com/asynchronous-tasks-with-django-and-celery/

最新更新