[Python]django Rest Framework write post and get interface

Source: Internet
Author: User

Version Declaration

python3.6.5
Django-2.0.6
djangorestframework-3.8.2
mysqlclient-1.3.12

1. Write a login interface, not much to say, directly on the code

login_models.py

#-*-coding:utf-8from django.db import models# Create your models here.# User table 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 Sort Data    class Meta:        ordering = ['-creat_time ']

 

POST request

login_userin.py

# coding:utf-8import jsonfrom django.http import httpresponsefrom rest_framework.views import Apiviewfrom ApiSoftware.loginApi.PublicParameters Import meta_json_response,_response_publicfrom apisoftware.modes Import Login _modelsfrom ApiSoftware.loginApi.PublicParameters Import get_datesimport time,datetimeimport hashlibclass usr_login ( Apiview): # Defines the request method as post, this method needs to inherit Rest_framework's Apiview def Post (self,request): #初始化登录的model Register_model s = login_models # takes the body of the Request object (JSON) Parameter_json = request.body # JSON to dictionary parameter = Json.loads (Parameter_json) #定义请求里的key get_phone = ' phone ' get_password = ' password ' #这是我写的一个方法        The Get_json_response = Meta_json_response () #这个是初始化一个公共类 used to turn the dictionary into JSON, the invalid arguments are called here to the Dictionary of an invalid argument, and then to the JSON, back to the client Get_response_public = _response_public () # If the defined Get_phone and Get_password are left out of the requested JSON, if Get_phone in para Meter and Get_password in parameter: #取出其rEquest.json in the phone and password Phone=parameter[get_phone] Password=parameter[get_password] #                If phone and password are not empty 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 #如果用户表没有这个手机号, go to normal login logic if inspect = = True:                        #写一个方法通过sha256加密生成token def _token_value (value): hash = hashlib.sha256 () Hash.update (Value.encode (' Utf-8 ')) return (Hash.hexdigest ()) #获取 Now the time to turn str nowtime_to_token = Datetime.datetime.today () nowtime_to_token=str (nowtime_               To_token)     #定义原字符串是目前时间加上手机号和密码 get_user_str=str (Phone+password+nowtime_to_token) #通过上面sha                    256 Encrypt original string get_token=_token_value (GET_USER_STR) # Query the user based on the requested phone number password                    Inster_token = Login_models.tbl_user.objects.filter (Phone__contains=phone, Password__contains=password)                        # Take out the object (query to the user data), this for can not because of the uniqueness of the data, direct index, too lazy to change for the value in Inster_token: #                        Value.token_value=get_token #把上面的加密的token保存到这个用户数据库token_value字段中 Value.save () user_list = [] #取出对象 (query to the user data), this for can not because of the uniqueness of the data, direct index, too lazy to change, in fact, above have already taken, too lazy to change #想把用户名取出来返回出去 for the users in inster_token:name_info= [Users.user_name,users.token_value] User_list.append (name_info) usersinfo=user_l                  IST[0] # return Dictionary datas = {' status ': ' True ', ' message ': ' Login successful!                    ', ' name ': usersinfo[0], ' token ': Get_token}                                        # Dictionary to JSON back to client return HttpResponse (Get_json_response.json_response (datas),                    Content_type= "Application/json,charset=utf-8") # exception condition Else: Datas = {' status ': ' False ', ' message ': ' The phone number or password is incorrect! ', ' data ': ' null '} return HttpResponse (GET_JSON_RESPONSE.JSO  N_response (datas), content_type= "Application/json,charset=utf-8") # exception condition Public methods Else:return HttpResponse (Get_response_public. Invalidparameter (), content_type= "Application/json,charset=utf-8 ") # Exception Condition public method Else:return HttpResponse (get_response_public. Invalidparameter (), content_type= "Application/json,charset=utf-8")

1.1. Set up a route

url.py

]

1.2 Start the service Python manage.py runserver127.0.0.1:8100 test write the Post interface, Postman Debug tool

Request OK

2. Write a Get interface

It's Sunday, let's go to bed early tomorrow and write it down

[Python]django Rest Framework write post and get interface

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.