1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Flask cache memoize not working with flask restful resources

Discussão em 'Python' iniciado por Stack, Dezembro 20, 2024.

  1. Stack

    Stack Membro Participativo

    flask_cache.Cache.memoize not working with flask_restful.Resource

    Here is sample code:

    from flask import Flask, request, jsonify
    from flask_restful import Resource, Api
    from flask_cache import Cache

    app = Flask(__name__)
    api = Api(app)
    cache = Cache(app, config={'CACHE_TYPE': 'simple'})


    class MyResource(Resource):
    JSONIFY = True
    PATH = None
    ENDPOINT = None

    def dispatch_request(self, *args, **kwargs):
    kw = dict(**kwargs)
    kw.update(request.args.items())
    r = super().dispatch_request(*args, **kw)
    if self.JSONIFY:
    return jsonify(r)
    else:
    return r


    class DebugResource(MyResource):
    PATH = '/debug'
    ENDPOINT = 'debug'

    @cache.memoize(timeout=30)
    def get(self, **kwargs):
    print('cache is not used!')
    return kwargs

    for r in [DebugResource]:
    api.add_resource(r, r.PATH, endpoint=r.ENDPOINT)


    print('running!')
    app.run()


    Notice that in get() I added print so I can see when the code is actually called and when cached value is used.

    I start server then in browser i go to http://localhost:5000/debug?a=1 and press f5 repeatetely. I expect that my function get is called once and then cached value is used. But in server console I see my print each time I press f5. So memoize is not working. What am I doing wrong?

    edit:

    I moved my cached function outside from Resource class

    @cache.memoize(timeout=30)
    def my_foo(a):
    print('cache is not used!')
    return dict(kw=a, id=id(a))

    class DebugResource(MyResource):
    PATH = '/debug'
    ENDPOINT = 'debug'

    def get(self, a):
    return my_foo(a)


    and that worked. As far as I can see, the issue was self argument that was actually unique in each call. The question is still, how to make it work without extracting additional function for each method i want to cache? Current solution looks like a workaround.

    Continue reading...

Compartilhe esta Página