No Description

__init__.py 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # -*- encoding: utf-8 -*-
  2. """
  3. License: MIT
  4. Copyright (c) 2019 - present AppSeed.us
  5. """
  6. from flask import Flask, url_for
  7. from flask_login import LoginManager
  8. from flask_sqlalchemy import SQLAlchemy
  9. from importlib import import_module
  10. from logging import basicConfig, DEBUG, getLogger, StreamHandler
  11. from os import path
  12. db = SQLAlchemy()
  13. login_manager = LoginManager()
  14. def register_extensions(app):
  15. db.init_app(app)
  16. login_manager.init_app(app)
  17. def register_blueprints(app):
  18. for module_name in ('base', 'home'):
  19. module = import_module('app.{}.routes'.format(module_name))
  20. app.register_blueprint(module.blueprint)
  21. def configure_database(app):
  22. @app.before_first_request
  23. def initialize_database():
  24. db.create_all()
  25. @app.teardown_request
  26. def shutdown_session(exception=None):
  27. db.session.remove()
  28. def configure_logs(app):
  29. # soft logging
  30. try:
  31. basicConfig(filename='error.log', level=DEBUG)
  32. logger = getLogger()
  33. logger.addHandler(StreamHandler())
  34. except:
  35. pass
  36. def apply_themes(app):
  37. """
  38. Add support for themes.
  39. If DEFAULT_THEME is set then all calls to
  40. url_for('static', filename='')
  41. will modfify the url to include the theme name
  42. The theme parameter can be set directly in url_for as well:
  43. ex. url_for('static', filename='', theme='')
  44. If the file cannot be found in the /static/<theme>/ location then
  45. the url will not be modified and the file is expected to be
  46. in the default /static/ location
  47. """
  48. @app.context_processor
  49. def override_url_for():
  50. return dict(url_for=_generate_url_for_theme)
  51. def _generate_url_for_theme(endpoint, **values):
  52. if endpoint.endswith('static'):
  53. themename = values.get('theme', None) or \
  54. app.config.get('DEFAULT_THEME', None)
  55. if themename:
  56. theme_file = "{}/{}".format(themename, values.get('filename', ''))
  57. if path.isfile(path.join(app.static_folder, theme_file)):
  58. values['filename'] = theme_file
  59. return url_for(endpoint, **values)
  60. def create_app(config, selenium=False):
  61. app = Flask(__name__, static_folder='base/static')
  62. app.config.from_object(config)
  63. if selenium:
  64. app.config['LOGIN_DISABLED'] = True
  65. register_extensions(app)
  66. register_blueprints(app)
  67. configure_database(app)
  68. configure_logs(app)
  69. apply_themes(app)
  70. return app