matt hoover
matt hoover

Reputation: 346

How do I run an instance of Elasticsearch from within a Flask python application?

I am trying create a server with an instance of Elasticsearch using the Flask python framework. I have the simple code below:

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)

However, I can only get the mainApp to connect to the Elasticsearch instance if I start it outside of my application (i.e. run it on localhost 9200). However, what I would like to have happen is that when I run app.py, both my Flask server and the Elasticsearch instance to which it is connected are created. How would I do this in python? Thanks in advance for any help.

Upvotes: 0

Views: 1378

Answers (1)

Mir Ilias
Mir Ilias

Reputation: 515

You should run elasticsearch's service first sudo service elasticsearch start and then serve your app

Upvotes: 2

Related Questions