Django自定义中间件Middleware

2019-11-5 张宇童 Python

from django.utils.deprecation import MiddlewareMixin
# from django.http import HttpResponse
from django.shortcuts import HttpResponse, redirect
 
 
# 方式一:
class MyMiddleware(MiddlewareMixin):
    def process_request(self, request):
        next_url = request.path_info
        if not request.path_info.startswith("/login/"):
            # 做登录验证
            login_flag = request.session.get("login", "")
            if not login_flag:
                return redirect("/login/?next={}".format(next_url))
 
    def process_view(self, request, view_func, view_args, view_kwargs):
        pass
 
    def process_exception(self, request, exception):
        if isinstance(exception, ValueError):
            return HttpResponse("404")
 
    def process_response(self, request, response):
        return response # 这里必须返回response
 
 
# 方式二:
class SimpleMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
        # 一次性配置和初始化。
 
    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        # 这里写的代码会在视图被调用前执行来处理请求
        response = self.get_response(request)
        # 这里写的代码会在视图调用后执行来处理响应
        # Code to be executed for each request/response after
        # the view is called.
 
        return response
 
    def process_view(self, request, view_func, view_args, view_kwargs):
        pass
 
    def process_exception(self, request, exception):
        pass
 
    def process_template_response(self, request, response):
	pass

# 在settings.py里的下面列表中添加自定义的中间件来激活该中间件
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'mymiddlewares.middlewares.MyMiddleware',
    'mymiddlewares.middlewares.SimpleMiddleware',
]

标签: python3 中间件

评论(0) 浏览(587)

exceptions: django2.2/ mysql ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3

2019-10-20 张宇童 Python

在centos部署python应用后访问页面,显示如下异常信息

报错环境 python=3.6,django=2.2
……
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.
解决方法:

Django连接MySQL时默认使用MySQLdb驱动,但MySQLdb不支持Python3,因此这里将MySQL驱动设置为pymysql,使用 pip install pymysql 进行安装,然后在工程文件__init__.py添加以下代码即可。

# 安装pymysql
pip install pymysql
#__init__.py
import pymysql
pymysql.install_as_MySQLdb()
第一种:
django降到2.1.4版本就OK了

第二种(仍使用django 2.2版本):
#找到Python环境下 django包,并进入到backends下的mysql文件夹
cd /opt/anaconda3/envs/envAGC_Mini/lib/python3.6/site-packages/django/db/backends/mysql
#文件列表如下
1320942-20190709151951155-349243023.png


# 找到base.py文件,注释掉 base.py 中如下部分(35/36行)
if version < (1, 3, 3):
     raise ImproperlyConfigured("mysqlclient 1.3.3 or newer is required; you have %s" % Database.__version__)

此时仍会会报错,报错信息如下:

AttributeError: ‘str’ object has no attribute ‘decode’

#找到operations.py文件(46行,版本不同行数不同哈~自个儿find一下),将decode改为encode
#linux vim 查找快捷键:?decode
if query is not None:
    query = query.decode(errors='replace')
return query
#改为
if query is not None:
    query = query.encode(errors='replace')
return query

标签: Django python3

评论(0) 浏览(2130)

Powered by emlog