知识为进步之母,而进步又为富强之源泉。这篇文章主要讲述Django REST Framework相关的知识,希望能为你提供帮助。
Django REST框架用于快速构建前后端分离的WebAPI的工具包。
简单使用
1.安装依赖
pip install djangorestframework
pip install markdown
pip install django-filter
2.创建Django项目
python manage.py startapp Rest
3.在 settings 中的 INSTALLED_APPS 添加 rest_framework
INSTALLED_APPS = [
django.contrib.admin,
django.contrib.auth,
django.contrib.contenttypes,
django.contrib.sessions,
django.contrib.messages,
django.contrib.staticfiles,
rest_framework# 增加
]
MIDDLEWARE = [
django.middleware.security.SecurityMiddleware,
django.contrib.sessions.middleware.SessionMiddleware,
django.middleware.common.CommonMiddleware,
#django.middleware.csrf.CsrfViewMiddleware,# 屏蔽
django.contrib.auth.middleware.AuthenticationMiddleware,
django.contrib.messages.middleware.MessageMiddleware,
django.middleware.clickjacking.XFrameOptionsMiddleware,
]
- views.py 文件,并添加如下代码:
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
# Create your views here.
class TestView(APIView):
# 构造函数
def dispatch(self, request, *args, **kwargs):
print("init")
return super().dispatch(request,*args,**kwargs)
def get(self,*args, **kwargs):
print("get ".format(kwargs))
return Response("get 请求")
def post(self, request, *args, **kwargs):
print("post ".format(request))
return Response(POST请求,响应内容)
def put(self, request, *args, **kwargs):
print("put 1")
return Response(put请求,响应内容)
5.在urls.py文件中添加想要访问的 url,并关联上述 views
from django.contrib import admin
from django.urls import path
from Rest import views
urlpatterns = [
path(admin/, admin.site.urls),
path(ruser/,views.TestView.as_view())
]
启动项目,访问?
?http://127.0.0.1:8000/user/?format=api?
?python manage.py runserver
通过?
?get方式?
?参数传递from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import JsonResponse
class TestView(APIView):
# 构造函数
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request,*args,**kwargs)
# 接收get方式参数传递
# http://127.0.0.1:8000/user/?format=api& color=red
def get(self,request, *args, **kwargs):
ret = "code":1001, "msg":"Get"
ref_data = https://www.songbingjia.com/android/request.query_params.dict()
print("获取参数传递: ".format(ref_data))
return JsonResponse(ret)
使用过滤器
1.安装依赖
pip install djangorestframework markdown django-filter
2.创建Django项目
python manage.py startapp rest
3.在 settings 中的 INSTALLED_APPS 添加 rest_framework
INSTALLED_APPS = [
rest_framework# 增加
rest
]
MIDDLEWARE = [
#django.middleware.csrf.CsrfViewMiddleware,# 屏蔽
]
APPEND_SLASH=False
在blog的models中,建立我们需要的model
from django.db import models
# Create your models here.
class UserInfo(models.Model):
USER_TYPE = (
(1,普通用户),
(2,VIP),
(3,SVIP)
)
user_type = models.IntegerField(choices=USER_TYPE,default=1)
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
class UserToken(models.Model):
user = models.OneToOneField(UserInfo,on_delete=models.CASCADE)
token = models.CharField(max_length=64)
建表
python .\\manage.py makemigrations
python .\\manage.py migrate
【Django REST Framework】urls.py增加路由
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from rest.views import AuthView
urlpatterns = [
path(admin/, admin.site.urls),
url(r^rest/v1/auth/$, AuthView.as_view())
]
增加views.py视图
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from django.views import View
from rest import models
import json
def md5(user):
import hashlib
import time
# 当前时间,相当于生成一个随机的字符串
ctime = str(time.time())
# token加密
m = hashlib.md5(bytes(user, encoding=utf-8))
m.update(bytes(ctime, encoding=utf-8))
return m.hexdigest()
class AuthView(View):
def get(self, request, *args, **kwargs):
ret = code: 1000, msg: success, name: 偷偷
ret = json.dumps(ret, ensure_ascii=False)
return HttpResponse(ret)
def post(self, request, *args, **kwargs):
ret = code: 1000, msg: None
try:
user = request.POST.get(username)
pwd = request.POST.get(password)
obj = models.UserInfo.objects.filter(username=user).first()
if not obj:
# 如果用户第一次登陆则创建用户
obj = models.UserInfo.objects.create(username=user, password=pwd)
ret[code] = 1001
ret[msg] = 创建用户成功
# 为用户创建token
token = md5(user)
# 存在就更新,不存在就创建
models.UserToken.objects.update_or_create(user=obj, defaults=token: token)
ret[token] = token
except Exception as e:
ret[code] = 1002
ret[msg] = 请求异常
return JsonResponse(ret)
版权声明:本博客文章与代码均为学习时整理的笔记,文章 [均为原创] 作品,转载请 [添加出处] ,您添加出处是我创作的动力!
推荐阅读
- Win10中如何枚举所有SSDT
- Bootstrap 常用框架的使用
- Flask与axios 前后端交互
- 操作系统开发(BIOS/MBR 编写开机引导)
- FPS游戏(D3D内部游戏菜单实现)
- Mac m1 Ubuntu里docker中安装mysql
- 40篇学完C语言——(第四篇)指针与地址
- 基于云服务MRS构建DolphinScheduler2调度系统
- Python 3的教程