当前位置: 移动技术网 > IT编程>脚本编程>Python > Django2.1.3 中间件使用详解

Django2.1.3 中间件使用详解

2019年06月14日  | 移动技术网IT编程  | 我要评论

丽人保镖国语版,圣力宝正元胶囊,偷上冰山老公

环境

  • win10
  • python3.6.6
  • django2.1.3

中间件作用 中间件用于全局修改django的输入或输出。

中间件常见用途

  • 缓存
  • 会话认证
  • 日志记录
  • 异常

中间件执行流程

全局异常捕捉实现

创建django项目&添加app

django-admin startproject middleware
cd middleware
django-admin startapp app

添加app到项目

# middleware/settings.py
# installed_apps最后添加 app
installed_apps = [
 'app',
]

编辑中间件并添加到项目

注:中间件注册访问有一定的关联性,位置不可以随意放

# 创建app/middleware.py并编辑
from django.http import jsonresponse


class custommiddleware:
 def __init__(self, get_response):
  print("程序启动时执行, 只执行一次")
  self.get_response = get_response

 def __call__(self, request):
  print("中间件开始")
  response = self.get_response(request)
  print("中间件结束")
  return response

 def process_view(self, request, view_func, view_args, view_kwargs):
  print("请求实际函数前执行")

 def process_exception(self, request, exception):
  print("程序异常时执行")
  return jsonresponse({"msg": exception.args[0], "code": -1})

编辑middleware.setttings.py

middleware = [
...
'app.middleware.custommiddleware'
]

编写一个异常

# app/views.py
from django.http import jsonresponse


def json_response(request):
 print('json_response')
 err = 3 / 0
 return jsonresponse({"msg": "ok", "code": 0})

添加到路由

# middleware/urls.py

from app.views import json_response, view_response

urlpatterns = [
 ...
 path("view", view_response)
]

运行测试

访问: http://127.0.0.1:8000/json/

结果

另一个觉用途日志记录

# 在中间件函数process_view中添加
print("path: {}; method: {}; data: {}".format(request.get_full_path(), request.method, request.body or ''))

参考:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网