rest-framework项目的使用步骤
一、基础准备工作
- 1、创建一个虚拟环境
2、虚拟环境中安装依赖包
pip3 install -r requirements.txt
(在之前的项目下运行命令pip3 freeze > requirements.txt
)asn1crypto==0.24.0 certifi==2018.4.16 cffi==1.11.5 chardet==3.0.4 coreapi==2.3.3 coreschema==0.0.4 cryptography==2.3 diff-match-patch==20121119 Django==2.0.7 django-cors-headers==2.4.0 django-crispy-forms==1.7.2 django-filter==2.0.0 django-formtools==2.1 django-import-export==1.0.1 djangorestframework==3.8.2 djangorestframework-jwt==1.11.0 et-xmlfile==1.0.1 future==0.16.0 geetest==3.2.0 httplib2==0.11.3 idna==2.7 itypes==1.1.0 jdcal==1.4 Jinja2==2.10 Markdown==2.6.11 MarkupSafe==1.0 odfpy==1.3.6 openpyxl==2.5.5 Pillow==5.2.0 post==1.0.2 pycparser==2.18 PyJWT==1.6.4 PyMySQL==0.9.2 pytz==2018.5 PyYAML==3.13 qiniu==7.2.2 requests==2.19.1 six==1.11.0 tablib==0.12.1 unicodecsv==0.14.1 uritemplate==3.0.0 urllib3==1.23 xlrd==1.1.0 xlwt==1.3.0 yunpian-python-sdk==1.0.0
二、项目的基本配置
1、配置
mysql
的数据库引擎DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mxshop', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': 3306 } }
2、在根目录的
__init__.py
中配置支持pymysql
引擎import pymysql pymysql.install_as_MySQLdb()
3、配置根
url
from django.urls import path, include, re_path import xadmin from django.views.static import serve from django.conf import settings from rest_framework.documentation import include_docs_urls urlpatterns = [ path('xadmin/', xadmin.site.urls), path('goods/', include('goods.urls', namespace='goods')), # 配置访问本地的资源地址 re_path(r'^media/(?P<path>.*)', serve, {"document_root": settings.MEDIA_ROOT}), # 配置用户登录 path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), # 配置文档 path('docs/', include_docs_urls(title='电商文档')) ]
三、重写用户表
1、重新定义
model
from django.contrib.auth.models import AbstractUser class UserProfileModel(AbstractUser): """ 创建一个用户的模型 """ nick_name = models.CharField(max_length=50, verbose_name='昵称', null=False, default='') birthday = models.DateField(verbose_name='生日', null=True, blank=True) gender = models.CharField(max_length=20, choices=(('male', '男'), ('female', '女')), default='male', verbose_name='性别') address = models.CharField(max_length=100, default='', verbose_name='地址') mobile = models.CharField(max_length=11, null=True, blank=True, verbose_name='手机号码') image = models.ImageField(upload_to='images/users/%Y/%m', default='images/default.jepg', verbose_name='头像') create_at = models.DateTimeField(auto_now_add=True, null=False, verbose_name='添加时间') update_at = models.DateTimeField(auto_now=True, null=False, verbose_name='修改时间') class Meta(object): verbose_name = '用户信息' verbose_name_plural = verbose_name def __unicode__(self): return self.username
2、在
settings.py
中定义使用我们自己定义的model
# 配置认证的用户表 AUTH_USER_MODEL = 'users.UserProfileModel'
四、用户登录的配置
1、用户登录的视图
from django.contrib.auth import authenticate, login, logout class LoginView(View): """ 用户登录的视图 """ def get(self, request, *args, **kwargs): return render(request, 'login.html', kwargs) def post(self, request, *args, **kwargs): login_form = forms.LoginForm(request.POST) if login_form.is_valid(): username = login_form.cleaned_data.get('username', None) password = login_form.cleaned_data.get('password', None) user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('home') else: return self.get(request, message="用户还没激活") return self.get(request, message='用户名或者密码错误') return self.get(request, message=login_form.errors)
五、实现多种登录方式
1、重写
authenticate
方法from django.contrib.auth.backends import ModelBackend from django.db.models import Q class CustomBackend(ModelBackend): """ 定义校验用户登录 """ def authenticate(self, request, username=None, password=None, **kwargs): try: user = models.UserProfileModel.objects.get(Q(username=username) | Q(email=username) | Q(mobile=username)) if user.check_password(password): return user except Exception as e: print(e) return None
2、在
settings.py
中配置自己定义的类# 配置用户认证的类 AUTHENTICATION_BACKENDS = ( 'users.views.login.CustomBackend', )