python: Use Djangorestframework write post and get interfaces

1, install django

pip install django

 

2, a new django project

python manage.py startproject cainiao_monitor_api

 

3, create a new app

python manage.py startapp monitor

 

4, installation DRF

pip install djangorestframework

 

5, the preparation of view function

views.py

from rest_framework.views Import APIView
 Import json
 Import cx_Oracle
 from django.http Import HttpResponse
 # the Create your views here Wallpaper. 


class MonitorMsg (APIView):
     # Here the method name can only post or get other names, the name is the type of interface 
    DEF post ( Self, request):
         "" " 
        this method is a POST request type, according urls.py configuration, the interface address: / monitorMsg 
        : param request: 
        : return: return all exception information table CAINIAO_MONITOR_MSG 
        " "" 
        SQL = ' SELECT * from CAINIAO_MONITOR_MSG ' 
        # connect to the database
        cx_Oracle.connect = conn ( ' name ' , ' pwd ' , ' 10 * * *:... 1521 / sid ' )
         # create a cursor 
        the Cursor = conn.cursor ()
         # execute sql statement 
        cursor.execute (sql)
         # submit data 
        conn.commit ()
         # Get query data type is list 
        data = cursor.fetchall ()
         # close the cursor 
        cursor.close ()
         # disconnect from the database 
        conn.Close ()
         # Create an empty list to put the data 
        msg_list =[]
         # Traversed query data 
        for I in Data:
             # Create an empty dictionary, stored corresponding to the field information 
            msg_dict = {}
             # query to the data as a value corresponding to the dictionary corresponding Key 
            msg_dict [ ' ID ' ] = I [ 0] 
            msg_dict [ ' scenario_code ' ] = I [. 1 ] 
            msg_dict [ ' MSG ' ] = I [2 ] 
            msg_dict [ ' Status ' ] = I [. 4 ]
             # traverses the data stored in the list
            msg_list.append (msg_dict)
         # define the final pattern data return 
        res_data = { ' COUNT ' : len (msg_list), ' Data ' : msg_list}
         # The res_data sequence into json object and return to 
        return the HttpResponse (json.dumps (res_data ), the content_type = " file application / JSON " )

 

6, the preparation route

urls.py

from django.contrib import admin
from django.urls import path
from monitor.views import MonitorMsg

urlpatterns = [
    path('admin/', admin.site.urls),
    # 接口的url:http://127.0.0.1:8000/monitorMsg
    path('monitorMsg', MonitorMsg.as_view()),
]

 

7, start the service

python manage.py runserver

 

8, test access

 

Guess you like

Origin www.cnblogs.com/gcgc/p/11541628.html