我有一个带有登录网页的 Django 站点。当提交页面上的登录表单时,它会执行登录视图,该视图会在其中运行一个需要很长时间处理(30秒左右)的函数。因此,为了在登录期间向客户端显示进度,一旦提交表单,登录页面上的 JS 函数就会开始向服务器发出 AJAX POST 请求(向poll_state
view),它返回登录状态。然后它更新登录页面的 html 以显示状态(如加载栏)。
我的问题是当我做常规的python manage.py runserver
使用 NGINX 代理服务器,它可以完美地工作。但是当我使用 Gunicorn 而不是python manage.py runserver
在登录视图完全处理并返回响应(这是下一个网页)之前,AJAX 请求不会执行。它不会轮询登录状态,而是返回一堆错误poll_state
加载下一个网页后查看。
当用户提交登录表单时,服务器执行登录视图,同时客户端开始使用 AJAX 请求轮询服务器。以下是登录网页上发送请求的 JS 代码:
let willstop = 0
var poll = function() {
$.ajax({
url:'http://<my server's ip>/poll_state/',
type: 'POST',
data: {
csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(),
id: $('#id').val(),
},
success: function(pollResult) {
step = pollResult.data
if (step == 'Done')
willstop = 1
$('#step').html(step)
}
})
}
let refreshIntervalId = setInterval(function() {
poll()
if(willstop == 1) {
clearInterval(refreshIntervalId);
}
}, 500)
它只是向我的服务器发送一个请求poll_state
查看(我省略了我的服务器地址,但如果有帮助的话可以分享它!)每半秒一次,直到登录完成(步骤==“完成”),然后它只是清除间隔(这有点多余,因为它重定向无论如何,到一个新页面)。
And the poll_state
view:
def poll_state(request):
""" A view to report the progress to the user """
data = 'Fail'
if request.is_ajax() and request.method == 'POST':
data = loggingInSteps[request.POST.get('id')]
else:
data = 'This is not an ajax request'
result = {'data': data}
return JsonResponse(result)
loggingInSteps
是服务器上的全局字典,其中包含所有客户端的步骤。每个客户端都有一个唯一的id,它是键,值是客户端在登录过程中所处的步骤。键值对在重定向时被删除。
我运行的服务器是 64 位 Ubuntu DigitalOcean Droplet,因此它应该是我的生产服务器。我跟着本教程 http://adambeagle.com/blog/deploying-django-17-ubuntu/设置服务器,所以我的 NGINX 配置是:
server {
listen 80;
server_name cume;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /static/ {
alias /home/mikmaks/dev/CUNYsecond/cume/static/;
}
}
我这样启动 Gunicorngunicorn config.wsgi --bind 127.0.0.1:8000
或者作为这样的守护进程:gunicorn config.wsgi --bind 127.0.0.1:8000 --daemon --log-file ~/dev/logs/cume_gunicorn.log --workers=3
任何一个版本都不起作用。
有谁知道 Gunicorn 是否可以在处理来自同一客户端的正常请求时接受来自同一客户端的 AJAX 请求?也许问题不在于 Gunicorn,而在于我的 NGINX 配置。十分感谢你的帮助。如有必要,我很乐意提供任何代码或附加信息:)