首页 > 解决方案 > django并发请求两个url,每个请求头对每个url都是错误的

问题描述

并发请求具有两个 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 的内容不匹配,body 是好的

标签: django

解决方案


对不起,我发现了问题,不是django的问题,是我的错。

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

headers是全局变量,并发请求可以并发修改这个header,所以请求django,django得到错误的header


推荐阅读