【问题标题】:API serving up old responses in flaskAPI 在烧瓶中提供旧响应
【发布时间】:2017-11-01 07:33:20
【问题描述】:

我正在调用一个 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. 响应:“新消息日志文件成功!”使用 json 获取我指定的文件

  1. 响应:“日志文件成功!”这是上面python代码的旧版本!数据到达文件但没有时间戳,因为旧代码没有它

  1. “未找到服务器上未找到请求的 URL。如果您手动输入了 URL,请检查拼写并重试。”

  1. { "message": "Authenticate." } 这是我在另一个旧版本代码中的响应!

注意:如果我更改了代码,我会执行“gunicorn my-api:app”和nginx 重新启动,确保首先手动删除.pyc 文件

有人可以帮忙吗?它从哪里获得旧代码响应?为什么它是断断续续的,只是有时给我预期的新代码响应?

【问题讨论】:

    标签: python nginx gunicorn flask-restful


    【解决方案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
    

    【讨论】:

    • 这似乎是一个缓存问题 - 我尝试了这些标头,但我得到了这个错误 response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate' NameError : 未定义全局名称“响应”
    • 啊,是的,这只是一个示例代码...您应该针对您的用例专门处理它...我也用更通用的解决方案更新了我的答案...
    • 谢谢。我尝试了缓存修复的各种变体,但碰壁了,所以我去定义了一条新路由“my-api1”,它解决了“旧代码”问题。所以我现在得到了正确的回应。这是目前可行的解决方法。
    • @user3760188,如果此答案对您有帮助,请将其标记为该问题的解决方案
    【解决方案2】:

    使用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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-12
      • 2022-10-18
      • 1970-01-01
      • 2017-12-04
      • 2012-07-20
      • 1970-01-01
      • 2021-01-23
      相关资源
      最近更新 更多