需要用到的第三方包:
rest_framework: 提供restful api的实现
官方地址:https://www.django-rest-framework.org/
pip install djangorestframework
pip install markdown # Markdown support for the browsable API.
pip install django-filter # Filtering support
Django rest_framework JWT: JSON Web Token Authentication support for Django REST Framework
官方地址:http://getblimp.github.io/django-rest-framework-jwt/
pip install djangorestframework-jwt
django-oauth2-provider: 提供oauth2的实现
官方地址:https://django-oauth2-provider.readthedocs.io/en/latest/
pip install django-oauth2-provider
mongoengine: 提供Django对Mongodb的访问实现
官方地址:http://docs.mongoengine.org/
pip install -U mongoengine
pymysql:提供对Mysql的访问实现
pip install pymysql
Setting设置:
需要添加的第三方APPS
INSTALLED_APPS=...
'rest_framework',
数据库设置:同时支持Mysql和Mongodb
Mysql设置:
import pymysql
pymysql.install_as_MySQLdb()
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1',
'PORT': 3306,
'USER': 'root',
'PASSWORD': '1234',
'NAME': 'databasename',
}
# 'default': {
# 'ENGINE': None,
# }
}
语言支持和时区
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
跨站点访问支持
CORS_ORIGIN_ALLOW_ALL = True
JWT验证相关参数
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
import datetime
JWT_AUTH = {
'JWT_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_payload_handler',
'JWT_PAYLOAD_GET_USER_ID_HANDLER':
'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',
'JWT_RESPONSE_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_response_payload_handler',
'JWT_GET_USER_SECRET_KEY': None,
'JWT_PUBLIC_KEY': None,
'JWT_PRIVATE_KEY': None,
'JWT_ALGORITHM': 'HS256',
'JWT_VERIFY': True,
'JWT_VERIFY_EXPIRATION': True,
'JWT_LEEWAY': 0,
'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=5),
'JWT_AUDIENCE': None,
'JWT_ISSUER': None,
'JWT_ALLOW_REFRESH': False,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
'JWT_AUTH_HEADER_PREFIX': 'Bearer',
'JWT_AUTH_COOKIE': None,
}
创建一个自定义User继承自AbstractUser,添加需要的自定义。