简体   繁体   English

Django 会话不工作

[英]Django Sessions not Working

I have built an application that shows users their storage usage and quotas on a system.我构建了一个应用程序,可以向用户显示他们在系统上的存储使用情况和配额。 Since there are many users, sifting through their storage allocations can be tedious so I want to give admins the option of acting as that user.由于有很多用户,筛选他们的存储分配可能很乏味,所以我想让管理员可以选择充当该用户。 The application decides which user is accessing the application based on an employee ID received via a secure badg, the variable (EMPLOYEE_ID) is stored in the request.META dictionary.应用程序根据通过安全徽章收到的员工 ID 来决定哪个用户正在访问应用程序,变量 (EMPLOYEE_ID) 存储在 request.META 字典中。

Ideally, I want the admins to be able to override this employee ID with another user's ID by posting it in a form.理想情况下,我希望管理员能够通过在表单中发布该员工 ID 来使用另一个用户的 ID 覆盖它。 The form works and then serves the storage_home.html page as the employee the admin wishes to act as via a POST request, but when I or another admin clicks and does a GET for the quotas, the request.session dictionary is empty!该表单有效,然后作为管理员希望通过 POST 请求充当的员工提供 storage_home.html 页面,但是当我或其他管理员单击并为配额执行 GET 时,request.session 字典为空!

EMPLOYEE_ID is the original employee id of the admin
SIM_EMPLOYEE_ID is the employee the admin wishes to act as

I wonder if it's the way I'm linking to the quotas view in the storage_home.html template?我想知道这是否是我链接到 storage_home.html 模板中的配额视图的方式? Not sure.不确定。

Here is my code, I believe you should only need views, and the template that calls the quotas view function to see what the issue is since the request.sessions dictionary does have the SIM_EMPLOYEE_ID variable after the post that serves storage_home.html.这是我的代码,我相信您应该只需要视图,以及调用配额视图 function 以查看问题所在的模板,因为 request.sessions 字典在服务于 storage_home.html 的帖子后确实有 SIM_EMPLOYEE_ID 变量。 I've omitted some variables from the views that are used in the template, but they work just fine, didn't want to clutter the code too much.我从模板中使用的视图中省略了一些变量,但它们工作得很好,不想让代码过于混乱。

The sim_user function is called when the form is submitted.提交表单时调用 sim_user function。 This then just recalls the storage function and right now successfully displays what I want it to, it's the GET request subsequently that fail to keep the session. I also have the following set in my settings:然后这只是召回存储 function,现在成功显示了我想要的内容,随后的 GET 请求未能保留 session。我的设置中也有以下设置:

SESSION_COOKIE_SECURE = True
SESSION_COOKIE_DOMAIN = '.mydomain.com'
SESSION_SAVE_EVERY_REQUEST = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = False

views.py视图.py

def home(request):
    """Redirect requests at root url to /storage"""

    return HttpResponseRedirect('/storage/')

def storage(request):
    """Return the home template."""

    context = {}
    context.update(csrf(request))

    empid = request.session.get('SIM_EMPLOYEE_ID')
    if not empid:
        empid = request.META.get('EMPLOYEE_ID')

    if functions.is_admin(empid):
        form = UserForm()
        context['form'] = form
        template = loader.get_template('storage_admin.html')
    else:
        template = loader.get_template('storage_home.html')

    data = RequestContext(request, context)
    return HttpResponse(template.render(data))

def sim_user(request):
    context = {}
    context.update(csrf(request))

    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            empid = form.cleaned_data['empid']
            request.session['SIM_EMPLOYEE_ID'] = empid
            request.session.modified = True
            return storage(request)

    template = loader.get_template('deny.html')
    data = RequestContext(request, context)
    return HttpResponse(template.render(data))

def quotas(request, sitename):
    """Return quota page depending on the
       id of the employee. If employee is an
       administrator, show all the quota information
       for all users/projects. If employee is a user
       of the sitename, show them user specific quota information.
       Otherwise, deny access and display a custom template."""

    context = {}
    site = sitename.capitalize()

    # EMPLOYEE_ID is in the Http Request's META information
    empid = request.session.get('SIM_EMPLOYEE_ID')
    if not empid:
        empid = request.META.get('EMPLOYEE_ID')

    if not empid:
        template = loader.get_template('deny.html')
        return HttpResponse(template.render(RequestContext(request, context)))

    if functions.is_admin(empid):
        template = loader.get_template('all_quotas.html')
    else:
        template = loader.get_template('personal_quotas.html')

    data = RequestContext(request, context)
    return HttpResponse(template.render(data))

storage_home.html storage_home.html

{% extends 'base.html' %}

{% block title %}Storage Utilization{% endblock %}

{% block content %}
    <h1 id="header"><b>Storage Utilization</b></h1>
    <p></p>
    <table id="storage_table" cellspacing="15">
        <tbody>
        {% for site in sites %}
        {% url "su.views.quotas" as quota %}
        <tr>
            <td><a href="{{ quota }}{{ site }}/"><img src="/static/images/{{ site }}.png"></a></td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
    <br></br>
{% endblock %}

Thanks for any help, please let me know if you need more explanation, code, or simplification.感谢您的帮助,如果您需要更多解释、代码或简化,请告诉我。

Turns out removing SESSION_COOKIE_SECURE = True fixed the issue. 原来是删除SESSION_COOKIE_SECURE = True解决了该问题。 This is my fault for not forgetting that my dev environment uses http and prod https. 这是我不能忘记我的开发环境使用http和prod https的错误。 I actually have separate settings files, but failed to use them properly when I went back to test this new feature. 我实际上有单独的设置文件,但是当我回去测试此新功能时未能正确使用它们。 I believe setting the SESSION_COOKIE_SECURE to True when using https should work once I test the production server. 我相信在测试生产服务器后,使用https时将SESSION_COOKIE_SECURE设置为True应该可以。

Django provided session stopped working for me for some reason. Django 提供 session 出于某种原因停止为我工作。 I made my own it's really easy:我自己做的,真的很简单:

models.py模型.py

class CustomSession(models.Model):
    uid = models.CharField(max_length=256)

    def __str__(self):
        return self.uid

How to work with CustomSession如何使用 CustomSession

from oauth.models import CustomSession
session = CustomSession.objects      # get a list of session objects
new_user = CustomSession(uid=<UID>)  # save a user to the session (by uid)
session.get(id=<ID>).uid                 # get user id
session.get(id=<ID>).delete()           # delete user from session (logout)
session.all().delete()               # delete all user data in session

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM