我正在调用Flask api,由gunicorn运行,并且由nginx提供,所有这些都在linux box viretal env上提供
当我使用curl或postman测试时,每次运行时我会随机获得4个响应中的1个 - 但主要是响应2以下
这是我的烧瓶api py文件。我是新手,请原谅任何错误:
app = Flask(__name__)
now = datetime.now()
timestamp=str(now.strftime("%Y-%m-%d %H:%M"))
# assignes route for POSTING JSON requests
@app.route('/api/v1.0/my-api', methods=['POST'])
#@requires_auth
def runscope():
if request.method == 'POST':
in_json = request.json
in_json["api_datetime"] = timestamp
json_to_file(in_json)
return timestamp + "New msg log file success!"
# assigns route for the default GET request
@app.route('/')
def index():
return 'test on the index'
if __name__ == "__main__":
app.debug = True
application.run()
# function to drop request data to file
def json_to_file(runscope_json):
with open('data/data.json', 'a') as outfile:
json.dump(runscope_json, outfile, indent=2)
所以当我连续几次运行测试时
curl -H "Content-Type: application/json" -X POST -d '{"username":"xyz","password":"xyz"}' http://localhost:8000/api/v1.0/my-api
我得到了 1.响应:"新的msg日志文件成功!"随着json到达我指定的文件
OR
OR
OR
{ "message": "Authenticate." }
这是我在另一个OLD版本的代码中的回复!注意:我做了一个" gunicorn my-api:app
"如果我更改了代码,则nginx
重新启动,确保首先手动删除.pyc
文件
任何人都可以帮忙吗?它得到了旧的代码响应吗?为什么它是间歇性的,有时只给我预期的新代码响应?
答案 0 :(得分:1)
您是否尝试在回复中添加与缓存相关的标头?类似的东西:
# example code
@app.route('/api/v1.0/my-api', methods=['POST'])
def runscope():
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
# rest of the code...
针对特定的Flask路线...
或者如果要为所有请求禁用缓存:
# example code
@app.after_request
def add_header(response):
response.cache_control.max_age = 60
if 'Cache-Control' not in response.headers:
response.headers['Cache-Control'] = 'no-store'
return response
答案 1 :(得分:0)
使用Flask-Caching
https://flask-caching.readthedocs.io/en/latest/
pip install Flask-Caching
设置
缓存是通过缓存实例进行管理的:
from flask import Flask
from flask_caching import Cache
config = {
"DEBUG": True, # some Flask specific configs
"CACHE_TYPE": "simple", # Flask-Caching related configs
"CACHE_DEFAULT_TIMEOUT": 300
}
app = Flask(__name__)
# tell Flask to use the above defined config
app.config.from_mapping(config)
cache = Cache(app)
缓存视图功能
要缓存视图功能,您将使用cached()装饰器。默认情况下,此装饰器将对request_path使用cache_key:
@app.route("/")
@cache.cached(timeout=50)
def index():
return render_template('index.html')