django并发请求有两个URL,每个URL的每个请求标头都不对

时间:2018-07-31 06:36:51

标签: django

并发请求带有两个URL的django应用程序,每个URL请求标头我给一个id,例如urla id = 1,urlb id = 2,但是当我从请求标头从django视图获取时,我从请求标头获取urla的id是2 ...太困惑了...柱子身体还可以

客户代码

#coding=utf-8
import threadpool

import requests

HOST = 'http://127.0.0.1:8000'
urls = ['/health', '/x2']
headers = {'Content-Type': 'application/json', 'HOST': 'xx.com'}

pool = threadpool.ThreadPool(5)

def request_api(n):
    url = urls[n%2]
    print('---------------------start request url {}'.format(url))
    headers.update(url=url)
    body = dict(
        url=url
    )
    r = requests.post(url=HOST + url, headers=headers, json=body)
    print(r.status_code)

reqs = threadpool.makeRequests(request_api, range(5))
[pool.putRequest(req) for req in reqs]
pool.wait()
print('over')

服务器代码

# coding=utf-8
from rest_framework.views import APIView
from django.http.response import HttpResponse


class ApiHealthCheck(APIView):
    def post(self, request, request_id='', **kwargs):
        print('api_health_check: {},{},{}'.format(request.path, request.META.get('HTTP_URL'), request.data))
        return HttpResponse("ok")


class ApiHealthCheck2(APIView):
    def post(self, request, request_id='', **kwargs):
        print('api_health_check2: {},{},{}'.format(request.path, request.META.get('HTTP_URL'), request.data))
        return HttpResponse("ok")

服务器打印

api_health_check: /health,/health,{u'url': u'/health'}
api_health_check2: /x2,/health,{u'url': u'/x2'}
api_health_check: /health,/health,{u'url': u'/health'}
api_health_check2: /x2,/x2,{u'url': u'/x2'}
api_health_check: /health,/health,{u'url': u'/health'}

注意其中之一有误,路径与META的内容不符,身体还可以

1 个答案:

答案 0 :(得分:0)

很抱歉,我找到了问题,不是Django问题,这是我的错。

headers = {'Content-Type': 'application/json', 'HOST': 'xx.com'}

headers是一个全局变量,并发请求可以并发修改此头,因此django请求,django获取错误的头