版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
在使用postman自测后端接口的时候,因为没法在postman中给request添加user,导致诸如权限验证等功能难以检测。这时可以先注释这一部分功能,等向前端开放接口时在去注释,也可以通过中间件给request伪造一个user,开放接口时注释掉中间件即可。
中间件至少需要定义以下三种钩子函数中一个或多个:
process_request # 请求预处理,在视图函数被定为之前预先处理请求,本例中就是定义了这个函数
process_view # 视图预处理,确定了当前请求对应的视图函数后,执行此函数
process_response # 响应后处理,在生成响应后执行
- 编写中间件
Press ? for help | 1 from django.utils.deprecation import MiddlewareMixin
| 2 from user.models import User
.. (up a dir) | 3
/home/starx/program/project / | 4
▾ apps/ | 5 class GrantUserMiddleware(MiddlewareMixin):
▸ __pycache__/ | 6 """为当前请求添加一个用户实例"""
▸ user/ | 7 def process_request(self, request):
▾ userapi/ | 8 ¦ # 1.获取一个可用的用户实例
__init__.py | 9 ¦ user = User.objects.get(id=1)
check.py | 10
urls.py | 11 ¦ # 2.将用于添加给request
UserView.py | 12 ¦ request.user = user # 注意这里不能return,否则会中断请求的处理流程
__init__.py |~
▾ project/ |~
▸ __pycache__/ |~
__init__.py |~
settings.py |~
urls.py |~
wsgi.py |~
▾ utils/ |~
▸ __pycache__/ |~
▸ errorcode/ |~
__init__.py |~
GrantTmpUser.py |~
middleware.py |~
db.sqlite3 |~
manage.py* |~
memo.md |~
中间件可以定义在项目目录下任意位置,这里定义在’project/utils/middleware.py’。
2. 在settinngs.py中注册自定义的中间件
" Press ? for help | 27
| 28 # SECURITY WARNING: don't run with debug turned on in production!
.. (up a dir) | 29 DEBUG = True
/home/starx/program/project / | 30
▾ apps/ | 31 ALLOWED_HOSTS = []
▸ __pycache__/ | 32
▸ user/ | 33
▾ userapi/ | 34 # Application definition
__init__.py | 35
check.py | 36 INSTALLED_APPS = [
urls.py | 37 +-- 7 lines: 'django.contrib.admin',-----------------------------------------------------------------------------------------------------------------------------------
UserView.py | 44 ]
__init__.py | 45
▾ project / | 46 MIDDLEWARE = [
▸ __pycache__/ | 47 'django.middleware.security.SecurityMiddleware',
__init__.py | 48 'django.contrib.sessions.middleware.SessionMiddleware',
settings.py | 49 'django.middleware.common.CommonMiddleware',
urls.py | 50 'django.middleware.csrf.CsrfViewMiddleware',
wsgi.py | 51 'django.contrib.auth.middleware.AuthenticationMiddleware',
▾ utils/ | 52 'django.contrib.messages.middleware.MessageMiddleware',
▸ __pycache__/ | 53 'django.middleware.clickjacking.XFrameOptionsMiddleware',
▸ errorcode/ | 54 'utils.middleware.GrantUserMiddleware', # 注册自定义的中间件
__init__.py | 55 ]
GrantTmpUser.py | 56
middleware.py | 57 ROOT_URLCONF = 'project.urls'
db.sqlite3 | 58
manage.py* | 59 TEMPLATES = [
memo.md
- 测试接口
接口部分代码:
class UserView(View):
"""
@apiName user_post
@api {POST} /user/
@apiGroup User
@apiVersion 0.0.1
@apiDescription [用户管理]添加用户
@apiParam {String} username 用户姓名
@apiParam {String} password 用户密码
@apiParam {String} eamil 邮箱地址
@apiParam {string} gender 性别 'm'男,'f'女
@apiSuccess (200) {String} msg 信息
@apiSuccess (200) {String} code 0代表无错误 1代表有错误
@apiSuccess (200) {int} user_id 用户id
@apiSuccessExample {json} 返回样例:
{
¦ "code": 0,
¦ "msg": "SUCCESS",
¦ "user_id":1 用户id
}
"""
def post(self, request):
¦ # 1.获取参数
¦ creater = request.user
¦ print(creater.username)
¦ username = str(request.POST.get('username'))
¦ password = str(request.POST.get('password'))
¦ email = str(request.POST.get('email'))
¦ gender = str(request.POST.get('gender'))
¦
¦ # 2.校验参数
¦ if not creater.is_superuser:
¦ ¦ raise AuthenticationException(error=u'当前用户没有操作权限')
¦ if username == None or username == '':
¦ ¦ raise ParamMissingException(error=u'用户名不能为空')
改变middleware中添加的用户身份,测试接口的验证逻辑
给request添加的user是普通用户时:
给request添加的user是管理员时: