gpt4 book ai didi

python - 坚持在Flask应用中实现Elasticsearch

转载 作者:行者123 更新时间:2023-12-03 00:45:48 26 4
gpt4 key购买 nike

我目前正在研究Flask Mega-Tutorial(第XVI部分),并且陷入了实现Elasticsearch的困境。具体来说,当从flask shell命令行运行以下命令时,出现此错误:

from app.search import add_to_index, remove_from_index, query_index
>>> for post in Post.query.all():
... add_to_index('posts', post)

AttributeError: module 'flask.app' has no attribute 'elasticsearch'

我应该提到的是,我没有实现上一课中的应用程序重组以使用蓝图。我的文件如下所示:

__init__.py:
#
from elasticsearch import Elasticsearch
app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \
if app.config['ELASTICSEARCH_URL'] else None

config.py:
class Config(object):
#
ELASTICSEARCH_URL = 'http://localhost:9200'

search.py​​:
from flask import app

def add_to_index(index, model):
if not app.elasticsearch:
return
payload = {}
for field in model.__searchable__:
payload[field] = getattr(model, field)
app.elasticsearch.index(index=index, id=model.id, body=payload)

def remove_from_index(index, model):
if not app.elasticsearch:
return
app.elasticsearch.delete(index=index, id=model.id)

def query_index(index, query, page, per_page):
if not app.elasticsearch:
return [], 0
search = app.elasticsearch.search(
index=index,
body={'query': {'multi_match': {'query': query, 'fields': ['*']}},
'from': (page - 1) * per_page, 'size': per_page})
ids = [int(hit['_id']) for hit in search['hits']['hits']]
return ids, search['hits']['total']['value']

我认为我没有将Elasticsearch正确导入到search.py​​中,但是由于上一课没有进行重组,因此我不确定如何表示它。有任何想法吗?

最佳答案

将其写入 search.py​​ 文件的正确方法应该是from flask import current_app

关于python - 坚持在Flask应用中实现Elasticsearch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61862069/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com