RestfulAPI使用举例

RestfulAPI使用举例

1、创建django项目testRestfulAPI

复制代码

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
url(r’^admin/’, admin.site.urls),
url(r’^asset/’, views.AssetView.as_view()),
]

复制代码

from django.shortcuts import HttpResponse
from django.views import View
import json

class AssetView(View):
def get(self,request): # 返回查询信息
print(‘response_select’,request.META.get(‘HTTP_HOSTNAME’)) # c1.com
return HttpResponse(json.dumps({‘status’:‘ok’,‘method’:‘select’}))
def post(self,request):              # 创建
    print('response_create',request.body)     # {"hostname": "c1.com"}
    return HttpResponse(json.dumps({'status':'ok','method':'create'}))

def put(self,request):              # 更新
    print('response_update',request.body)     # {"hostname": "c1.com"}
    return HttpResponse(json.dumps({'status':'ok','method':'update'}))

def delete(self,request):          # 删除
    print('response_delete',request.body)     # {"hostname": "c1.com"}
    return HttpResponse(json.dumps({'status':'ok','method':'delete'}))

2、创建文件test.py使用requests模块模拟增删改查(注释服务器端csrf)

复制代码
import requests

2.1、查询

response_select = requests.get(‘http://127.0.0.1:8000/asset/’,
headers={‘hostname’:‘c1.com’},
)
print(‘response_select’,response_select.json()) # {‘method’: ‘select’, ‘status’: ‘ok’}

2.2、创建

response_create = requests.post(‘http://127.0.0.1:8000/asset/’,
headers=’’,
json={‘hostname’:‘c1.com’}
)
print(‘response_create’,response_create.json()) # {‘status’: ‘ok’, ‘method’: ‘create’}

2.3、更新

response_put = requests.put(‘http://127.0.0.1:8000/asset/’,
headers=’’,
json={‘hostname’:‘c1.com’}
)
print(‘response_update’,response_put.json()) # {‘method’: ‘update’, ‘status’: ‘ok’}

2.4、删除

response_delete = requests.delete(‘http://127.0.0.1:8000/asset/’,
headers=’’,
json={‘hostname’:‘c1.com’}
)
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页