-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplication.py
72 lines (56 loc) · 2.57 KB
/
application.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import flask
import flask_restful
import flask.ext.cors
from celery import Celery
from resources.analysis import AnalysisRes, AnalysisStatusRes
from resources.catchment import CatchmentListRes, CatchmentRes
from resources.dataimport import DataImportRes
import floodestimation
import floodestimation.loaders
import floodestimation.fehdata
from sqlalchemy import create_engine
from sqlalchemy.schema import MetaData
from sqlalchemy.orm import sessionmaker
class Application(object):
def __init__(self, settings):
self.flask_app = flask.Flask(__name__)
self.flask_app.config.from_object(settings)
flask.ext.cors.CORS(self.flask_app, resources=r'/api/*', allow_headers=['Content-Type', 'Authorization'],
expose_headers=['Location'])
self.rest_api = flask_restful.Api(self.flask_app)
self.db = floodestimation.db
self.db.engine = create_engine(self.flask_app.config['DATABASE_URL'])
self.db.metadata = MetaData(bind=self.db.engine, reflect=True)
self.db.Session = sessionmaker(bind=self.db.engine)
self._set_db_session()
self._set_routes()
def _set_routes(self):
self.rest_api.add_resource(AnalysisRes, '/api/v0/analyses/', endpoint='post_analysis')
self.rest_api.add_resource(AnalysisRes, '/api/v0/analyses/<task_id>', endpoint='get_analysis')
self.rest_api.add_resource(AnalysisStatusRes, '/api/v0/analysis-tasks/<task_id>', endpoint='analysis_status')
self.rest_api.add_resource(CatchmentListRes, '/api/v0/catchments/')
self.rest_api.add_resource(CatchmentRes, '/api/v0/catchments/<int:catchment_id>')
self.rest_api.add_resource(DataImportRes, '/api/v0/data-imports/')
def _set_db_session(self):
@self.flask_app.before_request
def before_request():
flask.g.db_session = self.db.Session()
@self.flask_app.teardown_request
def teardown_request(exception):
db_session = getattr(flask.g, 'db_session', None)
if db_session is not None:
db_session.close()
def celery(self):
app = self.flask_app
celery = Celery(app.import_name)
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery
def start_app(self):
self.flask_app.run()