禁用Django中的会话创建 [英] Disable session creation in Django

查看:43
本文介绍了禁用Django中的会话创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望对某些URL禁用Django中的自动会话创建。我有/ api / *,每个点击的客户端都会获得一个新的Django会话。有没有办法忽略某些网址?

I'm looking to disable the automatic session creation in Django for certain URLs. I have /api/* and each client that hits that gets a new Django session. Is there a way to ignore certain urls?

推荐答案

一个简单的解决方案是让您的网络服务器区分API调用和常规调用调用,然后有两个不同的应用程序WSGI实例:一个启用了会话,另一个禁用了会话。 (使用Nginx可能比使用Apache更容易。)

A trivial solution to this is to have your webserver distinguish between API calls and regular calls, then have two different WSGI instances of your application: one with sessions enabled, the other with sessions disabled. (This is probably much easier with Nginx than with Apache.)

另一种方法是继承SessionMiddleware,然后编辑流程函数以忽略所有符合您条件的请求。像这样的东西:

An alternative is to inherit SessionMiddleware and then edit the process functions to ignore all requests matching your criteria. Something like:

from django.contrib.sessions.middleware import SessionMiddleware

class MySessionMiddleware(SessionMiddleware):
    def process_request(self, request):
        if request.path_info[0:5] == '/api/':
            return
        super(MySessionMiddleware, self).process_request(request)

    def process_response(self, request, response):
        if request.path_info[0:5] == '/api/':
            return response
        return super(MySessionMiddleware, self).process_response(request, response)

然后编辑设置文件,以便MIDDLEWARE_CLASSES包含 MySessionMiddleware的路径,而不是 django.contrib.sessions.middleware.SessionMiddleware的路径。

And then edit your setting's file so that MIDDLEWARE_CLASSES contains the path to "MySessionMiddleware" and not 'django.contrib.sessions.middleware.SessionMiddleware'.

这篇关于禁用Django中的会话创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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