python - 如何将 Django 函数设置为通过按钮 onclick 在后台运行?

标签 python django asynchronous background-process pythonanywhere

我有一个 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")

该函数运行并跟随授权用户的关注者。我的问题是,当部署在我的 pythonanywhere Web 应用程序上时,该函数将在浏览器中加载,然后在大约 10 分钟后超时。我已经对最多 100 个关注者的用户进行了测试,一切正常。

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

有没有办法转移到followed.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 任务队列是 Celeryrq - rq 特别轻量级,并且还有 Django 包装器 django-rq

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

关于python - 如何将 Django 函数设置为通过按钮 onclick 在后台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65494875/

相关文章:

Django 忽略了我的 TestCase 装置

c++ - boost::asio::deadline_timer::async_wait 内部出现段错误

c# - Lazy<> 和 Task<> 可以组合起来推迟数据库查找吗?

python - 无法在 Docker Ubuntu 主机中使用 cv2.VideoCapture(0) 打开相机

python - 具有 "gcloud functions deploy"的 GCP 云函数失败,--source 作为文件而不是目录

python - 属性错误: module 'cv2.cv2' has no attribute 'samples'

django - 如何在 django 模板中显示代码片段, "|safe"过滤器没有帮助

python - 为什么db_index=False时需要指定 key 长度?

python - 使用 parquet 文件统计信息而不读取文件

jQuery ajax 页面重新加载