我最近设置了一个python flask服务器,它将托管家用流式摄像机,有点像安全摄像头。我想知道是否有可能使用python和flask来记录对服务器进行的所有连接。这将包括连接的日期,时间和IP。 如果我在python IDLE中运行烧瓶app,烧瓶会输出::
127.0.0.1 - - [08/Feb/2018 19:17:09] "GET / HTTP/1.1" 302 -
127.0.0.1 - - [08/Feb/2018 19:17:09] "GET /login HTTP/1.1" 200 -
127.0.0.1 - - [08/Feb/2018 19:17:13] "POST /login HTTP/1.1" 302 -
127.0.0.1 - - [08/Feb/2018 19:17:13] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [08/Feb/2018 19:17:13] "GET /fake.jpg HTTP/1.1" 404 -
我想知道是否可以将所有这些信息记录到日志文件中。
谢谢!
答案 0 :(得分:0)
这些消息是对服务器的请求,因此我非常确定Flask的Requests模块是您正在寻找的。 p>
只需在每个函数的开头保存Request对象(或您想要的属性),这是Flask路由(@app.route("XXX")
)
我用Flask应用程序做了一点测试,这就是我得到的:
<强>代码强>
from flask import request
@app.route('/')
def main():
print("HEHEHE: {}".format(request.headers))
@app.route('/getCharacters', methods=['GET'])
def getCharacters():
print("HIHIHII: {}".format(request.headers))
<强>结果强>
HEHEHE: Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
127.0.0.1 - - [09/Feb/2018 08:59:23] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [09/Feb/2018 08:59:23] "GET /static/css/style.css HTTP/1.1" 304 -
127.0.0.1 - - [09/Feb/2018 08:59:23] "GET /static/chart.min.js HTTP/1.1" 304 -
127.0.0.1 - - [09/Feb/2018 08:59:23] "GET /static/main.js HTTP/1.1" 304 -
127.0.0.1 - - [09/Feb/2018 08:59:23] "GET /static/assets/movies/lotr_logo.png HTTP/1.1" 304 -
127.0.0.1 - - [09/Feb/2018 08:59:23] "GET /static/assets/movies/sw_logo.png HTTP/1.1" 304 -
HIHIHII: Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: */*
Accept-Language: es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
Referer: http://localhost:8000/
Connection: keep-alive
127.0.0.1 - - [09/Feb/2018 09:00:49] "GET /getCharacters?movie=sw HTTP/1.1" 200 -
127.0.0.1 - - [09/Feb/2018 09:00:49] "GET /static/assets/pjs/sw/han.png HTTP/1.1" 304 -
127.0.0.1 - - [09/Feb/2018 09:00:49] "GET /static/assets/pjs/sw/vader.png HTTP/1.1" 304 -
127.0.0.1 - - [09/Feb/2018 09:00:49] "GET /static/assets/pjs/sw/threepio.png HTTP/1.1" 304 -
127.0.0.1 - - [09/Feb/2018 09:00:49] "GET /static/assets/pjs/sw/luke.png HTTP/1.1" 304 -
127.0.0.1 - - [09/Feb/2018 09:00:49] "GET /static/assets/pjs/sw/leia.png HTTP/1.1" 304 -