request的用法

2022-02-17  本文已影响0人  草木山川
# 运行操作
@require_http_methods(["POST"])
def run_api(request):
    # 获取前端传入的参数,将字符串转化为json格式
    json_data = json.loads(request.body)
    # 定义返参
    response = {}
    try:
        # get()方法取到的值是字符串类型
        api_url = json_data.get('api_url')
        api_request_type = json_data.get('api_request_type')
        api_address = json_data.get('api_address')
        api_request_parameter_type = json_data.get('api_request_parameter_type')
        api_request_data = json_data.get('api_request_data')
        
        # host地址+接口地址构成请求地址
        url = api_url+api_address
        header = {'content-type': 'application/json', 'Authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjZiOTQyZDhlLWFmOTEtNDNhMC05OGE0LWExYjdhMjhlNmYwMiJ9.npUDE-TOmoR1sFn9fgVmy02ZQExIucUsTbEkJg3y7XzyL175hamHEAHyOLdOl7RG-LKpM07jW2kV9uibkmx5TQ'}
        if api_request_type == 'POST':
            # post请求时入参是json格式
            request_data = json.loads(api_request_data)
            res = requests.post(url=url, json=request_data, headers=header)
        elif api_request_type == 'GET':
            # get请求时入参是字符串格式,请求路径作一下拼接
            request_data = url+'?'+api_request_data
            res = requests.get(url=url, params=request_data, headers=header)
        elif api_request_type == 'PUT':
            # put请求时入参是json格式
            request_data = json.loads(api_request_data)
            res = requests.put(url=url, json=request_data, headers=header)
        elif api_request_type == 'DELETE':
            # delete请求时入参是json格式
            request_data = json.loads(api_request_data)
            res = requests.delete(url=url, json=request_data, headers=header)

        res2 = res.json()
        print(res.json())
        response['msg'] = res2['msg']
        response['code'] = res2['code']
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 900
    return JsonResponse(response)
上一篇 下一篇

猜你喜欢

热点阅读