[python]django rest framework写POST和GET接口
版本声明
python3.6.5
Django-2.0.6
djangorestframework-3.8.2
mysqlclient-1.3.12
1.写一个登录接口,不多说,直接上代码
login_models.py
# -*- coding: utf-8 from django.db import models # Create your models here. # 用户表 class tbl_user(models.Model): user_name = models.TextField(max_length=10) email = models.TextField(max_length=50,default='') phone=models.CharField(max_length=11,default='') password=models.TextField(max_length=30,default='') token_value=models.TextField(max_length=100) status=models.CharField(max_length=100) creat_time = models.DateTimeField(auto_now_add=True) # desc排序数据 class Meta: ordering = ['-creat_time']
post请求
login_userIn.py
# coding:utf-8 import json from django.http import HttpResponse from rest_framework.views import APIView from ApiSoftware.loginApi.PublicParameters import meta_json_Response,_Response_public from ApiSoftware.modes import login_models from ApiSoftware.loginApi.PublicParameters import get_dates import time,datetime import hashlib class usr_login(APIView): # 定义请求方法为post,这种方法需要继承rest_framework的APIView def post(self,request): #初始化登录的model register_models = login_models # 取到request对象的body(json) parameter_json = request.body # json转字典 parameter = json.loads(parameter_json) #定义请求里的key get_phone = 'phone' get_password = 'password' #这是我写的一个方法用来把字典转成json的 get_json_Response = meta_json_Response() #这个是初始化一个公共类,后面无效参数都调用这里的一个无效参数的字典,然后再转json,返回给客户端 get_Response_public = _Response_public() # 如果定义的get_phone和get_password都在请求的json中忘下走 if get_phone in parameter and get_password in parameter: #取出其request.json中的phone和password phone=parameter[get_phone] password=parameter[get_password] # 如果phone和password都不为空 if phone and password: #通过在model创建用户表通过取出的手机号和密码模糊查询是否有这个手机号和对应的密码 inspect_phone = register_models.tbl_user.objects.filter(phone__contains=phone,password__contains=get_password) #判断inspect_phone是否为空 if inspect_phone: inspect=True else: inspect=False #如果用户表没有这个手机号,走正常登录逻辑 if inspect == True: #写一个方法通过sha256加密生成token def _token_value(value): hash = hashlib.sha256() hash.update(value.encode('utf-8')) return (hash.hexdigest()) #获取现在的时间转str nowTime_to_token = datetime.datetime.today() nowTime_to_token=str(nowTime_to_token) #定义原字符串是目前时间加上手机号和密码 get_user_str=str(phone+password+nowTime_to_token) #通过上面sha256加密原字符串 get_token=_token_value(get_user_str) # 根据请求的手机号密码查询出用户 inster_token = login_models.tbl_user.objects.filter(phone__contains=phone, password__contains=password) # 取出对象(查询到的用户数据),这个for可以不用因为唯一性的数据,直接索引,懒得改了 for value in inster_token: # value.token_value=get_token #把上面的加密的token保存到这个用户数据库token_value字段中 value.save() user_list = [] #取出对象(查询到的用户数据),这个for可以不用因为唯一性的数据,直接索引,懒得改了,其实上面已经取过了,懒得改 #想把用户名取出来返回出去 for users in inster_token: name_info=[users.user_name,users.token_value] user_list.append(name_info) usersInfo=user_list[0] # 返回字典 datas = { 'status': 'true', 'message': '登录成功!', 'name':usersInfo[0], 'token':get_token } # 字典转json返回给客户端 return HttpResponse(get_json_Response.json_Response(datas), content_type="application/json,charset=utf-8") # 异常情况 else: datas = { 'status': 'false', 'message': '手机号或密码不正确!', 'data': 'null' } return HttpResponse(get_json_Response.json_Response(datas), content_type="application/json,charset=utf-8") # 异常情况 公共方法 else: return HttpResponse(get_Response_public.InvalidParameter(), content_type="application/json,charset=utf-8") # 异常情况 公共方法 else: return HttpResponse(get_Response_public.InvalidParameter(), content_type="application/json,charset=utf-8")
1.1.设置路由
url.py
"""TestWebApi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from django.urls import path # import上面写的类 from ApiSoftware.loginApi.login_userIn import usr_login urlpatterns = [ path('admin/', admin.site.urls), url(r'login/userin/',usr_login().as_view()) #前面login/userin/自己定义访问路径,后面写类.as_view()
]
1.2启动服务python manage.py runserver127.0.0.1:8100 测试写的post接口,postman调试工具
请求ok
2.写一个GET接口(带key的请求)
get_Students.py
# coding:utf-8 import json from django.http import HttpResponse from rest_framework.views import APIView class getStudentDates(APIView): def json_Response(self,dict_va): respone_bodys=json.dumps(dict_va) return respone_bodys def get(self,request): # 取出url上sex和age参数的值 sex = request.GET.get('sex') age = request.GET.get('age') print(sex) print(age) # 取出请求header中heelo的key值 header_hello = request.META.get("HTTP_HELLO") print(header_hello) datas = { "status":"ok", "students":[{"name":"小张","age":"20"},{"name":"小王","sex":"22"}], "message":"查询成功" } return HttpResponse(self.json_Response(datas), content_type="application/json,charset=utf-8")
url.py
"""TestWebApi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from django.urls import path from ApiSoftware.loginApi.get_Students import getStudentDates urlpatterns = [ # 设置路由 url(r'alldata/getstudent',getStudentDates().as_view()), path('admin/', admin.site.urls), ]
这是GET请求的一种url带指定key请求的方式,这里需要主要的是 header_hello = request.META.get("HTTP_HELLO"),我们定义了请求的header中有个hello参数,但是取值需要加上 HTTP_ 这样的写法,并且,hello参数尽管定义的大写,但是这里取值必须得大写,否者会取不到,下面看下cmd请求下的print
E:\TestWebApi>python manage.py runserver 127.0.0.1:8100 Performing system checks... System check identified no issues (0 silenced). July 23, 2018 - 13:42:40 Django version 2.0.6, using settings 'TestWebApi.settings' Starting development server at http://127.0.0.1:8100/ Quit the server with CTRL-BREAK. 10 20 word [23/Jul/2018 13:42:43] "GET /alldata/getstudent?sex=10&age=20 HTTP/1.1" 200 147
可以看到请求的值我们都print出来了
下面是postman的请求
这样带参数的url请求就结束了,这里返回的学生信息,直接写死的,理论上可以用前面写的一篇序列化数据库查询出来的数据
3.写一个GET请求(不带Key的请求)
直接上代码~
getstudets_NOKEY.py
# coding:utf-8 import json from django.http import HttpResponse from rest_framework.views import APIView class getStudentDatesNokey(APIView): # 写一个转json的小方法 def json_Response(self,dict_va): respone_bodys=json.dumps(dict_va) return respone_bodys # 写get请求,定义url上两个参数 def get(self,request,param1,param2): # 打印这两个参数,判断是否获取到 print(param1) print(param2) #把获取的两个值放到dict, datas={ "key":param1, "key1":param2 } # 返回json return HttpResponse(self.json_Response(datas), content_type='application/json; charset=utf-8')
url.py 这里需要注意url有参数,所以定义url需要匹配后面的值
"""TestWebApi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from django.urls import path from ApiSoftware.loginApi.getstudets_NOKEY import getStudentDatesNokey urlpatterns = [ # plist后带两个参数用(.+)匹配任何字符除了/n url(r'plist/(.+)/(.+)/$', getStudentDatesNokey.as_view()), path('admin/', admin.site.urls), ]
这样算是写好了,然后python manage.py runserver 127.0.0.1:8100,可以看到请求时,print的参数
E:\TestWebApi>python manage.py runserver 127.0.0.1:8100 Performing system checks... System check identified no issues (0 silenced). July 23, 2018 - 18:47:37 Django version 2.0.6, using settings 'TestWebApi.settings' Starting development server at http://127.0.0.1:8100/ Quit the server with CTRL-BREAK. hello hello2 [23/Jul/2018 18:47:38] "GET /plist/hello/hello2/ HTTP/1.1" 200 34
最后,postman请求
终于写完拉~ 每次学完一些东西不记录,过两天又忘了,越往后学,这种情况越严重,所以记录每次学习的点点滴滴吧~ 若有理解错误的地方,多多指教~
下一篇会写一些django在linux上部署后端的一些文档~!