如何从Flask python应用程序中运行Elasticsearch实例?
我正在尝试使用Flask python框架创建一个带有Elasticsearch实例的服务器。我有下面的简单代码:如何从Flask python应用程序中运行Elasticsearch实例?,python,
elasticsearch,flask,Python,
elasticsearch,Flask,我正在尝试使用Flask python框架创建一个带有Elasticsearch实例的服务器。我有下面的简单代码: from flask import Flask, render_template from flask_bootstrap import Bootstrap from datetime import datetime from pyelasticsearch import ElasticSearch """ Insert some code here that creates/r
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from datetime import datetime
from pyelasticsearch import ElasticSearch
""" Insert some code here that creates/runs the Elasticsearch instance """
es = ElasticSearch('http://localhost:9200/')
doc = {
'author': 'kimchy',
'text': 'Elasticsearch: cool. bonsai cool.',
'timestamp': datetime(2010, 10, 10, 10, 10, 10)
}
es.index(index="test-index", doc_type='tweet', doc=doc,id=1,overwrite_existing=True)
def create_app():
app = Flask(__name__)
Bootstrap(app)
return app
mainApp = create_app()
@mainApp.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
mainApp.run(debug=True)
但是,如果在应用程序之外启动Elasticsearch实例(即在localhost 9200上运行),我只能让mainApp连接到Elasticsearch实例。然而,我希望发生的是,当我运行app.py时,我的Flask服务器和它所连接的Elasticsearch实例都被创建。在python中如何实现这一点?提前感谢您的帮助。您应该先运行elasticsearch的服务
sudo服务弹性搜索开始
然后为您的应用程序提供服务您正试图连接到本地主机上运行的ElasticsSearch实例。您确定服务器正在运行吗?Flask不应该设置elasticsearch可以使用的服务器吗?elasticsearch是一种类似于数据库(如MySQL)或缓存(如Memcached)的服务。您可以在本地或其他主机上运行它。一旦你让它运行在某个地方,你的Flask应用程序就可以连接到它。你现在有一个Elasticsearch实例在localhost上运行吗?在连接之前,您无法连接到它。