首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Flask-使用蓝图缓存函数

Flask-使用蓝图缓存函数
EN

Stack Overflow用户
提问于 2021-02-16 22:35:24
回答 1查看 219关注 0票数 0

我正在做一个应用程序,我正在使用蓝图结构。我的代码运行正常,但我在尝试将flask-caching实现到一个函数中时遇到了这个错误。

返回的错误是: AttributeError:'Blueprint‘对象没有'cache’属性

有没有人在这里有一个解决方案,使缓存发生在这个函数上?

下面是我的一段代码:

代码语言:javascript
复制
from flask import render_template, redirect, request, Blueprint
from cache import store_weather, number_of_views, cached_weather, cache
import json, requests

bp = Blueprint('bp', __name__, url_prefix="/weather")
main = Blueprint('main', __name__)

api_key = "42fbb2fcc79717f7601238775a679328"

@main.route('/')
def hello():

    views = 5
    max_views = number_of_views()
    return render_template('index.html', cached_weather=cached_weather, max_views=max_views, views=views)


@bp.route('/', methods=['GET'])
def weather():

    clean_list_cache()

    if request.args.get('max').isdigit():
        views = int(request.args.get('max'))
    else:
        views = 5

    try:
        city_name = request.args.get('city')

        if city_name not in cached_weather:
            
            uri = 'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={key}'.format(city=city_name,key=api_key)
            # On that point, we bring the data from the Open Weather API
            rUrl = requests.get(uri)

            # The temperature of the Open Weather API is in Kelvin, so, we have to subtract 273.15 to transform
            # it into Celsius degrees
            temperature = str(round((json.loads(rUrl.content)['main'])['temp']-273.15))+" °C"
            name = json.loads(rUrl.content)['name']
            description = json.loads(rUrl.content)['weather'][0]['description']

            city_data = { "temp":temperature, "name":name, "desc":description }

            store_weather(city_data)

        max_views = number_of_views(views)

        return render_template('weather.html',  cached_weather = cached_weather, error_rec_city = False, max_views=max_views, views=views)

    except KeyError:
        max_views = number_of_views(views)
        return render_template('weather.html',  cached_weather=cached_weather, error_rec_city = True, max_views=max_views, views=views)


@bp.cache.cached(timeout=30, key_prefix='list_cache')
def clean_list_cache():
    cached_weather.clear()
EN

回答 1

Stack Overflow用户

发布于 2021-02-17 04:34:14

当您试图调用蓝图上的缓存时,就会出现这个错误:@bp.cache.cached。文档中有关如何使用缓存的示例如下:

代码语言:javascript
复制
@app.route("/")
@cache.cached(timeout=50)
def index():
    return render_template('index.html')

因此,您必须将缓存装饰器夹在应用程序装饰器和函数之间

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66226406

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档