Beispiel #1
1
def create_app(config_name):
    app = Flask(config_name)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    Markdown(app)

    _dir = os.path.dirname(os.path.abspath(__file__))
    app.template_folder = os.path.join(_dir, "templates")
    app.static_folder = os.path.join(_dir, "static")

    return app
Beispiel #2
0
def create_app(source=None, config=None):    
    app = Flask("flaskrst")
    
    # Set default config values
    app.config.setdefault('MODULES', {})
    app.config.setdefault('STYLESHEETS', [])
    app.config.setdefault('FEEDS', [])
    
    # Load config
    if config:
        app.config.from_pyfile(config)
        config_loaded = True
    # maybe there is a file declared by env
    elif 'FLASK_RST_CONFIG' in os.environ:
        app.config.from_envvar('FLASK_RST_CONFIG')
        config_loaded = True
    # no config loaded try again later after source setting
    else:
        config_loaded = False
    
    # Set source path
    if source:
        app.config['SOURCE'] = source
    elif 'FLASK_RST_SOURCE' in os.environ:
        app.config['SOURCE'] = os.environ['FLASK_RST_SOURCE']
    else:
        # Use current working directory as source
        app.config['SOURCE'] = os.getcwd()
    
    # If no config already loaded than is a config maybe in source path
    if not config_loaded:
        config_path = os.path.join(app.config['SOURCE'], 'config.py')
        app.config.from_pyfile(config_path, silent=True)
    
    # Set path of static folder
    if 'STATIC_FOLDER' in app.config:
        app.static_folder = app.config['STATIC_FOLDER']
    else:
        # Is a static folder called _static in source path?
        source_static_folder = os.path.join(app.config['SOURCE'], "_static")
        if os.path.isdir(source_static_folder):
            app.static_folder = source_static_folder
    
    # Load flask-rst modules
    manager.init_app(app)
    manager.load_from_config()

    # Add some jinja globals and context processors
    app.jinja_env.globals['date'] = date
    app.context_processor(inject_navigation)
    
    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('404.html'), 404

    return app
Beispiel #3
0
def create_app(config=None):
  config = 'dev' if config is None else config

  app = Flask(__name__)
  app.config.from_object('main.config.' + config)

  # DB
  global db
  db = Connection(app.config['MONGO_HOST'], app.config['MONGO_PORT'])[app.config['MONGO_DB']]

  # Cache
  global cache
  cache = redis.Redis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT'], db=app.config['REDIS_DB'])

  # Static resources
  app.static_folder = app.config['STATIC_DIR']

  # Templating
  app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')


  from main.server.controllers import gui, api


  app.register_blueprint(gui.blueprint)
  app.register_blueprint(api.blueprint, url_prefix='/api')

  return app
Beispiel #4
0
def create_app(config_name):
    app = Flask(config_name)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    app_admin.init_app(app)
    babel.init_app(app)
    celery.init_app(app)
    bootstrap.init_app(app)

    db.init_app(app)
    with app.app_context():
        print current_app.name
        db.create_all()
    login_manager.init_app(app)

    app_admin.base_template = 'layout.html'

    from main import main as main_blueprint
    from admin import admin as admin_blueprint
    from auth import auth as auth_blueprint

    app.register_blueprint(main_blueprint)
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    import os.path

    _dir = os.path.dirname(os.path.abspath(__file__))
    app.template_folder = os.path.join(_dir, 'templates')
    app.static_folder = os.path.join(_dir, 'static')

    return app
Beispiel #5
0
def create_app(config=None):
  config = 'dev' if config is None else config

  app = Flask(__name__)
  app.config.from_object('glu.config.' + config)

  # Static content
  app.static_folder = app.config.get('STATIC_DIR', 'assets')

  # Use pyjade templates
  app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')

  # Cache
  global cache
  cache = redis.Redis(
      host=app.config['REDIS_HOST'],
      port=app.config['REDIS_PORT'])

  from glu.views.api import api
  from glu.views.site import site

  app.register_blueprint(site)
  app.register_blueprint(api, url_prefix='/api')

  return app
Beispiel #6
0
def create_app():
    app = Flask(
        __name__.split('.')[0],
        template_folder='../templates',
        static_url_path=None,
        static_folder=None
    )

    env = Development
    if os.environ.get('APPLICATION_ENV', '') == 'Production':
        env = Production

    app.config.from_object(env)

    # Load config items into jinja settings
    for key, val in app.config.items():
        if key.startswith('JINJA'):
            setattr(app.jinja_env, key[6:].lower(), val)

    register_controllers(app)
    register_errorhandlers(app)
    register_extensions(app)

    app.static_folder = '../public/'
    app.add_url_rule(app.config['STATIC_URL_PATH'] + '/<path:filename>',
                     endpoint='static',
                     view_func=app.send_static_file
                     )

    signal.signal(signal.SIGUSR1, sig_handler)
    signal.signal(signal.SIGUSR2, sig_handler)

    return app
Beispiel #7
0
def create_app(config=None):
    app = Flask(__name__, template_folder='views')
    app.static_folder = os.path.abspath('static')

    app.config.from_pyfile('configs/default.py')

    production_config = os.path.join(os.path.dirname(__file__), 'configs/production.py')
    if os.path.exists(production_config):
        app.config.from_pyfile(production_config)

    if isinstance(config, dict):
        app.config.update(config)
    elif config:
        app.config.from_pyfile(os.path.abspath(config))

    register_hook(app)
    register_celery(app)
    register_celery_beat(app)
    register_oauth(app)
    register_curator(app)
    register_jinja2(app)
    register_database(app)
    register_route(app)

    return app
Beispiel #8
0
def create_app(config=None):
    app = Flask(
        __name__,
        template_folder='templates')

    app.config.from_pyfile('_settings.py')

    if isinstance(config, dict):
        app.config.update(config)
    elif config:
        app.config.from_pyfile(os.path.abspath(config))

    app.static_folder = app.config.get('STATIC_FOLDER')
    app.config.update({'SITE_TIME': datetime.utcnow()})

    register_hooks(app)
    register_jinja(app)
    register_database(app)
    register_mail(app)
    register_admin(app)
    register_routes(app)
    register_whoosh(app)
    # register_babel(app)

    return app
Beispiel #9
0
def createApp():
    app = Flask(__name__, template_folder=config.TEMPLATE_FOLDER, static_folder=config.STATIC_FOLDER)

    app.config.from_object(config)
    app.template_folder = app.config['TEMPLATE_FOLDER']
    app.static_folder = app.config['STATIC_FOLDER']

    return app
Beispiel #10
0
    def watch(self):
        
        # Setup Flask app, which will be our dev server
        from flask import Flask

        server = Flask(__name__, static_folder="dist")
        server.static_folder = self.dist

        @server.route(self.url_prefix)
        def index():
            return server.send_static_file('index.html')

        @server.route('%s<path:path>' % self.url_prefix)
        def everything_else(path):

            # urls that end with a / are prolem index-wrapping
            if path.endswith("/"):
                path = "%sindex.html" % path

            try:
                # send_static_file will guess the correct MIME type
                return server.send_static_file(path)
            except NotFound:
                # If the file doesn't exist, assume it should
                # be an html file.
                return server.send_static_file("%s.html" % path)


        # Assign self to closure variable
        parent = self

        class RenderOnChangeHandler(FileSystemEventHandler):
            """
            Restart and when anything in src changes.
            """
            def on_modified(self, *args, **kwargs):
                parent.render()
                # Loading templates and classes over and over
                # causes gradual memory usage to creep up.
                # The garbage collector should fire every
                # after automatic renders to prevent this.
                gc.collect()
        
        # Setup observer
        logging.basicConfig(level=logging.INFO,
                            format='%(asctime)s - %(message)s',
                            datefmt='%Y-%m-%d %H:%M:%S')

        observer = Observer()
        observer.schedule(RenderOnChangeHandler(), self.src, recursive=True)
        observer.start()

        try:
            # Run Simple python server
            server.run()
        except KeyboardInterrupt:
            observer.stop()
        observer.join()
Beispiel #11
0
def create_app(config_name):
    app = Flask(__name__, static_url_path='')
    app.static_folder = 'static'
    app.template_folder = 'templates'
    config[config_name].init_app(app)
    app.config.from_object(config[config_name])
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.session_protection = 'basic'
    login_manager.login_view = 'user.login'
    principal.init_app(app)
    identity_config(app)
    toolbar.init_app(app)
    cdn.init_app(app)

    app.jinja_env.filters['date'] = date

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .user import user as user_blueprint
    app.register_blueprint(user_blueprint)

    from .vendor import vendor as vendor_blueprint
    app.register_blueprint(vendor_blueprint, url_prefix='/vendor')

    from .item import item as item_blueprint
    app.register_blueprint(item_blueprint, url_prefix='/item')

    from .distributor import distributor as distributor_blueprint
    app.register_blueprint(distributor_blueprint, url_prefix='/distributor')

    from .operation import operation as operation_blueprint
    app.register_blueprint(operation_blueprint, url_prefix='/operation')

    from .privilege import privilege as privilege_blueprint
    app.register_blueprint(privilege_blueprint, url_prefix='/privilege')

    from .service import service as service_blueprint
    app.register_blueprint(service_blueprint, url_prefix='/service')

    @app.after_request
    def set_csrf_token_cookie(response):
        csrf_token = getattr(request, 'csrf_token', None)
        if csrf_token is not None:
            response.set_cookie('csrf_token', csrf_token, max_age=3600)
        return response

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('user/404.html'), 404

    if config_name != 'testing':
        from app import statisitc
        with app.app_context():
            statisitc.init_statistic()

    return app
def create_app():
    ''' Create flask app.'''

    app = Flask(__name__)

    app.config.from_object(config)

    app.template_folder = app.config['TEMPLATE_FOLDER']
    app.static_folder = app.config['STATIC_FOLDER']

    return app
Beispiel #13
0
def create_app():
    select_default_settings()

    app = Flask(__name__)
    app.config.from_object(os.environ.get('MINIFICTION_SETTINGS'))

    default_handler.setLevel(app.config['LOGLEVEL'])
    logging.basicConfig(level=app.config['LOGLEVEL'], format=app.config['LOGFORMAT'])

    app.static_folder = app.config['STATIC_ROOT']
    app.extra_css = []
    app.extra_js = []

    if app.config['UMASK'] is not None:
        if isinstance(app.config['UMASK'], str):
            app.config['UMASK'] = int(app.config['UMASK'], 8)
        os.umask(app.config['UMASK'])

    if app.config['TESTING']:
        if not os.path.isdir(app.config['TESTING_DIRECTORY']):
            os.makedirs(app.config['TESTING_DIRECTORY'])
        elif os.listdir(app.config['TESTING_DIRECTORY']):
            raise RuntimeError('Testing directory %r is not empty' % app.config['TESTING_DIRECTORY'])

    init_bl()

    configure_user_agent(app)
    configure_i18n(app)
    configure_cache(app)
    configure_forms(app)
    configure_users(app)
    configure_error_handlers(app)
    configure_views(app)
    configure_admin_views(app)
    configure_ajax(app)
    configure_errorpages(app)
    configure_templates(app)
    if not app.config['SPHINX_DISABLED']:
        configure_search(app)
    configure_celery(app)
    configure_captcha(app)
    configure_story_voting(app)
    configure_misc(app)
    configure_development(app)
    configure_frontend(app)
    configure_sidebar(app)

    app.context_processor(templates_context)

    init_plugins(app)
    database.configure_for_app(app)

    return app
Beispiel #14
0
def create_app():
    """Create the Flask app."""

    app = Flask("modelconvert", static_folder=None)
    
    app.config.from_object('modelconvert.settings')
    app.config.from_envvar('MODELCONVERT_SETTINGS', silent=True)

    # configure custom static path for serving files during
    # development
    app.static_folder = app.config['STATIC_PATH']
    app.add_url_rule('/static/<path:filename>',
                      endpoint='static',
                      view_func=app.send_static_file)

    # custom template path, fall back to default
    jinja_loader = jinja2.ChoiceLoader([
        jinja2.FileSystemLoader(app.config['TEMPLATE_PATH']),
        app.jinja_loader,
    ])
    app.jinja_loader = jinja_loader


    configure_logging(app)

    app.register_blueprint(frontend)
    app.register_blueprint(api, url_prefix='/api')

    celery.add_defaults(app.config)

    # configure error handlers
    @app.errorhandler(403)
    def forbidden_page(error):
        return render_template("403.html"), 403

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template("404.html"), 404

    @app.errorhandler(500)
    def server_error_page(error):
        return render_template("500.html"), 500


    if app.config['DEBUG']:
        from werkzeug.wsgi import SharedDataMiddleware
        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
            '/preview': app.config["DOWNLOAD_PATH"]
        })

    return app
Beispiel #15
0
def create_app(config=None, app_name=None):
    if app_name is None:
        app_name = DEFAULT_APP_NAME

    app = Flask(app_name)

    app.template_folder = os.path.join(os.path.dirname(__file__), '_templates')
    app.static_folder = os.path.join(os.path.dirname(__file__), "_static")

    configure_app(app, config)
    configure_extensions(app)
    configure_template_filters(app)
    configure_blue_print(app, DEFAULT_BLUEPRINTS)

    return app
Beispiel #16
0
def create_app(config=None):
    app = Flask(__name__, template_folder='templates')
    app.config.from_pyfile('config.py')
    env = EnvConfig()
    env.init_app(app, 'BOOKMARKS_')
    if isinstance(config, dict):
        app.config.update(config)
    elif config:
        app.config.from_pyfile(os.path.realpath(config))
    app.static_folder = app.config.get('STATIC_FOLDER')

    register_exts(app)
    register_bps(app)

    return app
Beispiel #17
0
def create_app():
    app = Flask(__name__, template_folder='views')
    app.static_folder = os.path.abspath('public')

    app.config.from_pyfile('../config/default.py')

    register_database(app)
    register_csrf(app)
    register_jwt(app)
    register_socketio(app)
    register_routes(app)
    register_api(app)
    register_view_filters(app)
    reigster_not_found(app)

    return app
Beispiel #18
0
def create_app(config=None):
  config = 'dev' if config is None else config

  app = Flask(__name__)
  app.config.from_object('main.config.' + config)

  # Static resources
  app.static_folder = app.config['STATIC_DIR']

  # Templating
  app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')


  from main.server.controllers import gui, api

  app.register_blueprint(gui.blueprint)
  app.register_blueprint(api.blueprint, url_prefix='/api')

  return app
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # import and register main app
    from core import core
    app.register_blueprint(core)
    # ---

    # import and register packages
    # from packages.auth import auth
    # app.register_blueprint(main_blueprint)
    # ---
    
    # Set views folders
    app.template_folder = app.config['TEMPLATES_FOLDER']
    app.static_folder = app.config['STATIC_FOLDER']

    return app
Beispiel #20
0
def create_app(config=None):
    app = Flask(__name__, template_folder='templates',)

    app.config.from_pyfile('_settings.py')

    if 'ARCTIC_SETTINGS' in os.environ:
        app.config.from_envvar('ARCTIC_SETTINGS')

    if isinstance(config, dict):
        app.config.update(config)
    elif config:
        app.config.from_pyfile(os.path.abspath(config))

    app.static_folder = app.config.get('STATIC_FOLDER')
    app.config.update({'SITE_TIME': datetime.datetime.utcnow()})

    #register_jinja(app)
    #register_babel(app)
    register_routers(app)
    register_log(app)
    return app
Beispiel #21
0
def create_app(config=None):
    app = Flask(__name__)
    config = config or {}
    app.config.update(config)
    app.static_folder = app.config.get(keys.STATIC_FOLDER)
    app.api = get_api_instance(app.config)

    flask_gravatar.Gravatar(app)

    env = ViewEnvironment(app.api, app.config)
    app.register_blueprint(lang.create_blueprint(env), url_prefix='/lang')
    app.register_blueprint(auth.create_blueprint(env), url_prefix='/auth')
    app.register_blueprint(users.create_blueprint(env), url_prefix='/users')
    app.register_blueprint(games.create_blueprint(env), url_prefix='/games')
    app.register_blueprint(teams.create_blueprint(env), url_prefix='/teams')
    app.register_blueprint(notifications.create_blueprint(env), url_prefix='/notifications')

    create_logger(app)
    create_filters(app)
    create_bundles(app)
    create_main_views(app)
    initialize_cloudinary(app)

    return app
Beispiel #22
0
from flask import Flask
from promua_test_app.views import *
from flask_wtf import CsrfProtect

import __config as config

app = Flask(__name__)
# configure app
app.config.from_object(config)
# setup extensions
csrf_protect = CsrfProtect()
# init extensions
csrf_protect.init_app(app)
login_manager.init_app(app)
# setup static and templates
app.template_folder = "promua_test_app/templates"
app.static_folder = "promua_test_app/static"
# register handlers
app.before_request(before_request)
app.teardown_appcontext(teardown_app_context)
# register views
IndexView.register(app)
UserView.register(app)

if __name__ == '__main__':
    app.run()
Beispiel #23
0
    return render_template("photo_set.html", **context)


@app.route("/video/<slug>")
def video(slug):
    video = db.video_by_slug(slug)
    if not video:
        raise NotFound("No such video.")
    context = ctx.get_for_path(["Video", "All", video["title"]])
    context["video"] = video
    return render_template("video.html", **context)


# @app.route('/blog/', defaults = {'page':0})
# @app.route('/blog/<int:page>')
# def blog(page):
# 	page = page
# 	context = ctx.get_for_path(['Blog'])
# 	context['posts'] = db.get_blog_posts(skip=page*POSTS_PER_PAGE,size=POSTS_PER_PAGE)
# 	total_posts = db.get_total_blog_posts()
# 	if page > 0:
# 		context['prev_page'] = page-1
# 	if total_posts > (page+1)*POSTS_PER_PAGE:
# 		context['next_page'] = page+1
# 	return render_template('blog.html', **context)

if __name__ == "__main__":
    if not settings.DEBUG:
        app.static_folder = "assets"
    app.run(debug=settings.DEBUG)
Beispiel #24
0
    """
    Endpoint where sending chat messages which get passed into the database.
    :return: Either a generic 200 response or 401 depending on whether or not user is properly logged in.
    """
    if session and session["logged_in"]:
        username = session["username"]
        json_data = request.get_json()
        message = json_data["message"]
        m.store_message(username, message)
        okay = make_response("")
        return okay
    else:
        error = make_response("")
        error.data = "not allowed to send the message"
        error.status_code = 401
        return error


@app.route("/getmessages", methods=["GET"])
def get_messages():
    """
    Grab all the chat messages and send it back to the chat interface as json.
    :return: json chat messages
    """
    return jsonify({"messages": m.Messages})


if __name__ == "__main__":
    app.static_folder = "../static/"
    app.run("0.0.0.0", debug=True)
Beispiel #25
0
import zipfile
import re
from flask import Flask, jsonify, request
from flask.views import MethodView
from flasgger import Swagger


app = Flask(__name__, instance_relative_config=True)
app.config['GATLING_PATH'] = '/opt/gatling'
app.config['SIM_PATH'] = app.config['GATLING_PATH']+'/user-files/simulations/'
app.config['REPORT_PATH'] = app.config['GATLING_PATH']+'/results/'
app.config['TMP_PATH'] = ''
app.config['DEBUG'] = False
app.debug = app.config['DEBUG']
app.static_url_path = app.config['TMP_PATH']
app.static_folder = app.config['TMP_PATH']
app.config.from_envvar('CONFIG_FILE', silent=True)


_GATLING_PATH = app.config['GATLING_PATH']
_SIM_PATH = app.config['SIM_PATH']
_REPORT_PATH = app.config['REPORT_PATH']
_TMP_PATH = app.config['TMP_PATH']
app.config['SWAGGER'] = {
    "swagger_version": "2.0",
    # headers are optional, the following are default
    # "headers": [
    #     ('Access-Control-Allow-Origin', '*'),
    #     ('Access-Control-Allow-Headers', "Authorization, Content-Type"),
    #     ('Access-Control-Expose-Headers', "Authorization"),
    #     ('Access-Control-Allow-Methods', "GET, POST, PUT, DELETE, OPTIONS"),
Beispiel #26
0
    def wants_json(self):
        mimes = json_mimetypes
        mimes.append('text/html')
        best = self.accept_mimetypes.best_match(mimes)
        return best in json_mimetypes and \
            self.accept_mimetypes[best] > \
            self.accept_mimetypes['text/html']


app = Flask(__name__)
app.config.from_object(config)
app.request_class = JSONRequest
app.jinja_env.filters['datetime'] = format_datetime
app.jinja_env.filters['isodatetime'] = lambda d: d.isoformat() + 'Z'
app.jinja_env.filters['format_currency'] = format_currency
app.static_folder = 'static'

redis_conn = redis.from_url(app.config['REDIS_URL'])
app.session_interface = session.RedisSessionInterface(redis_conn)

csrf = SeaSurf(app)
db = SQLAlchemy(app)
migrate = Migrate(app, db)

login_manager = LoginManager()
login_manager.login_view = "auth.login"
login_manager.init_app(app)

from wuvt import admin
app.register_blueprint(admin.bp, url_prefix='/admin')
Beispiel #27
0
from flask import Flask
from core.services import postgres

# blueprints
from web_client import web_client
from identity import identity
from authentication import authentication
from authorization import authorization

# app
app = Flask(__name__)

# file storage
app.static_folder = '../../client/static'
app.template_folder = '../../client/templates'

# config
app.config.from_object('core.config.default')
# app.config.from_object('core.config.development')
# app.config.from_object('core.config.production')

# services
postgres.app = app
postgres.init_app(app)

# blueprints
app.register_blueprint(web_client)
app.register_blueprint(identity, url_prefix='/api')
app.register_blueprint(authentication, url_prefix='/api')
app.register_blueprint(authorization, url_prefix='/api')
Beispiel #28
0
import os

from flask import Flask, jsonify, abort, make_response, render_template
from flask_httpauth import HTTPBasicAuth

app = Flask(__name__, static_url_path="")   # pylint: disable=invalid-name
app.config.from_object("config")
app.debug = True
auth = HTTPBasicAuth()  # pylint: disable=invalid-name

# This is the path to the upload directory
app.config["UPLOAD_FOLDER"] = "uploads"
# These are the extension that we are accepting to be uploaded
app.config["ALLOWED_EXTENSIONS"] = set(["txt", "pdf", "png", "jpg", "jpeg", "gif", "py"])
# create upload folder if not exist
if not os.path.exists(app.config["UPLOAD_FOLDER"]):
    os.makedirs(app.config["UPLOAD_FOLDER"])

# redefine jinja start/end string to avoid conflict with AngularJS
app.jinja_env.variable_start_string = "{[{ "
app.jinja_env.variable_end_string = " }]}"

# use different static/templates folder with different mode
if not app.debug:
    app.template_folder = "build/templates"
    app.static_folder = "build/static"
else:
    app.template_folder = "src/templates"
    app.static_folder = "src/static"
    
Beispiel #29
0
			flash("<b>Invalid login details!</b>", "danger")
	else:
		referrer = request.referrer or url_for("index")
	return render_template("login.html", referrer=referrer)

@app.route('/logout')
def logout():
	session.pop('user', None)
	return redirect(request.referrer or url_for("index"))


@app.context_processor
def register_helpers():
	return {
		"is_authorized_for": lambda owner: is_authorized(owner, session)
	}


if not os.path.isfile("/var/lib/ffmap/secret_key"):
	open("/var/lib/ffmap/secret_key", "wb").write(os.urandom(24))
	os.chmod("/var/lib/ffmap/secret_key", 0o600)

app.secret_key = open("/var/lib/ffmap/secret_key", "rb").read()

if __name__ == '__main__':
	app.run(host='0.0.0.0', debug=True)
else:
	app.template_folder = "/usr/share/ffmap/templates"
	app.static_folder = "/usr/share/ffmap/static"
	#app.debug = True
Beispiel #30
0
import os
import xbmcaddon
from flask import Flask

__addonpath__ = xbmcaddon.Addon(id="script.webui").getAddonInfo("path")
app = Flask(__name__)

app.root_path = __addonpath__
app.static_path = "/static"
app.static_folder = os.path.join(__addonpath__, "resources", "static")
app.template_folder = os.path.join(__addonpath__, "resources", "templates")
app.add_url_rule(app.static_path + "/<path:filename>", endpoint="static", view_func=app.send_static_file)

from jinja2 import FileSystemLoader

app.jinja_loader = FileSystemLoader(os.path.join(__addonpath__, "resources", "templates"))