【问题标题】:Cache function or view?缓存功能还是视图?
【发布时间】:2022-01-08 14:23:09
【问题描述】:

我想将django-rest-framework 与缓存一起使用。

@cache_page(10 * 60)
@api_view(['GET'])
def get_num(request):
    if request.method == "GET":
        res = ["ok"]
        return Response(res)

效果很好。

所以实际上我想缓存的不是view,而是function

@cache_page(10 * 60)
def getCalc(num):
    return num * 10


@api_view(['GET'])
def get_num(request):
    if request.method == "GET":
        res = getCalc(request.query_params.get('num'))
        return Response(res)

出现错误TypeError: _wrapped_view() missing 1 required positional argument: 'request'

function可以使用缓存吗??

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    你可以使用cachetools

    @cachetools.func.ttl_cache(maxsize=10,ttl=10*6)
    def getCalc(num):
        return num * 10
    

    最大尺寸取决于您的要求。

    【讨论】:

    • 好答案。但是,请注意,这不会使用 Django 的缓存来存储缓存的值——它会将缓存的值作为 Python 对象存储在本地进程中。这意味着三件事:1)在不同的工作进程上调用这个函数不会共享一个缓存。 2)本地进程将使用更多内存进行缓存。 3) Cachetools 通常比 Django 的缓存框架更快,因为它不需要取消任何内容或通过网络加载任何内容。您可以在此处找到相关文档:docs.djangoproject.com/en/4.0/topics/cache
    • @Mahamudul Hasan 我可以用这个库和
    【解决方案2】:

    您可以向函数参数添加请求:

    @cache_page(10 * 60)
    def getCalc(request, num):
        return num * 10
    
    
    @api_view(['GET'])
    def get_num(request):
        if request.method == "GET":
            res = getCalc(request, request.query_params.get('num'))
            return Response(res)
    

    【讨论】:

      猜你喜欢
      • 2018-02-12
      • 2018-03-09
      • 2015-10-22
      • 1970-01-01
      • 2011-06-15
      • 1970-01-01
      • 2019-02-22
      • 2012-08-04
      • 1970-01-01
      相关资源
      最近更新 更多