flask使用redis缓存小记:sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: t...

项目场景:

新手小白,flask项目使用redis缓存


问题描述

我的数据库配置写在config.py文件中,因此当我按照其它博客写时出现了问题,因为我原本的数据库配置找不到了
 

from flask_caching import Cache

cache = Cache()

config = {
    'CACHE_TYPE': 'redis',
    'CACHE_REDIS_HOST': '150.158.161.159',
    'CACHE_REDIS_PORT': 8090,
    'CACHE_REDIS_DB': '',
    'CACHE_REDIS_PASSWORD': 'Woaisumeijing'
}

app = Flask(__name__)

app.config.from_mapping(config)
db.init_app(app)
mail.init_app(app)
cache = Cache(app)

 

 解决:给config起个别的名字,就叫redis_config

from flask_caching import Cache

cache = Cache()

redis_config = {
    'CACHE_TYPE': 'redis',
    'CACHE_REDIS_HOST': '150.158.161.159',
    'CACHE_REDIS_PORT': 8090,
    'CACHE_REDIS_DB': '',
    'CACHE_REDIS_PASSWORD': 'Woaisumeijing'
}

app = Flask(__name__)

app.config.from_object(config)
app.config.from_mapping(redis_config)
db.init_app(app)
mail.init_app(app)
cache = Cache(app)

这样就能找到数据库了。

然后在视图函数中添加@cache装饰器

# 新闻情感分类
@app.route('/api/news/sentiment')
@cache.cached(timeout=50)
def sentiment_classify():
    # 使用senta模型
    senta = hub.Module(name="senta_bilstm")
    data = TestdataModel.query.all()
    content_list = []
    for i in data:
        content_list.append(i.content)
    input_dict = {"text": content_list}
    results = senta.sentiment_classify(data=input_dict)
    # 取各个文本的情感标签:0,1
    classify_results = []
    for result in results:
        classify_results.append(result['sentiment_label'])
    # 计算两种类别的数目
    classify_num = []
    num_0 = classify_results.count(0)
    num_1 = classify_results.count(1)
    classify_num.append({"value": num_0, "name": "negative"})
    classify_num.append({"value": num_1, "name": "positive"})
    return jsonify(classify_num)


你可能感兴趣的:(flask使用redis缓存小记:sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: t...)