-
Notifications
You must be signed in to change notification settings - Fork 16
/
core.py
310 lines (247 loc) · 9.63 KB
/
core.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import os
import threading
import yaml
from flask import Flask
from flask_login import LoginManager
from flask_cors import CORS
from jinja2 import FileSystemLoader
from lxml import etree
from portality import settings, constants, datasets
from portality.bll import exceptions, DOAJ
from portality.error_handler import setup_error_logging
from portality.lib import es_data_mapping, dates, paths
from portality.ui.debug_toolbar import DoajDebugToolbar
import elasticsearch
login_manager = LoginManager()
@login_manager.user_loader
def load_account_for_login_manager(userid):
"""
~~LoginManager:Feature->Account:Model~~
:param userid:
:return:
"""
from portality import models
out = models.Account.pull(userid)
return out
def create_app():
"""
~~CreateApp:Framework->Flask:Technology~~
:return:
"""
app = Flask(__name__)
# ~~->AppSettings:Config~~
configure_app(app)
#~~->ErrorHandler:Feature~~
setup_error_logging(app)
#~~->Jinja2:Environment~~
setup_jinja(app)
#~~->CrossrefXML:Feature~~
app.config["LOAD_CROSSREF_THREAD"] = threading.Thread(target=load_crossref_schema, args=(app, ), daemon=True)
app.config["LOAD_CROSSREF_THREAD"].start()
#~~->LoginManager:Feature~~
login_manager.init_app(app)
#~~->CORS:Framework~~
CORS(app)
#~~->APM:Feature~~
initialise_apm(app)
#~~->DebugToolbar:Framework~~
DoajDebugToolbar(app)
#~~->ProxyFix:Framework~~
proxyfix(app)
#~~->CMS:Build~~
build_statics(app)
return app
##################################################
# Configure the App
def configure_app(app):
"""
Configure the DOAJ from:
a) the settings.py file
b) the <env>.cfg file
c) the local secrets config in app.cfg
Later imports have precedence, so e.g. app.cfg will override the same setting in production.cfg and settings.py.
"""
# import for settings.py
app.config.from_object(settings)
# import from <env>.cfg
proj_root = paths.get_project_root().as_posix()
app.config['DOAJENV'] = get_app_env(app)
config_path = os.path.join(proj_root, app.config['DOAJENV'] + '.cfg')
print('Running in ' + app.config['DOAJENV']) # the app.logger is not set up yet (?)
if os.path.exists(config_path):
app.config.from_pyfile(config_path)
print('Loaded environment config from ' + config_path)
# import from app.cfg
config_path = os.path.join(proj_root, 'app.cfg')
if os.path.exists(config_path):
app.config.from_pyfile(config_path)
print('Loaded secrets config from ' + config_path)
def get_app_env(app):
if not app.config.get('VALID_ENVIRONMENTS'):
raise Exception('VALID_ENVIRONMENTS must be set in the config. There shouldn\'t be a reason to change it in different set ups, or not have it.')
env = os.getenv('DOAJENV')
if not env:
envpath = paths.rel2abs(__file__, '../.env')
if os.path.exists(envpath):
with open(envpath, 'r') as f:
env = f.readline().strip()
if not env or env not in app.config['VALID_ENVIRONMENTS']:
raise Exception(
"""
Set the DOAJENV environment variable when running the app, guessing is futile and fraught with peril.
DOAJENV=test python portality/app.py
to run the app will do.
Or use the supervisord options - put this in the config: environment= DOAJENV="test" .
Finally, you can create a file called .env with the text e.g. 'dev' in the root of the repo.
Recommended only for dev environments so you don't have to bother specifying it each time you run a script or test.
Valid values are: {valid_doajenv_vals}
You can put environment-specific secret settings in <environment>.cfg , e.g. dev.cfg .
The environment specified in the DOAJENV environment variable will override that specified in the
application configuration (settings.py or app.cfg).
""".format(valid_doajenv_vals=', '.join(app.config['VALID_ENVIRONMENTS']))
)
return env
################################################
# Crossref setup
def load_crossref_schema(app):
"""
~~CrossrefXML:Feature->CrossrefXML:Schema~~
:param app:
:return:
"""
schema442_path = app.config["SCHEMAS"].get("crossref442")
schema531_path = app.config["SCHEMAS"].get("crossref531")
if not app.config.get("CROSSREF442_SCHEMA"):
path = schema442_path
try:
schema_doc = etree.parse(schema442_path)
schema = etree.XMLSchema(schema_doc)
app.config["CROSSREF442_SCHEMA"] = schema
except Exception as e:
raise exceptions.IngestException(
message="There was an error attempting to load schema from " + path, inner=e)
if not app.config.get("CROSSREF531_SCHEMA"):
path = schema531_path
try:
schema_doc = etree.parse(schema531_path)
schema = etree.XMLSchema(schema_doc)
app.config["CROSSREF531_SCHEMA"] = schema
except Exception as e:
raise exceptions.IngestException(
message="There was an error attempting to load schema from " + path, inner=e)
############################################
# Elasticsearch initialisation
def create_es_connection(app):
# ~~ElasticConnection:Framework->Elasticsearch:Technology~~
conn = elasticsearch.Elasticsearch(app.config['ELASTICSEARCH_HOSTS'], verify_certs=app.config.get("ELASTIC_SEARCH_VERIFY_CERTS", True))
return conn
def put_mappings(conn, mappings):
for key, mapping in iter(mappings.items()):
altered_key = app.config['ELASTIC_SEARCH_DB_PREFIX'] + key
if not conn.indices.exists(altered_key):
r = conn.indices.create(index=altered_key, body=mapping,
request_timeout=app.config.get("ES_SOCKET_TIMEOUT", None))
print("Creating ES Type + Mapping in index {0} for {1}; status: {2}".format(altered_key, key, r))
else:
print("ES Type + Mapping already exists in index {0} for {1}".format(altered_key, key))
def initialise_index(app, conn, only_mappings=None):
"""
~~InitialiseIndex:Framework->Elasticsearch:Technology~~
:param app:
:param conn:
:return:
"""
if not app.config['INITIALISE_INDEX']:
app.logger.warning('INITIALISE_INDEX config var is not True, initialise_index command cannot run')
return
if app.config.get("READ_ONLY_MODE", False) and app.config.get("SCRIPTS_READ_ONLY_MODE", False):
app.logger.warning("System is in READ-ONLY mode, initialise_index command cannot run")
return
# get the app mappings
mappings = es_data_mapping.get_mappings(app)
if only_mappings is not None:
mappings = {key:value for (key, value) in mappings.items() if key in only_mappings}
# Send the mappings to ES
put_mappings(conn, mappings)
##################################################
# APM
def initialise_apm(app):
"""
~~APM:Feature->ElasticAPM:Technology~~
:param app:
:return:
"""
if app.config.get('ENABLE_APM', False):
from elasticapm.contrib.flask import ElasticAPM
app.logger.info("Configuring Elastic APM")
apm = ElasticAPM(app, logging=True)
##################################################
# proxyfix
def proxyfix(app):
"""
~~ProxyFix:Framework~~
:param app:
:return:
"""
if app.config.get('PROXIED', False):
from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
##################################################
# Jinja2
def setup_jinja(app):
"""
Jinja2:Environment->Jinja2:Technology
:param app:
:return:
"""
'''Add jinja extensions and other init-time config as needed.'''
app.jinja_env.add_extension('jinja2.ext.do')
app.jinja_env.add_extension('jinja2.ext.loopcontrols')
app.jinja_env.globals['getattr'] = getattr
app.jinja_env.globals['type'] = type
#~~->Constants:Config~~
app.jinja_env.globals['constants'] = constants
#~~-> Dates:Library~~
app.jinja_env.globals['dates'] = dates
#~~->Datasets:Data~~
app.jinja_env.globals['datasets'] = datasets
# ~~->DOAJ:Service~~
app.jinja_env.globals['services'] = DOAJ
_load_data(app)
#~~->CMS:DataStore~~
app.jinja_env.loader = FileSystemLoader([app.config['BASE_FILE_PATH'] + '/templates',
os.path.dirname(app.config['BASE_FILE_PATH']) + '/cms/fragments'])
# a jinja filter that prints to the Flask log
def jinja_debug(text):
print(text)
return ''
app.jinja_env.filters['debug']=jinja_debug
def _load_data(app):
if not "data" in app.jinja_env.globals:
app.jinja_env.globals["data"] = {}
datadir = os.path.join(app.config["BASE_FILE_PATH"], "..", "cms", "data")
for datafile in os.listdir(datadir):
with open(os.path.join(datadir, datafile)) as f:
data = yaml.load(f, Loader=yaml.FullLoader)
dataname = datafile.split(".")[0]
dataname = dataname.replace("-", "_")
app.jinja_env.globals["data"][dataname] = data
##################################################
# Static Content
def build_statics(app):
"""
~~CMS:Build->CMSFragments:Build~~
~~->CMSSASS:Build~~
:param app:
:return:
"""
if not app.config.get("CMS_BUILD_ASSETS_ON_STARTUP", False):
return
from portality.cms import build_fragments, build_sass
base_path = paths.get_project_root().as_posix()
print("Compiling static content")
build_fragments.build(base_path)
print("Compiling main SASS")
build_sass.build(build_sass.MAIN_SETTINGS, base_path=base_path)
app = create_app()
es_connection = create_es_connection(app)