繁体   English   中英

如何获取 WSGI `environ` 字典的内容?

[英]How do I get the contents of the WSGI `environ` dictionary?

我只是在扩展 WSGI def application...示例,您可以在任何地方找到。 到目前为止,我还没有弄清楚如何返回environ字典的内容。

#import json

def application(environ, start_response):
  status = '200 OK'

  # The output must be a "sequence of byte string values," not a
  # string. See https://www.python.org/dev/peps/pep-3333/#a-note-on-string-types
  # and https://diveintopython3.net/strings.html#byte-arrays
  #output = b'Hello World!'          # Success!
  #output = str(environ)             # Nope
  #output = bytes(environ)           # Nope
  #output = bytes(str(environ))      # Nope
  #output = b'str(environ)'          # Nope, but eye-rollingly funny
  #
  #jsonEnviron = json.dumps(environ) # Nope - error says environ is of
  #output = bytes(jsonEnviron)       # Nope - type 'TextIOWrapper'

  response_headers = [('Content-type', 'text/plain'),
                      ('Content-Length', str(len(output))),
                      ('X-Clacks-Overhead', 'GNU Terry Pratchett')]

  start_response(status, response_headers)

  return [output]

如果解决方案就在那里,我的 Duck Duck Go 搜索没有找到它。

您不能简单地将bytes()用作字典,因为如果不以一种或另一种方式定义格式,就没有规范的二进制表示形式。

return [repr(environ).encode('utf-8')]

应该是一个好的开始。

正如您所说,WSGI 应用程序的返回值必须是一个可迭代的bytes es,如果您只想读取输出,那么 repr 与任何表示一样好。 对于机器使用,您可能需要json.dumps().encode()等。

在玩了一段时间@AKX的回答后,我去寻找一种方法来获取 POST 数据的调试输出并遇到了这个页面 几乎可以处理所有事情,并免费提供漂亮的印刷品! 所以,这是我的最终服务器测试/调试脚本:

from json import dumps
from os import path
from pprint import pformat
from urllib import parse

def application(environ, start_response):
  status = '200 OK'

  # show the environment:
  output = [b'<pre>']
  output.append(pformat(environ).encode('utf-8'))

  output.append(b'\n\nPATH_INFO: ' + environ['PATH_INFO'].encode('utf-8'))
  filepath, filename = path.split(environ['PATH_INFO'])
  filebase, fileext = path.splitext(filename)
  output.append(b'\nPath = ' + filepath.encode('utf-8'))
  output.append(b'\nFile = ' + filename.encode('utf-8'))
  output.append(b'\nFile Base = ' + filebase.encode('utf-8'))
  output.append(b'\nFile Ext = ' + fileext.encode('utf-8'))

  output.append(b'\n\nQUERY_STRING is\n' + environ['QUERY_STRING'].encode('utf-8'))
  queryDict = parse.parse_qs(environ['QUERY_STRING'])
  output.append(b'\n\nQUERY_STRING as a dict:\n')
  output.append(dumps(queryDict, sort_keys=True, indent=2).encode('utf-8'))

  output.append(b'</pre>')

  #create a simple form:
  output.append(b'\n\n<form method="post">')
  output.append(b'<input type="text" name="test">')
  output.append(b'<input type="submit">')
  output.append(b'</form>')

  if environ['REQUEST_METHOD'] == 'POST':
    # show form data as received by POST:
    output.append(b'\n\n<h1>FORM DATA</h1>')
    output.append(b'\n<pre>')
    output.append(pformat(environ['wsgi.input'].read()).encode('utf-8'))
    output.append(b'</pre>')

  # send results
  output_len = sum(len(line) for line in output)

  response_headers = [('Content-type', 'text/html'),
                      ('Content-Length', str(output_len)),
                      ('X-Clacks-Overhead', 'GNU Terry Pratchett')]

  start_response(status, response_headers)

  return output

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM