ubantu deepin 版本下,windows下参考网址:
www.lfd.uci.edu/~gohlke/pythonlibs/
http://[email protected]/xxxx/xxxxx.git
安装虚拟环境:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py # 下载安装脚本
sudo apt install python3-pip #ubuntu下默认已安装python3
sudo python get-pip.py
#服务器裸机,如有python2,则安装pip,命令如上
pip3 install virtualenv
pip3 install virtualenvwrapper
创建虚拟环境:
mkvirtualenv 虚拟环境名称
deactivate #离开虚拟环境
rmvitualenv 虚拟环境名称 #删除虚拟环境
安装djangorestframework:
pip3 install djangorestframework # settings中INSTALLED_APPS中加入'rest_framework'
pip3 install django
pip3 install django-filter # settings中INSTALLED_APPS中加入'django_filters'
pip3 install markdown
pip3 install coreapi
pip3 install django-crispy-forms # settings中INSTALLED_APPS中加入'crispy_forms'
pip3 install django-guardian
pip3 install django-cors-headers
pip3 install django_tables2
#若使用postgresql,则安装psycopg2
pip install psycopg2
#安装失败需要安装前置包
sudo apt-get install libpq-dev python-dev
pip install psycopg2
安装图片处理的第三方包:
pip3 install -i https://pypi.douban.com/simple pillow
settings中加入以下配置:
import sys
#加入BASE_DIR下面
sys.path.insert(0, BASE_DIR)
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps'))
AUTH_USER_MODEL = 'users.UserProfile' #替换系统用户
富文本编辑去github上(https://github.com/twz915/DjangoUeditor3),下载djangoueditor3, 字段如下例:
class Goods(models.Model):
"""商品"""
name = models.CharField(max_length=30, db_column='name', null=True, blank=True, verbose_name='商品名称')
price = models.FloatField(db_column='price', null=True, blank=True, verbose_name='价格')
amount = models.PositiveIntegerField(db_column='amount', null=True, blank=True, verbose_name='数量')
dec = UEditorField(db_column='dec', imagePath='goods',width=1000, filePath='goods/files', height=1000, default='')
class Meta:
db_table = "war_goods"
verbose_name = '商品'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
admin后台,配置如下:
settings中,INSTALLED_APPS加入 'django.contrib.admin',
同级的urls.py如下:
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
url('doc/', include_docs_urls(title='XXX')),
]
记得新建超级用户。
解决跨域问题:
pip3 install django-cors-headers
在settings的MIDDLEWARE中配置'corsheaders.middleware.CorsMiddleware',放在第一个。
然后在MIDDLEWARE外配置 CORS_ORIGIN_ALLOW_ALL = True
jwt的登录配置:
pip3 install djangorestframework-jwt
在urls中配置:
from rest_framework_jwt.views import obtain_jwt_token
#...
urlpatterns = [
#drf自带的token认证模式
url(r'^api-token-auth/', views.obtain_auth_token),
#jwt的认证接口
url(r'^login/', obtain_jwt_token),
]
在views中的class中配置:
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication
class ()
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
自定义用户验证
在settings中加入代码:
AUTHENTICATION_BACKENDS = (
'一个验证的类',
)
在View或者其他文python件中加入代码:
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.db.models import Q
User = get_user_model()
class CustomBackend(ModelBackend):
"""自定义用户验证"""
def authenticate(self, username=None, password=None, **kwargs)
try:
user = User.objects.get(Q(username=username) | Q(mobile=username))
if user.check_password(password):
return user
except Exception as e:
return None
在settings中加入jwt设置:
"""
JWT认证的相关属性设置
"""
# JWT_AUTH = {
# 'JWT_ENCODE_HANDLER':
# 'rest_framework_jwt.utils.jwt_encode_handler',
#
# 'JWT_DECODE_HANDLER':
# 'rest_framework_jwt.utils.jwt_decode_handler',
#
# '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_SECRET_KEY': settings.SECRET_KEY,
# '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(seconds=300),
# 'JWT_AUDIENCE': None,
# 'JWT_ISSUER': None,
#
# 'JWT_ALLOW_REFRESH': False,
# 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
#
# 'JWT_AUTH_HEADER_PREFIX': 'JWT',
# 'JWT_AUTH_COOKIE': None,
# }
JWT_AUTH = {
'JWT_RESPONSE_PAYLOAD_HANDLER': 'system.tools.jwt_response_payload_handler',
'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=3),
'JWT_AUTH_HEADER_PREFIX': 'JWT',
'JWT_AUTH_COOKIE': 'JWT'
}
创建用户时修改密码,信号量配置如下:
新建signals.py文件:
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth import get_user_model
user = get_user_model
@receiver(post_save, sender=user)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
password = instance.password
instance.set_password(password)
instance.save()
在apps.py 中配置如下:
class UsersConfig(AppConfig):
name = 'users'
verbose_name = '用户管理'
def ready(self):
import users.signals
用户注册后直接跳转登录配置:
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
#在userview中重写create方法
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = self.perform_create(serializer)
re_dict = serializer.data
payload = jwt_payload_handler(user)
re_dict['token'] = jwt_encode_handler(payload)
re_dict['name'] = user.name if user.name else user.username
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def perform_create(self, serializer):
serializer.save()