Django接收自定义httpheader过程详解-创新互联

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())

当前标题:Django接收自定义httpheader过程详解-创新互联
链接URL:http://ybzwz.com/article/gpcpg.html