烧瓶在请求操作之前和之后不起作用/打印任何内容



所以我有一个奇怪的错误,before和after操作不起作用。他们以前写过requests.log文件,但现在不起作用了,并且定期将语句打印到控制台也不起作用,我不知道为什么:


# function to handle bson type returned by mongodb
# taken from https://stackoverflow.com/a/18405626
def parse_json(data):
return json.loads(json_util.dumps(data))
app = flask.Flask(__name__)
api = Api(app)
#we will be logging the API end point that was accessed, the time it was accessed, and how long it took to address the request
#all logging will be to a local file, requests.log.
@app.before_request
def start_timer():
g.start = time.time()
@app.after_request
def log_request(response):
now = time.time()
duration = round(now - g.start, 2)
print(response.get_data())  #not working
f = open("requests.log", "a+")
f.write("testing") #also not working
f.write("The following request took ({}) seconds".format(duration)) #not working
f.write("n")
f.close()
print("dhefei") #not working
app.logger.info('Processing default request') #not working
print(request.url, request.remote_addr,file=sys.stderr)
return response

这些操作之外的任何打印语句都有效。

我测试了您的代码,看起来不错!但几乎没有更新。

from flask import g, request, Flask
import logging
import time
import sys

logging.basicConfig(
format='%(asctime)-15s %(levelname)-8s %(name)-1s: %(message)s',
level=logging.DEBUG)
logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
# function to handle bson type returned by mongodb
# taken from https://stackoverflow.com/a/18405626
def parse_json(data):
return json.loads(json_util.dumps(data))
app = Flask(__name__)
@app.route('/')
def hello_world():
time.sleep(4)
return 'Hello, World!'
@app.before_request
def start_timer():
g.start = time.time()
@app.after_request
def log_request(response):
now = time.time()
duration = round(now - g.start, 2)
logging.info(response.get_data())  #not working
logging.info("testing") #also not working
logging.info("The following request took ({}) seconds".format(duration)) #not working
logging.info("dhefei") #not working
logging.info('Processing default request') #not working
return response

if __name__ == '__main__':
app.run(host='localhost', port=9999)

控制台中:

python3 flaskapp.py
* Serving Flask app "flaskapp" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
2021-03-15 11:13:13,723 INFO     werkzeug:  * Running on http://localhost:9999/ (Press CTRL+C to quit)
2021-03-15 11:13:19,982 INFO     root: b'Hello, World!'
2021-03-15 11:13:19,982 INFO     root: testing
2021-03-15 11:13:19,983 INFO     root: The following request took (4.0) seconds
2021-03-15 11:13:19,983 INFO     root: dhefei
2021-03-15 11:13:19,983 INFO     root: Processing default request
2021-03-15 11:13:19,985 INFO     werkzeug: 127.0.0.1 - - [15/Mar/2021 11:13:19] "GET / HTTP/1.1" 200 -

最新更新