-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.py
More file actions
471 lines (395 loc) · 15.8 KB
/
app.py
File metadata and controls
471 lines (395 loc) · 15.8 KB
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
"""
Temporary notice:
Need help?
- Join the discord https://discord.com/invite/k37Ef6w
- Raise an issue https://github.com/shopyo/shopyo/issues/new/choose
- Mail maintainers https://github.com/shopyo/shopyo#-contact
Hope it helps! We welcome all questions and even requests for walkthroughs
"""
import importlib
import json
import os
import sys
import jinja2
from flask import Flask
from flask_admin import Admin
from flask_admin.menu import MenuLink
from flask_login import current_user
from shopyo.api.assets import get_static
from shopyo.api.assets import register_devstatic
from shopyo.api.debug import is_yo_debug
from shopyo.api.file import trycopy
import click
import sqlalchemy
base_path = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, base_path)
from config import app_config
# from init import db
from init import load_extensions
from init import modules_path
from init import installed_packages
from shopyo_admin import MyAdminIndexView
from shopyo_admin import DefaultModelView
from shopyo_settings.models import Settings
from shopyo_settings.helpers import set_setting as set_value
from init import db
from dotenv import load_dotenv
load_dotenv()
def create_app(config_name="development"):
global_template_variables = {}
global_configs = {}
app = Flask(
__name__,
instance_path=os.path.join(base_path, "instance"),
instance_relative_config=True,
)
load_plugins(app, global_template_variables, global_configs, config_name)
load_config_from_obj(app, config_name)
load_config_from_instance(app, config_name)
create_config_json()
load_config_json(app)
load_extensions(app)
from shopyo_base import ShopyoBase
from shopyo_auth import ShopyoAuth
from shopyo_appadmin import ShopyoAppAdmin
from shopyo_dashboard import ShopyoDashboard
from shopyo_page import ShopyoPage
from shopyo_i18n import Shopyoi18n
from shopyo_settings import ShopyoSettings
from shopyo_theme import ShopyoTheme
sh_base = ShopyoBase()
sh_auth = ShopyoAuth()
sh_appadmin = ShopyoAppAdmin()
sh_dashboard = ShopyoDashboard()
sh_page = ShopyoPage()
sh_i18n = Shopyoi18n()
sh_settings = ShopyoSettings()
sh_theme = ShopyoTheme()
sh_base.init_app(app)
sh_auth.init_app(app)
sh_appadmin.init_app(app)
sh_dashboard.init_app(app)
sh_page.init_app(app)
sh_i18n.init_app(app)
sh_settings.init_app(app)
sh_theme.init_app(app)
setup_flask_admin(app)
register_devstatic(app, modules_path)
load_blueprints(app, config_name, global_template_variables, global_configs)
setup_theme_paths(app)
inject_global_vars(app, global_template_variables)
sync_keyvalue_envvar(app)
custom_commands(db, app)
return app
def load_plugins(app, global_template_variables, global_configs, config_name):
for plugin in installed_packages:
if plugin not in ["shopyo_admin"]:
try:
mod = importlib.import_module(f"{plugin}.view")
app.register_blueprint(getattr(mod, f"{plugin}_blueprint"))
except AttributeError:
# print("[ ] Blueprint skipped:", e)
pass
# global's available everywhere template vars
try:
mod_global = importlib.import_module(f"{plugin}.global")
global_template_variables.update(mod_global.available_everywhere)
except ImportError as e:
if is_yo_debug():
print("[ ] Not loading template variable", e)
except AttributeError as e:
if is_yo_debug():
print("[ ] Not loading template variable", e)
# load configs
try:
mod_global = importlib.import_module(f"{plugin}.global")
if config_name in mod_global.configs:
global_configs.update(mod_global.configs.get(config_name))
except ImportError as e:
# print(f"[ ] {e}")
if is_yo_debug():
print("[ ] Not loading template variable", e)
except AttributeError as e:
# click.echo('info: config not found in global')
if is_yo_debug():
print("[ ] Not loading template variable", e)
def load_config_from_obj(app, config_name):
try:
configuration = app_config[config_name]
except KeyError as e:
print(
f"[ ] Invalid config name {e}. Available configurations are: "
f"{list(app_config.keys())}\n"
)
sys.exit(1)
app.config.from_object(configuration)
def load_config_from_instance(app, config_name):
if config_name != "testing":
# load the instance config, if it exists, when not testing
app.config.from_pyfile("config.py", silent=True)
# create empty instance folder and empty config if not present
try:
os.makedirs(app.instance_path)
with open(os.path.join(app.instance_path, "config.py"), "a"):
pass
except OSError:
pass
def create_config_json():
if not os.path.exists("config.json"):
trycopy("config_demo.json", "config.json")
def load_config_json(app):
config_path = os.path.join(app.config["BASE_DIR"], "config.json")
if os.path.exists(config_path):
with open(config_path) as f:
data = json.load(f)
app.config["SEED_SETTINGS"] = data.get("settings", {})
def setup_flask_admin(app):
admin = Admin(
app,
name="My App",
template_mode="bootstrap4",
index_view=MyAdminIndexView(),
)
admin.add_view(DefaultModelView(Settings, db.session))
admin.add_link(MenuLink(name="Logout", category="", url="/auth/logout?next=/admin"))
def load_blueprints(app, config_name, global_template_variables, global_configs):
"""
- Registers blueprints
- Adds global template objects from modules
- Adds global configs from modules
"""
for folder in os.listdir(os.path.join(base_path, "modules")):
if folder.startswith("__"): # ignore __pycache__
continue
if folder.startswith("box__"):
# boxes
for sub_folder in os.listdir(os.path.join(base_path, "modules", folder)):
if sub_folder.startswith("__"): # ignore __pycache__
continue
elif sub_folder.endswith(".json"): # box_info.json
continue
try:
sys_mod = importlib.import_module(
f"modules.{folder}.{sub_folder}.view"
)
app.register_blueprint(getattr(sys_mod, f"{sub_folder}_blueprint"))
except AttributeError:
pass
try:
mod_global = importlib.import_module(
f"modules.{folder}.{sub_folder}.global"
)
global_template_variables.update(mod_global.available_everywhere)
except ImportError as e:
if is_yo_debug():
print("[ ] skipped", e)
except AttributeError as e:
if is_yo_debug():
print("[ ] skipped", e)
# load configs
try:
mod_global = importlib.import_module(
f"modules.{folder}.{sub_folder}.global"
)
if config_name in mod_global.configs:
global_configs.update(mod_global.configs.get(config_name))
except ImportError as e:
if is_yo_debug():
print("[ ] skipped", e)
except AttributeError as e:
# click.echo('info: config not found in global')
if is_yo_debug():
print("[ ] skipped", e)
else:
# apps
try:
mod = importlib.import_module(f"modules.{folder}.view")
app.register_blueprint(getattr(mod, f"{folder}_blueprint"))
except AttributeError as e:
if is_yo_debug():
print("[ ] skipped", e)
# global's available everywhere template vars
try:
mod_global = importlib.import_module(f"modules.{folder}.global")
global_template_variables.update(mod_global.available_everywhere)
except ImportError as e:
# print(f"[ ] {e}")
if is_yo_debug():
print("[ ] skipped", e)
except AttributeError as e:
if is_yo_debug():
print("[ ] skipped", e)
# load configs
try:
mod_global = importlib.import_module(f"modules.{folder}.global")
if config_name in mod_global.configs:
global_configs.update(mod_global.configs.get(config_name))
except ImportError as e:
# print(f"[ ] {e}")
if is_yo_debug():
print("[ ] skipped", e)
except AttributeError as e:
# click.echo('info: config not found in global')
if is_yo_debug():
print("[ ] skipped", e)
app.config.update(**global_configs)
def setup_theme_paths(app):
with app.app_context():
front_theme_dir = os.path.join(
app.config["BASE_DIR"], "static", "themes", "front"
)
back_theme_dir = os.path.join(
app.config["BASE_DIR"], "static", "themes", "back"
)
loaders = [app.jinja_loader]
if os.path.exists(front_theme_dir):
loaders.append(jinja2.PrefixLoader({
name: jinja2.FileSystemLoader(os.path.join(front_theme_dir, name))
for name in os.listdir(front_theme_dir)
if os.path.isdir(os.path.join(front_theme_dir, name))
}))
if os.path.exists(back_theme_dir):
loaders.append(jinja2.PrefixLoader({
name: jinja2.FileSystemLoader(os.path.join(back_theme_dir, name))
for name in os.listdir(back_theme_dir)
if os.path.isdir(os.path.join(back_theme_dir, name))
}))
app.jinja_loader = jinja2.ChoiceLoader(loaders)
def inject_global_vars(app, global_template_variables):
@app.context_processor
def inject_global_vars():
import datetime
from flask_login import current_user
from shopyo.api.assets import get_static
from shopyo_theme.helpers import get_active_front_theme, get_active_back_theme
APP_NAME = os.environ.get('APP_NAME', 'PythonCMS')
def get_setting(env_var):
return os.environ.get(env_var)
def get_url_prefix(parts=None, as_str=False):
from flask import request
prefix = "/" + request.path.split("/")[1]
if parts == 1 and as_str:
return request.path
return prefix
def get_modules_info():
from shopyo.api.module import iter_modules
import json
modules_info = {}
for module_name, module_path in iter_modules(base_path):
info_path = os.path.join(module_path, "info.json")
if os.path.exists(info_path):
try:
with open(info_path) as f:
info = json.load(f)
mname = info.get("module_name")
if mname:
if "icons" not in info:
info["icons"] = {"fa": "", "boxicons": ""}
modules_info[mname] = info
except Exception:
pass
return modules_info
def get_content(type_name, limit=None, order='desc'):
from modules.contenttype.models import ContentType, ContentItem
ct = ContentType.query.filter_by(name=type_name).first()
if not ct:
return []
query = ContentItem.query.filter_by(content_type_id=ct.id)
if order == 'desc':
query = query.order_by(ContentItem.created_at.desc())
else:
query = query.order_by(ContentItem.created_at.asc())
if limit:
return query.limit(limit).all()
return query.all()
base_context = {
"APP_NAME": APP_NAME,
"OUR_APP_NAME": APP_NAME,
"current_year": datetime.datetime.now().year,
"len": len,
"current_user": current_user,
"get_static": get_static,
"get_setting": get_setting,
"get_value": get_setting,
"get_active_front_theme": get_active_front_theme,
"get_active_back_theme": get_active_back_theme,
"get_modules_info": get_modules_info,
"get_url_prefix": get_url_prefix,
"get_content": get_content
}
base_context.update(global_template_variables)
return base_context
def sync_keyvalue_envvar(app):
with app.app_context():
try:
set_value(
'ACTIVE_FRONT_THEME',os.environ.get('ACTIVE_FRONT_THEME', 'editorial')
)
set_value(
'ACTIVE_BACK_THEME',os.environ.get('ACTIVE_BACK_THEME', 'sneat')
)
set_value(
'SITE_TITLE',os.environ.get('SITE_TITLE', 'Site Info')
)
set_value(
'SITE_DESCRIPTION',os.environ.get('SITE_DESCRIPTION', 'Site Description')
)
set_value(
'APP_NAME',os.environ.get('APP_NAME', 'Default App Name')
)
set_value(
'ACTIVE_ICONSET',os.environ.get('ACTIVE_ICONSET', 'boxicons')
)
except sqlalchemy.exc.OperationalError as e: # on shopyo initialise command
if os.environ.get('FLASK_DEBUG', False):
print(e)
def custom_commands(db, app):
from flask.cli import with_appcontext
@click.command("shopyo-seed")
@with_appcontext
def shopyo_upload():
for ext in app.extensions:
if ext.startswith("shopyo_"):
try:
e = app.extensions[ext]
e.upload()
db.session.commit()
click.echo("Uploaded for " + ext)
except AttributeError as e:
pass
@click.command("update-password")
@click.argument("email")
@click.argument("password")
@with_appcontext
def update_password(email, password):
from shopyo_auth.models import User
user = User.query.filter_by(email=email).first()
if user:
user.password = password
db.session.commit()
click.echo(f"Password updated for {email}")
else:
click.echo(f"User {email} not found")
@click.command("add-user")
@click.argument("email")
@click.argument("password")
@click.option("--admin", is_flag=True, help="Create as admin")
@with_appcontext
def add_user(email, password, admin):
from shopyo_auth.models import User
user = User.query.filter_by(email=email).first()
if user:
click.echo(f"User {email} already exists")
else:
new_user = User()
new_user.email = email
new_user.password = password
new_user.is_email_confirmed = True
if admin:
new_user.is_admin = True
db.session.add(new_user)
db.session.commit()
click.echo(f"User {email} created")
app.cli.add_command(shopyo_upload)
app.cli.add_command(update_password)
app.cli.add_command(add_user)