如何在Django中发出发布请求时动态传递标题?

时间:2019-04-23 07:02:38

标签: django

现在,我正在标题中编码令牌,它可以正常工作,但我不想对其进行编码。我想在邮递员中发出投递请求时通过。那么该怎么做。预先感谢。


def addtocart(request):
    payload = request.data
    headers = {"content-type":"application/json", "token": "tk_ju9fdm8e", "source":"android"}
    response = requests.post('http://api/cart/update/v2', 
    data=json.dumps(payload), headers=headers)
    return HttpResponse(response)

更新 答案

def addtocart(request):
     payload = request.data.copy()
     token = request.META.get('HTTP_TOKEN')
     headers = {"content-type":"application/json", "token": token, "source":"android"}
     response = requests.post('http://api/cart/update/v2', data=json.dumps(payload), headers=headers)
     return HttpResponse(response)

1 个答案:

答案 0 :(得分:0)

您可以解析request.data并插入headers字典中。

def addtocart(request):
    token = request.META.get("token", None)  # if django>= 2.2 , you can use request.headers.get("token", None)
    headers = {"content-type":"application/json", "token": token, "source":"android"}
    response = requests.post('http://api/cart/update/v2', 
    data=json.dumps(payload), headers=headers)
    return HttpResponse(response)