Python 在 Flask 或 WSGI 中打印原始 HTTP 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25466904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print raw HTTP request in Flask or WSGI
提问by Sparrowcide
I am debugging a microcontroller I've built which is writing raw HTTP requests line by line. I am using Flask for my backend and I would like to see the entire request as it appears in this format:
我正在调试我构建的微控制器,它正在逐行写入原始 HTTP 请求。我将 Flask 用于我的后端,我想查看以这种格式显示的整个请求:
GET / HTTP/1.1
Content-length: 123
User-agent: blah
...
I know Flask is based on WSGI. Is there anyway to get this to work with Flask?
我知道 Flask 基于 WSGI。有没有办法让它与 Flask 一起使用?
采纳答案by jkysam
With flask you have access to the request object which contains all the HTTP details:
使用flask,您可以访问包含所有HTTP 详细信息的请求对象:
from flask import request
@app.route('/')
def index():
print request.headers
回答by Andrew Johnson
This doesn't use flask but it is fairly simple to setup a socket echo server.
这不使用烧瓶,但设置套接字回声服务器相当简单。
import socket
host = ''
port = 8888
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
while 1:
client, address = s.accept()
data = client.recv(size)
if data:
client.send(data)
client.close()
回答by Martijn Pieters
Yes, Flask is a WSGI application, so it is trivial to wrap your app in an extra layer that logs the request:
是的,Flask 是一个 WSGI 应用程序,因此将您的应用程序包装在一个记录请求的额外层中是微不足道的:
import pprint
class LoggingMiddleware(object):
def __init__(self, app):
self._app = app
def __call__(self, env, resp):
errorlog = env['wsgi.errors']
pprint.pprint(('REQUEST', env), stream=errorlog)
def log_response(status, headers, *args):
pprint.pprint(('RESPONSE', status, headers), stream=errorlog)
return resp(status, headers, *args)
return self._app(env, log_response)
This defines a piece of middleware to wrap your Flask application in. The advantage is that it operates entirely independent of Flask, giving you unfiltered insight into what goes in and what comes out.
这定义了一个中间件来包装您的 Flask 应用程序。优点是它完全独立于 Flask 运行,让您可以不加过滤地洞察进入和退出的内容。
How you apply the middleware depends on the exact WSGI server you are using; see your WSGI server documentation.
您如何应用中间件取决于您使用的确切 WSGI 服务器;请参阅您的 WSGI 服务器文档。
When running Flask with the built-in server (app.run()), do:
使用内置服务器 ( app.run())运行 Flask 时,请执行以下操作:
if __name__ == '__main__':
app.wsgi_app = LoggingMiddleware(app.wsgi_app)
app.run()
The little app.wsgi_appwrapping dance places the LoggingMiddlewarearound the Flask WSGI application.
小小的app.wsgi_app环绕舞LoggingMiddleware将 Flask WSGI 应用程序置于周围。
The output goes to the wsgi.errorstream; where that ends up again depends on your WSGI server; mod_wsgiputs this in the Apache error log for your site, the bundled Flask server prints this to stderr.
输出到wsgi.error流;最终的结果取决于您的 WSGI 服务器;mod_wsgi将此放入您站点的 Apache 错误日志中,捆绑的 Flask 服务器将其打印到stderr.
回答by Nava
suppose if you want complete details,
假设你想要完整的细节,
There is an another way
还有一种方法
@app.route('/')
def index():
print request.__dict__
#this prints all variables in `dict` format including `headers`
回答by geckos
Why not?
为什么不?
from flask import Flask, request
app = Flask(__name__)
@app.before_request
def log_request():
app.logger.debug("Request Headers %s", request.headers)
return None
# The remaining application code.
I've used the headers but you can use the same aproach to print any request attribute. The docs are here: http://flask.pocoo.org/docs/0.12/api/#flask.Request.
我使用了标头,但您可以使用相同的方法来打印任何请求属性。文档在这里:http: //flask.pocoo.org/docs/0.12/api/#flask.Request。
Also you need to setup FLASK_DEBUG=1 to Flask.logger.debug to work, what is nice since you can disable it in production.
您还需要将 FLASK_DEBUG=1 设置为 Flask.logger.debug 才能工作,这很好,因为您可以在生产中禁用它。
Regards,
问候,
回答by Sonic Soul
if you're using a logger i found this useful
如果您使用的是记录器,我发现这很有用
https://docs.python.org/3/library/pprint.html#pprint.pformat
https://docs.python.org/3/library/pprint.html#pprint.pformat
from pprint import pformat
import requests
log.debug(pformat(request.headers))

