Django Session在Heroku上不起作用 [英] Django Session Not Working on Heroku

查看:95
本文介绍了Django Session在Heroku上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经基于Django教程编写了一个简单的投票应用程序.我想将每个访问者的投票数限制为1,因此我使用了Django的中间件会话.我完全不熟悉会话,但是可以在本地计算机上工作.不幸的是,一旦我将它推到Heroku上,它就停止工作了.当您有多个测功机时,我还看到了一些其他有关此问题的SO文章,但是我的Hobby帐户中只有1个测功机,所以...

I've written a simple voting app based on the Django tutorial. I want to limit the number of votes per visitor to one, so I have used Django's middleware sessions. I'm completely new to sessions, but I was able to get something working on my local machine. Unfortunately, once I pushed it to Heroku, it stopped working. I saw a few other SO articles regarding this issue when you have multiple dynos, but I am on a Hobby account with just 1 dyno, so...

这是我的观点的逻辑.py:

Here's the logic in my views.py:

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    if request.session.get('has_voted', False):
        return render(request, 'poll/detail.html', {
            'question': question,
            'error_message': ("You've already voted."),
            })
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'poll/detail.html', {
            'question': question,
            'error_message': "Make sure to select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        request.session['has_voted'] = True
        return HttpResponseRedirect(reverse('results', args=(question.id,)))

会话逻辑几乎完全来自文档,并且我的settings.py配置正确.我错过了Heroku的特殊配置吗?毕竟我需要在我的settings.py中添加一些内容吗?我无所适从,因为没有实际的错误.它只是默默地失败了...

The session logic comes almost verbatim from the documentation, and my settings.py is correctly configured. Is there a special configuration for Heroku that I missed? Do I need to add something to my settings.py after all? I'm at a loss since there is no actual error. It just fails silently...

谢谢!

推荐答案

您在settings.py中使用哪种SESSION_ENGINE?在Heroku上,Dynos始终重新启动,应将其视为临时资源.

What sort of SESSION_ENGINE are you using in your settings.py? On Heroku, Dynos restart all the time, and should be treated as ephemeral resources.

要解决这个问题,您可能应该使用SESSION_ENGINE= 'django.contrib.sessions.backends.cached_db'.这将确保您的会话数据持久化到Heroku上的数据库中(您正在使用 Heroku Postgres ,对吧?)

To combat this, you should probably use SESSION_ENGINE= 'django.contrib.sessions.backends.cached_db'. This will ensure your session data gets persisted to your database on Heroku (you are using Heroku Postgres, right?)

这篇关于Django Session在Heroku上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆