-
Notifications
You must be signed in to change notification settings - Fork 2k
/
flask_app.py
81 lines (57 loc) · 2.26 KB
/
flask_app.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
72
73
74
75
76
77
78
79
80
81
# encoding: utf-8
from flask import Flask
from werkzeug.exceptions import HTTPException
from ckan.common import config
import logging
log = logging.getLogger(__name__)
def make_flask_stack(conf, **app_conf):
""" This has to pass the flask app through all the same middleware that
Pylons used """
app = flask_app = CKANFlask(__name__)
app.app_ctx_globals_class = CKAN_AppCtxGlobals
# Update Flask config with the CKAN values. We use the common config
# object as values might have been modified on `load_environment`
if config:
app.config.update(config)
else:
app.config.update(conf)
app.config.update(app_conf)
@app.route('/hello', methods=['GET'])
def hello_world():
return 'Hello World, this is served by Flask'
@app.route('/hello', methods=['POST'])
def hello_world_post():
return 'Hello World, this was posted to Flask'
# Add a reference to the actual Flask app so it's easier to access
app._wsgi_app = flask_app
return app
class CKAN_AppCtxGlobals(_AppCtxGlobals):
'''Custom Flask AppCtxGlobal class (flask.g).'''
def __getattr__(self, name):
'''
If flask.g doesn't have attribute `name`, fall back to CKAN's
app_globals object.
If the key is also not found in there, an AttributeError will be raised
'''
return getattr(app_globals.app_globals, name)
class CKANFlask(Flask):
'''Extend the Flask class with a special method called on incoming
requests by AskAppDispatcherMiddleware.
'''
app_name = 'flask_app'
def can_handle_request(self, environ):
'''
Decides whether it can handle a request with the Flask app by
matching the request environ against the route mapper
Returns (True, 'flask_app') if this is the case.
'''
# TODO: identify matching urls as core or extension. This will depend
# on how we setup routing in Flask
urls = self.url_map.bind_to_environ(environ)
try:
endpoint, args = urls.match()
log.debug('Flask route match, endpoint: {0}, args: {1}'.format(
endpoint, args))
return (True, self.app_name)
except HTTPException:
return (False, self.app_name)