【问题标题】:How should appropriate Django session template look like?适当的 Django 会话模板应该是什么样子?
【发布时间】:2017-11-01 22:49:28
【问题描述】:

我不确定我是否以适当的方式使用 Django 会话。要登录,我使用此视图和 URL:

url(r'^login/$', views.my_login)

from django.contrib.auth import authenticate, login

@api_view(['POST'])
def my_login(request):
  if request.method == 'POST':
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = authenticate(username=username, password=password)
    if user is not None:
      if user.is_active:
        request.session.set_expiry(86400)            
        login(request, user)

在所有需要身份验证的方法中,我都使用if request.user.is_authenticated()@login_required

如果这是一个好方法,我如何同时使用@api_view(['GET', 'POST'])@login_require

在我看来这不是一个好的解决方案:

@login_require
@api_view(['GET', 'POST'])
def my_func(request):
    #...

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: python django python-3.x session django-rest-framework


    【解决方案1】:

    由于您使用的是 django-rest-framework,我建议您使用他们的默认身份验证方式。

    使用@authentication_classes((SessionAuthentication, BasicAuthentication))

    drf setting-the-authentication-scheme

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-31
      • 1970-01-01
      • 1970-01-01
      • 2014-12-12
      • 2015-12-09
      • 2017-12-14
      • 1970-01-01
      相关资源
      最近更新 更多