注意,本应该是requests模块,为了区分,避免错误,用request
1、进入apps,创建request django-admin startapp request
2、因为只发送请求,没有数据库相关,不需要model。
3、进行序列化
from rest_framework import serializers
这里没u有进行引入ModeSer
class SingleRequestSerializer(serializers.Serializer):
method_choices = [
('get', 'get'),
('post', 'post'),
('delete', 'delete'),
('put', 'put'),
('patch', 'patch'),
]
url = serializers.CharField(help_text='url', label='url')
method = serializers.ChoiceField(choices=method_choices, help_text='请求方法', label='请求方法')
request = serializers.JSONField(help_text='请求参数', required=False, label='请求参数', default={})
def validate_request(self, value):
"""解决json数据为空的问题"""
if value.get('json') == {}:
value.pop('json')
return value
4views代码
from django.shortcuts import render
Create your views here.
import base64
import requests
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import SingleRequestSerializer
@api_view(http_method_names=['POST'])
def request_view(request, format=None):
1. 接受请求数据并校验
serializer = SingleRequestSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
2. 发送请求
data = serializer.validated_data
res = requests.request(method=data['method'], url=data['url'], **data['request'])
3. 组织响应数据并返回
res_data = {
'status_code': res.status_code,
'headers': dict(res.headers),
'cookies': dict(res.cookies)
}
content_type = res_data['headers'].get('Content-Type')
if content_type:
根据不同类型构造数据
if 'html' in content_type:
res_data['text'] = res.text
elif 'json' in content_type:
res_data['json'] = res.json()
else:
res_data['content'] = base64.b64encode(res.content).decode()
else:
res_data['content'] = base64.b64encode(res.content).decode()
return Response(res_data, status=200)
5、urls的代码
from django.urls import path
from .views import request_view
urlpatterns = [
path('', request_view, name='request')
]
6.进行调试