Django接收自定义http header过程详解


Posted in Python onAugust 23, 2019

add by zhj: Django将所有http header(包括你自定义的http header)都放在了HttpRequest.META这个Python标准字典中,当然HttpRequest.META

中还包含其它一些键值对,这些键值对是Django加进去的,如SERVER_PORT等。对于http header,Django进行了重命名,规则如下

(1) 所有header名大写,将连接符“-”改为下划线“_”

(2) 除CONTENT_TYPE和CONTENT_LENGTH,其它的header名称前加“HTTP_”前缀

参见 https://docs.djangoproject.com/en/1.6/ref/request-response/#django.http.HttpRequest.META

我个人比较喜欢跟踪源代码来查看,源代码如下,

class WSGIRequestHandler(BaseHTTPRequestHandler):

  server_version = "WSGIServer/" + __version__

  def get_environ(self):
    env = self.server.base_environ.copy()
    env['SERVER_PROTOCOL'] = self.request_version
    env['REQUEST_METHOD'] = self.command
    if '?' in self.path:
      path,query = self.path.split('?',1)
    else:
      path,query = self.path,''

    env['PATH_INFO'] = urllib.unquote(path)
    env['QUERY_STRING'] = query

    host = self.address_string()
    if host != self.client_address[0]:
      env['REMOTE_HOST'] = host
    env['REMOTE_ADDR'] = self.client_address[0]

    if self.headers.typeheader is None:
      env['CONTENT_TYPE'] = self.headers.type
    else:
      env['CONTENT_TYPE'] = self.headers.typeheader

    length = self.headers.getheader('content-length')
    if length:
      env['CONTENT_LENGTH'] = length

    for h in self.headers.headers:
      k,v = h.split(':',1)
      k=k.replace('-','_').upper(); v=v.strip()
      if k in env:
        continue          # skip content length, type,etc.
      if 'HTTP_'+k in env:
        env['HTTP_'+k] += ','+v   # comma-separate multiple headers
      else:
        env['HTTP_'+k] = v
    return env

  def get_stderr(self):
    return sys.stderr

  def handle(self):
    """Handle a single HTTP request"""

    self.raw_requestline = self.rfile.readline()
    if not self.parse_request(): # An error code has been sent, just exit
      return

    handler = ServerHandler(
      self.rfile, self.wfile, self.get_stderr(), self.get_environ()
    )
    handler.request_handler = self   # backpointer for logging
    handler.run(self.server.get_app())
class WSGIRequest(http.HttpRequest):
  def __init__(self, environ):
    script_name = base.get_script_name(environ)
    path_info = base.get_path_info(environ)
    if not path_info:
      # Sometimes PATH_INFO exists, but is empty (e.g. accessing
      # the SCRIPT_NAME URL without a trailing slash). We really need to
      # operate as if they'd requested '/'. Not amazingly nice to force
      # the path like this, but should be harmless.
      path_info = '/'
    self.environ = environ
    self.path_info = path_info
    self.path = '%s/%s' % (script_name.rstrip('/'), path_info.lstrip('/'))
    self.META = environ
    self.META['PATH_INFO'] = path_info
    self.META['SCRIPT_NAME'] = script_name
    self.method = environ['REQUEST_METHOD'].upper()
    _, content_params = self._parse_content_type(self.META.get('CONTENT_TYPE', ''))
    if 'charset' in content_params:
      try:
        codecs.lookup(content_params['charset'])
      except LookupError:
        pass
      else:
        self.encoding = content_params['charset']
    self._post_parse_error = False
    try:
      content_length = int(self.environ.get('CONTENT_LENGTH'))
    except (ValueError, TypeError):
      content_length = 0
    self._stream = LimitedStream(self.environ['wsgi.input'], content_length)
    self._read_started = False
    self.resolver_match = None

WSGIRequest类实例化方法__init__(self,environ)中第二个参数就是WSGIRequestHandler.get_environ()方法返回的数据

WSGIRequest.META在environ的基础上加了一些键值对

用Django做后台,客户端向Django请求数据,为了区分不同的请求,想把每个请求类别加在HTTP头部(headers)里面。

先做实验,就用Python的httplib库来做模拟客户端,参考网上写出模拟代码如下:

#coding=utf8
import httplib
httpClient = None
try:
  myheaders = { "category": "Books",
         "id": "21",
         'My-Agent': "Super brower"
       }
  httpClient = httplib.HTTPConnection('10.14.1XX.XXX',8086,timeout=30)
  httpClient.request('GET','/headinfo/',headers=myheaders)
  response = httpClient.getresponse()
  print response.status
  print response.reason
  print response.read()
except Exception, e:
  print e
finally:
  if httpClient:
    httpClient.close()

其中'/headinfo/'为服务器的响应目录。

然后是服务端的响应代码,《The Django Book》第七章有个获取META的例子:

# GOOD (VERSION 2)
def ua_display_good2(request):
  ua = request.META.get('HTTP_USER_AGENT', 'unknown')
  return HttpResponse("Your browser is %s" % ua)

正好看过这个例子,就模拟上面的这个写了一个能够返回客户端自定义头部的模块:

from django.http import HttpResponse
def headinfo(request):
  category = request.META.get('CATEGORY', 'unkown')
  id = request.META.get('ID','unkown')
  agent = request.META.get('MY-AGENT','unkown')
  html = "<html><body>Category is %s, id is %s, agent is %s</body></html>" % (category, id, agent)
  return HttpResponse(html)

运行结果如下:

$python get.py
#输出:
#200
#OK
#<html><body>Category is unkown, id is unkown, agent is unkown</body></html>

可以看到服务器成功响应了,但是却没有返回自定义的内容。

我以为是客户端模拟headers出问题了,查找和试验了许多次都没有返回正确的结果。后来去查Django的文档,发现了相关的描述:

HttpRequest.META

A standard Python dictionary containing all available HTTP headers. Available headers depend on the client and server, but here are some examples:

  • CONTENT_LENGTH ? the length of the request body (as a string).
  • CONTENT_TYPE ? the MIME type of the request body.
  • HTTP_ACCEPT_ENCODING ? Acceptable encodings for the response.
  • HTTP_ACCEPT_LANGUAGE ? Acceptable languages for the response.
  • HTTP_HOST ? The HTTP Host header sent by the client.
  • HTTP_REFERER ? The referring page, if any.
  • HTTP_USER_AGENT ? The client's user-agent string.
  • QUERY_STRING ? The query string, as a single (unparsed) string.
  • REMOTE_ADDR ? The IP address of the client.
  • REMOTE_HOST ? The hostname of the client.
  • REMOTE_USER ? The user authenticated by the Web server, if any.
  • REQUEST_METHOD ? A string such as "GET" or "POST".
  • SERVER_NAME ? The hostname of the server.
  • SERVER_PORT ? The port of the server (as a string).

With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted toMETA keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.

其中红色的部分说明是说除了两个特例之外,其他的头部在META字典中的key值都会被加上“HTTP_”的前缀,终于找到问题所在了,赶紧修改服务端代码:

category = request.META.get('HTTP_CATEGORY', 'unkown')
id = request.META.get('HTTP_ID','unkown')

果然,执行后返回了想要的结果:

$python get.py
#正确的输出:
#200
#OK
#<html><body>Category is Books, id is 21, agent is Super brower</body></html>

得到的经验就是遇到问题要多查文档,搜索引擎并不一定比文档更高效。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python打开url并按指定块读取网页内容的方法
Apr 29 Python
python实现在图片上画特定大小角度矩形框
Oct 24 Python
在mac下查找python包存放路径site-packages的实现方法
Nov 06 Python
Python中一般处理中文的几种方法
Mar 06 Python
python 实现将多条曲线画在一幅图上的方法
Jul 07 Python
Python实用库 PrettyTable 学习笔记
Aug 06 Python
djano一对一、多对多、分页实例代码
Aug 16 Python
python实现递归查找某个路径下所有文件中的中文字符
Aug 31 Python
使用python脚本自动创建pip.ini配置文件代码实例
Sep 20 Python
python3 pathlib库Path类方法总结
Dec 26 Python
Python 实现将数组/矩阵转换成Image类
Jan 09 Python
python 监控服务器是否有人远程登录(详细思路+代码)
Dec 18 Python
Python 处理文件的几种方式
Aug 23 #Python
python 数据生成excel导出(xlwt,wlsxwrite)代码实例
Aug 23 #Python
python @classmethod 的使用场合详解
Aug 23 #Python
python 一篇文章搞懂装饰器所有用法(建议收藏)
Aug 23 #Python
python 类的继承 实例方法.静态方法.类方法的代码解析
Aug 23 #Python
Python中最好用的命令行参数解析工具(argparse)
Aug 23 #Python
详解Python并发编程之创建多线程的几种方法
Aug 23 #Python
You might like
php daddslashes()和 saddslashes()有哪些区别分析
2012/10/26 PHP
ThinkPHP调试模式与日志记录概述
2014/08/22 PHP
PHP生成器简单实例
2015/05/13 PHP
ThinkPHP进程计数类Process用法实例详解
2015/09/25 PHP
PHP7之Mongodb API使用详解
2015/12/26 PHP
PHP异常处理定义与使用方法分析
2017/07/25 PHP
PHP实现单文件、多个单文件、多文件上传函数的封装示例
2019/09/02 PHP
Prototype中dom对象方法汇总
2008/09/17 Javascript
csdn 博客中实现运行代码功能实现
2009/08/29 Javascript
13个绚丽的Jquery 界面设计网站推荐
2010/09/28 Javascript
nodejs中exports与module.exports的区别详细介绍
2013/01/14 NodeJs
javascript中onclick(this)用法介绍
2013/04/19 Javascript
js获取当前页面路径示例讲解
2014/01/08 Javascript
JS实现slide文字框缩放伸展效果代码
2015/11/05 Javascript
JavaScript设计模式经典之命令模式
2016/02/24 Javascript
详解webpack es6 to es5支持配置
2017/05/04 Javascript
深入理解vue $refs的基本用法
2017/07/13 Javascript
webpack4 SplitChunks实现代码分隔详解
2019/05/23 Javascript
详解Python3.1版本带来的核心变化
2015/04/07 Python
Python使用bs4获取58同城城市分类的方法
2015/07/08 Python
Python 快速实现CLI 应用程序的脚手架
2017/12/05 Python
python画一个玫瑰和一个爱心
2020/08/18 Python
Python:合并两个numpy矩阵的实现
2019/12/02 Python
解决Tensorboard可视化错误:不显示数据 No scalar data was found
2020/02/15 Python
python 实现朴素贝叶斯算法的示例
2020/09/30 Python
Python通过fnmatch模块实现文件名匹配
2020/09/30 Python
澳大利亚波西米亚风连衣裙在线商店:Fortunate One
2019/04/01 全球购物
耐克奥地利官网:Nike奥地利
2019/08/16 全球购物
长曲棍球装备:Lacrosse Monkey
2020/12/02 全球购物
内科护士实习自我鉴定
2013/10/17 职场文书
正风肃纪剖析材料
2014/02/18 职场文书
班主任个人工作反思
2014/04/28 职场文书
统计学教授推荐信
2014/09/18 职场文书
2014年社区党建工作总结
2014/11/11 职场文书
学生会辞职信
2015/03/02 职场文书
厉害!这是Redis可视化工具最全的横向评测
2021/07/15 Redis