When we write code , We often use the method of separating the front end from the back end , For example, wechat applet , Android , Website, etc. …
that Python As a popular programming language , His built-in Django Framework is a good network framework , Can be used to build the back end , Interact with the front end . Now let's learn , How to use Python It's local requests request , And make... By request Django Help us solve some problems .
First, create a Django After the project , You will find that the official has already configured a lot of files for us . But these documents are still not enough , We need to create another one app. Then it can be directly at the terminal (terminal) Enter a line of instructions in .
python manage.py startapp api
After entering this line of instructions , We will find that , In our code, there is a called api Folder .
Now let's open up api Under folder views.py file . Then you can see that there is nothing in it .
Now let's write a simple interface . This interface is used to receive requests request , And returned after processing . His essence is a class. Let's write a simple demo, The code is as follows :
api/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
class demo(APIView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def post(self, request, *args, **kwargs):
print(request.data)
return Response({'message': True})
Let's take a look at the project file urls.py The meaning of this file is to configure the address of the web page and the interface content of the page .
from django.contrib import admin
from django.urls import path
from api import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', views.demo.as_view())
]
In this way , After we run django After the project , We can add... Directly after the port of the web address /login/, You can see us directly demo The interface of .
After writing the above section , We need to write one more thing , Otherwise our framework May not work properly . So let's find the... In the code setting.py. find INSTALLED_APPS.
After finding it, let's add the same parameter "rest_framework".
Now we're running Django Interface , But we didn't write the test part , So we're not sure if our code is correct .
The code is as follows :
import requests
url = 'http://127.0.0.1:8000/login/'
r = requests.post(url=url, data={'test': "heiheihei", 'mes':"666"})
ui = r.text
print(ui)
After running, we can see that a parameter is received locally {‘message’: True}. So our django and Python The local interaction is finished .