簡體   English   中英

Django 會話不工作

[英]Django Sessions not Working

我構建了一個應用程序,可以向用戶顯示他們在系統上的存儲使用情況和配額。 由於有很多用戶,篩選他們的存儲分配可能很乏味,所以我想讓管理員可以選擇充當該用戶。 應用程序根據通過安全徽章收到的員工 ID 來決定哪個用戶正在訪問應用程序,變量 (EMPLOYEE_ID) 存儲在 request.META 字典中。

理想情況下,我希望管理員能夠通過在表單中發布該員工 ID 來使用另一個用戶的 ID 覆蓋它。 該表單有效,然后作為管理員希望通過 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

我想知道這是否是我鏈接到 storage_home.html 模板中的配額視圖的方式? 不確定。

這是我的代碼,我相信您應該只需要視圖,以及調用配額視圖 function 以查看問題所在的模板,因為 request.sessions 字典在服務於 storage_home.html 的帖子后確實有 SIM_EMPLOYEE_ID 變量。 我從模板中使用的視圖中省略了一些變量,但它們工作得很好,不想讓代碼過於混亂。

提交表單時調用 sim_user function。 然后這只是召回存儲 function,現在成功顯示了我想要的內容,隨后的 GET 請求未能保留 session。我的設置中也有以下設置:

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

視圖.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

{% 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 %}

感謝您的幫助,如果您需要更多解釋、代碼或簡化,請告訴我。

原來是刪除SESSION_COOKIE_SECURE = True解決了該問題。 這是我不能忘記我的開發環境使用http和prod https的錯誤。 我實際上有單獨的設置文件,但是當我回去測試此新功能時未能正確使用它們。 我相信在測試生產服務器后,使用https時將SESSION_COOKIE_SECURE設置為True應該可以。

Django 提供 session 出於某種原因停止為我工作。 我自己做的,真的很簡單:

模型.py

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

    def __str__(self):
        return self.uid

如何使用 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