Exemple #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
Exemple #2
0
def create_app(config_type):
    # 根据配置类型取出配置类
    config_class = config_dict[config_type]
    app = Flask(__name__)

    app.config.from_object(config_class)
    app.template_folder = '../templates'
    app.config['JSON_AS_ASCII'] = False

    global db

    db = SQLAlchemy(app)

    Migrate(app, db)

    from SPA_back.src.py.services.DataService import data_blue
    app.register_blueprint(data_blue)

    @app.errorhandler(404)
    def page_not_found(e):
        return jsonify({"code": "404", "message": str(e)})

    # CSRFProtect(app)
    CORS(app, supports_credentials=True)

    from SPA_back.src.py.services.DataService import models

    return app
Exemple #3
0
def create_app():
    app = Flask(__name__)

    app.config.from_object(config)

    db.init_app(app)
    lm.init_app(app)

    # Register routes
    from microcenter.views.anonymous import anonymous_bp
    app.register_blueprint(anonymous_bp)
    from microcenter.views.associate import associate_bp
    app.register_blueprint(associate_bp, url_prefix='/a')
    from microcenter.views.manager import manager_bp
    app.register_blueprint(manager_bp, url_prefix='/m')

    # Prepare assets directory
    app.template_folder = '../templates'
    app.static_folder = '../static'

    # Prepare database
    with app.app_context():
        db.create_all()

    # Prepare login manager
    lm.login_view = 'anonymous.signin'

    return app
Exemple #4
0
def serve_static(app: Flask):
    """
    Create an app that is responsible to serve static resources.
    """
    cur_dir = os.path.abspath(os.path.dirname(__file__))
    ui_dir = app.config.get("UI_ASSETS_DIR", "")

    # did we gete a specific location?
    if not ui_dir and not os.path.isdir(ui_dir):
        # maybe its an installed with the chaoshubdashboard package?
        ui_dir = os.path.join(cur_dir, 'ui')

    # assume development mode
    if not ui_dir or not os.path.isdir(ui_dir):
        ui_dir = os.path.join(cur_dir, '..', '..', 'ui', 'dist')

    if not os.path.isdir(ui_dir):
        raise RuntimeError(
            "Cannot find your static resources (html, img, css...). "
            "Please set the UI_ASSETS_DIR environment variable to point "
            "where they are located.")

    app.logger.info("Serving static files from {}".format(ui_dir))
    app.template_folder = ui_dir
    cherrypy.tree.mount(
        None, "/static", {
            "/": {
                "tools.staticdir.on": True,
                "tools.staticdir.dir": os.path.join(ui_dir, 'static')
            }
        })
Exemple #5
0
def factory(fn, app_name, config={}):
    """ Create a flask/sockeio app instance and set some default configs
        Params:
            fn:
            name:
            cors:
            templete_folder:
            has_socket:
    """
    global app, socketio
    app = Flask(app_name)
    CORS(app, resources={json.dumps(cors_default)})
    # TODO: verify all parameters that flask accept and make
    # a loop to verify if the user wanna use some one of this parameters
    if 'template_folder' in config:
        app.template_folder = config['template_folder']
    if 'has_socket' in config:
        socketio = SocketIO(
            app)  #TODO: verify if it is a socket instance by other away
    if 'cors' in config:
        CORS(app, resources=json.dumps({**config['cors'], **cors_default}))

    add_url("/ping", ping.route, "GET")
    fn(app, config)

    @app.after_request
    def after_request(response):
        if 'deeptrace' in config:
            dt = DeepTrace(config['deeptrace'])
            dt.handle(request, response)
        return response
Exemple #6
0
def create_app():
    # Flask Config
    app = Flask(__name__)
    app.config.from_pyfile("config/config.cfg")
    cors = CORS(app, resources={r"/*": {"origins": app.config["FRONTEND_DOMAIN"]}})
    app.template_folder = '.'
    # Misc Config
    os.environ["TZ"] = app.config["TIMEZONE"]

    # Database Config
    if app.config["ENVIRONMENT"] == "development":
        mongo = MongoClient(app.config["MONGO_HOSTNAME"], app.config["MONGO_PORT"])
        app.db = mongo[app.config["MONGO_APP_DATABASE"]]
    else:
        mongo = MongoClient("localhost")
        mongo[app.config["MONGO_AUTH_DATABASE"]].authenticate(app.config["MONGO_AUTH_USERNAME"],
                                                              app.config["MONGO_AUTH_PASSWORD"])
        app.db = mongo[app.config["MONGO_APP_DATABASE"]]

    # Register Blueprints
    app.register_blueprint(user_blueprint, url_prefix="/user")

    # Index Routes
    @app.route("/")
    def index():
        return JsonResp({"status": "Online"}, 200)

    return app
def create_app(config_class=Config):
    app = Flask(__name__)
    app.static_folder = os.path.join(template_folder, 'static/')
    app.template_folder = template_folder
    app.config.from_object(config_class)
    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)
    flask_whooshalchemyplus.init_app(app)

    # Register blueprints
    from volunteercore.auth import bp as auth_bp
    app.register_blueprint(auth_bp)
    from volunteercore.volops import bp as volops_bp
    app.register_blueprint(volops_bp)
    from volunteercore.api import bp as api_bp
    app.register_blueprint(api_bp)
    from volunteercore.errors import bp as errors_bp
    app.register_blueprint(errors_bp)

    @app.route('/')
    def index():
        return render_template('index.html')

    return app
Exemple #8
0
    def create(self):
        flask = Flask(__name__)
        flask.config.from_pyfile(os.path.join(flask.root_path,self.root.config.get("web_conf")))
        for error in range(400, 420) + range(500,506):
            flask.error_handler_spec[None][error] = self.generic_error_handler

        if flask.config["TEMPLATE_DIR"]:
            flask.template_folder = flask.config["TEMPLATE_DIR"]

        if flask.config["AUTOINDEX_ITEMS"]:
            self.register_auto_index_items(flask)

        if flask.config["AUTOINDEX_LOGS"]:
            self.register_auto_index_logs(flask)

        Bootstrap(flask)

        @flask.route("/")
        def index():
            return render_template("index.html", page_title="Home", jobs = self.get_jobs())

        @flask.route("/spiders")
        def projects():
            project_spiders = []
            scrapyd_error = None
            for project in self.root.scheduler.list_projects():
                if project is '.DS_Store':
                    pass
                try:
                    project_spiders.append({'name': project, 'spiders': get_spider_list(project, runner=self.root.runner)})
                except RuntimeError, e:
                    scrapyd_error = "%s: %s" % (project, e.message)

            return render_template("spiders.html", page_title="Spiders", project_spiders=project_spiders,
                                   error=scrapyd_error)
Exemple #9
0
def create_app(env):

    app = Flask(__name__)

    # Config
    from .setting import config
    app.config.from_object(config[env])

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

    admin.name = app.config['APP_NAME']
    admin.template_mode = app.config['ADMIN_TEMPLATE_MODE']

    db.init_app(app)
    ckeditor.init_app(app)

    from blog import blog_init, views
    blog_init(app, admin)

    from admin import admin_init
    admin_init(admin)

    #
    admin.add_view(
        views.Logout(url='/logout', name='Log Out', category="Admin"))

    return app
Exemple #10
0
def make_app(secret_key):
    brewmonitor = Flask(__name__)
    brewmonitor.template_folder = '../../templates/'
    brewmonitor.secret_key = secret_key
    _ = MakoTemplates(brewmonitor)

    config = Configuration.load(
        os.environ.get('BREWMONITOR_CONFIG',
                       '/usr/local/brewmonitor/configuration.yaml'))
    brewmonitor.config.update(config.flask_configuration)
    # Ensure that at least that option is off
    brewmonitor.config['MAKO_TRANSLATE_EXCEPTIONS'] = False
    brewmonitor.config['brewmonitor config'] = config

    initialise_db(config)

    brewmonitor.register_blueprint(home_bp)
    brewmonitor.register_blueprint(accessor_bp)
    brewmonitor.register_blueprint(storage_bp)
    brewmonitor.register_blueprint(admin_bp)

    login_manager = LoginManager()
    login_manager.login_view = 'home.index'
    login_manager.init_app(brewmonitor)

    @login_manager.user_loader
    def load_user(id):
        return User.from_db(config.db_connection(), int(id))

    return brewmonitor
Exemple #11
0
def create_app(debug=True, base_url="/fire", templates="../templates"):
    """Create main Flask app if this module is the entrypoint, e.g. python3 -m fire.views"""
    app = Flask(__name__)
    app.debug = debug
    app.template_folder = templates
    configure_app(app, base_url=base_url)
    return app
def create_app():
    """Flask Application Factory

    Initialises the Flask Application, configures it,
    and then initialises both MongoDB and Prettify.

    Parameters
    ----------
    None

    Returns
    -------
    app : Flask Application
    """

    app = Flask(__name__)

    # Configuration
    app.config["MONGO_DBNAME"] = os.environ.get("MONGO_DBNAME")
    app.config["MONGO_URI"] = os.environ.get("MONGO_URI")
    app.config["PREFERRED_URL_SCHEME"] = "https"
    app.config["TESTING"] = False
    app.config["PRETTIFY"] = True

    # Directories and parameters
    app.template_folder = os.path.abspath("wyspa/templates")
    app.secret_key = os.environ.get("SECRET_KEY")
    app.static_folder = os.path.abspath("wyspa/static")

    # Mongo and Prettify Initialisation
    mongo.init_app(app)
    prettify.init_app(app)

    return app
def create_app(config):
    app = Flask(__name__)

    app.config.from_object(config)
    app.template_folder = app.config['TEMPLATE_FOLDER']
    app.static_folder = app.config['STATIC_FOLDER']
    return app
Exemple #14
0
def create_app(instance_path=None):
    app = Flask(__name__, instance_path=instance_path)

    if not os.path.exists(app.instance_path):
        os.makedirs(app.instance_path)

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

    from app import main, user, note, config
    app.register_blueprint(main.bp)
    app.register_blueprint(user.bp)
    app.register_blueprint(note.bp)
    app.register_blueprint(config.bp)

    db.init_app(app)
    with app.app_context():
        db.create_all()
        from app.config.model import Config
        from app.user.model import User
        Config.update_config()
        User.update_user()

    # FIXME: 설정에서 가져오도록
    theme = 'yaong'
    app.static_folder = '../themes/{}/static'.format(theme)
    app.template_folder = '../themes/{}/templates'.format(theme)

    return app
Exemple #15
0
def create_app(testing=False):
    app = Flask(__name__)

    if os.environ.get('DRIP_ENV', '') == 'production':
        app.config.from_object('drip.config.Production')
    else:
        app.config.from_object('drip.config.Development')

    app.template_folder = os.path.join(PATH, 'templates')

    if not testing:
        # Monitoring.
        newrelic.agent.initialize(os.path.join(PATH, '..', 'newrelic-web.ini'), 'development')

        db = create_mongo(app)

    login_manager = LoginManager()
    login_manager.init_app(app)
    # noinspection PyTypeChecker
    login_manager.user_loader(get_user)
    login_manager.login_view = "user.login"

    # views with jinja templates
    app.register_blueprint(main)
    app.register_blueprint(shopify)
    app.register_blueprint(dashboard)
    return app
Exemple #16
0
def init_app(app: Flask, settings: Settings):
    """
    This function is invoked before running app.
    """
    _init_sqlalchemy(app, settings)
    template_folder = join(dirname(__file__), 'templates')
    app.template_folder = template_folder
Exemple #17
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
Exemple #18
0
def create_app(config_name):
    app = Flask(config_name)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    admin.init_app(app)


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

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

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

    return app
Exemple #19
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
Exemple #20
0
def bootstrap_server():
    app = Flask("camrail")
    config = Config()
    app.config.from_object(config)
    app.template_folder = config.template_folder
    mako_templates = MakoTemplates(app)
    globals()["app"] = app
    globals()["mako_templates"] = mako_templates
Exemple #21
0
def bootstrap_server():
    app = Flask("camrail")
    config = Config()
    app.config.from_object(config)
    app.template_folder = config.template_folder
    mako_templates = MakoTemplates(app)
    globals()["app"] = app
    globals()["mako_templates"] = mako_templates
Exemple #22
0
 def test_renderer(self, **kwargs):
     app = Flask(__name__)
     app.template_folder = os.path.join(self.root, "templates")
     app.config.update(MAKO_CACHE_DIR=os.path.join(self.root, "cache"),
                       MAKO_CACHE_SIZE=10)
     app.config.update(kwargs)
     with app.test_request_context():
         yield app, MakoTemplates(app)
Exemple #23
0
def CreateApp():
    app = Flask(__name__)
    mode = NodeDefender.config.general.config['run_mode']
    app.config.from_object('NodeDefender.config.factory.DefaultConfig')
    app.template_folder = "templates"
    app.static_folder = "templates/frontend/static"
    moment.init_app(app)
    return app
Exemple #24
0
def create_app(debug=False):
    app = Flask(__name__)
    app.debug = debug
    app.template_folder = 'static/'
    # add whitenoise
    app.wsgi_app = WhiteNoise(app.wsgi_app, root='static/')

    return app
Exemple #25
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
Exemple #26
0
def app_factory(mode_config):
    app = Flask(__name__)
    app.config.from_object(config_dict[mode_config])
    app.template_folder = "html"

    from .main import main_bp
    app.register_blueprint(main_bp)

    return app
def create_app() -> Flask:
    app = Flask(__name__)
    app.config.from_envvar("APP_CONFIG")
    register_extensions(app)
    register_blueprints(app)
    configure_error_handlers(app)
    app.template_folder = "frontend/templates"
    app.static_folder = "frontend/static"
    return app
Exemple #28
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('config')
    app.template_folder = 'my_app/templates'
    app.static_folder = 'my_app/static'
    app.register_blueprint(conta_bp)
    app.register_blueprint(api_bp)
    db.init_app(app)
    return app
Exemple #29
0
 def test_renderer(self, **kwargs):
     app = Flask(__name__)
     app.template_folder = os.path.join(self.root, "templates")
     app.config.update(
         MAKO_CACHE_DIR=os.path.join(self.root, "cache"),
         MAKO_CACHE_SIZE=10
     )
     app.config.update(kwargs)
     with app.test_request_context():
         yield app, MakoTemplates(app)
Exemple #30
0
def create_app(templates_path='./src/templates'):
    app = Flask(__name__)
    # register the blueprint
    app.register_blueprint(bp)
    # specify that the blueprint should be on the main route
    app.add_url_rule("/", endpoint="helloworld")
    # register the templates path
    app.template_folder = os.path.abspath(templates_path)

    return app
Exemple #31
0
def create_app():
    flask_app = Flask(__name__,
                      template_folder=config.TEMPLATE_FOLDER,
                      static_folder=config.STATIC_FOLDER)
    flask_app.config.from_object(config)
    flask_app.template_folder = flask_app.config['TEMPLATE_FOLDER']
    flask_app.static_folder = flask_app.config['STATIC_FOLDER']
    log.info("create app done")

    return flask_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
Exemple #33
0
def create_app(mode_config_name):
    app = Flask(__name__)
    app.config.from_object(config_name[mode_config_name])
    app.template_folder = "html"

    db.init_app(app)

    from .src import main_bp as mbp
    app.register_blueprint(mbp)

    return app
Exemple #34
0
def create_app(Config):
    app = Flask(__name__)
    CORS(app, resources={r"/api/*": {"origins": "*"}})
    app.config.from_object(Config)
    app.static_folder = app.config["STATIC_FOLDER"]
    app.template_folder = app.config["TEMPLATE_FOLDER"]

    with app.app_context():
        from app.pages.routers import pages
        app.register_blueprint(pages)

    return app
Exemple #35
0
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
Exemple #36
0
def _create_base_app():
    flask_app = Flask(__name__)
    try:
        from app.application import config_location
    except ImportError:
        config_location = os.path.realpath(
            os.path.join(os.getcwd(), os.path.dirname(__file__), 'config'))

    flask_app.config.update(config.Config(config_location).all())

    try:
        from app.application import template_location
    except ImportError:
        template_location = os.path.realpath(
            os.path.join(os.getcwd(), os.path.dirname(__file__), 'templates'))
    flask_app.template_folder = template_location

    try:
        from app.application import static_location
    except ImportError:
        static_location = os.path.realpath(
            os.path.join(os.getcwd(), os.path.dirname(__file__), 'static'))
    flask_app.static_folder = static_location

    db_uri = re.sub(r'^postgres:', 'postgresql:',
                    _load_uri_from_vcap_services('postgres') or '')
    if not db_uri:
        db_uri = flask_app.config['app']['database_url']

    flask_app.cli.add_command(generic_cmd)

    try:
        from app.commands import get_command_groups
    except ImportError:
        pass
    else:
        for cmd_group in get_command_groups():
            flask_app.cli.add_command(cmd_group)

    flask_app.config.update({
        'TESTING':
        False,
        'SQLALCHEMY_DATABASE_URI':
        _create_sql_alchemy_connection_str(db_uri),
        # set SQLALCHEMY_TRACK_MODIFICATIONS to False because
        # default of None produces warnings, and track modifications
        # are not required
        'SQLALCHEMY_TRACK_MODIFICATIONS':
        False,
    })
    flask_app.json_encoder = CustomJSONEncoder
    flask_app.secret_key = flask_app.config['app']['secret_key']
    return _register_components(flask_app)
Exemple #37
0
def Create_App(Config='videoonline.config.DevConfig'):
    app = Flask(__name__)
    with app.app_context():
        app.config.from_object(Config)

        # Will be load the SQLALCHEMY_DATABASE_URL from config.py to db object
        db.init_app(app)
        # 数据库是一个重要的组件,所以先把数据库内容全部完成再继续后面的操作

        # Init the Flask-Bcrypt via app object
        bcrypt.init_app(app)
        # Init the Flask-Login via app object
        login_manager.init_app(app)
        # Init the Flask-Prinicpal via app object
        principals.init_app(app)

        # 因为 identity_loaded 信号实现函数,需要访问 app 对象, 所以直接在 create_app() 中实现.
        @identity_loaded.connect_via(app)
        def on_identity_loaded(sender, identity):
            """Change the role via add the Need object into Role.

               Need the access the app object.
            """

            # Set the identity user object
            identity.user = current_user

            # Add the UserNeed to the identity user object
            if hasattr(current_user, 'id'):
                identity.provides.add(UserNeed(current_user.id))

            # Add each role to the identity user object
            if hasattr(current_user, 'roles'):
                # 原本多对多的用户权限,现在改成用户对应角色 一对多,取消for循环
                # for role in current_user.roles:
                role = current_user.roles
                identity.provides.add(RoleNeed(role.name))

        app.static_folder = 'theme/static'
        app.template_folder = 'theme/templates'

        # 定义 404,405 等、这里只定义 404
        @app.errorhandler(404)
        def page_not_found(error):
            return render_template('40X/404.html'), 404

        from videoonline.view import root_view
        from videoonline.admin import admin_view

        app.register_blueprint(root_view, url_prefix='/')
        app.register_blueprint(admin_view, url_prefix='/admin')

        return app
Exemple #38
0
def create_app(config=None):
    app = Flask(__name__.split('.')[0])

    config = os.environ.get('CONFIG', 'dev')
    app.logger.info("Config: %s" % config)
    app.config.from_object(configs.get(config, None) or configs['default'])
    app.template_folder = app.config.get('TEMPLATE_FOLDER', 'templates')

    register_extensions(app)
    register_blueprints(app)

    return app
Exemple #39
0
def create_app(debug=True, base_url="", templates="../templates"):
    """Create main Flask app if this module is the entrypoint, e.g. python3 -m browser.views"""
    app = Flask(__name__)
    app.debug = debug
    app.template_folder = templates
    # configure app with generic /zip_files URLs by default here!?
    if not base_url:
        base_url = BASE_URL
    configure_app(app, base_url=base_url)
    # authorize_wrap = flask_authorize("admin")  # if one role for all view_funcs
    # configure_app(app, base_url=base_url, authorize_wrap=authorize_wrap)
    return app
Exemple #40
0
def make_app(config="config.py"):

    app = Flask(__name__)

    #----------------------------
    #helpers
    app.jinja_env.globals['icon'] =\
        lambda x:"<i class='glyphicon glyphicon-%s'></i>"%x

    #todo: app.jinja_env.globals['_'] = _
    app.template_folder = "app"

    app.config.from_pyfile(config)
    return app
Exemple #41
0
def run():
    app = Flask(__name__)
    db.init_app(app)
    environ['api_CONFIG'] = 'DEV'
    app.config.from_object('config.settings')
    app.template_folder = app.config.get('TEMPLATE_FOLDER', 'templates')
    app.register_blueprint(groups_blueprint)
    app.debug = app.config['DEBUG']
    print('Starting server at %s listening on port %s %s' % (
        app.config['HOST'],
        app.config['PORT'],
        'in DEBUG mode' if app.config['DEBUG'] else ''
    ))
    http_server = WSGIServer((app.config['HOST'], app.config['PORT']), DebuggedApplication(app))
    http_server.serve_forever()
Exemple #42
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
Exemple #43
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.template_folder = 'templates'
    app.debug = True

    config[config_name].init_app(app)

    db.init_app(app)

    login_manager.init_app(app)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

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

    return app
Exemple #44
0
def create_app(config_name='DEV'):
    """Flask app factory.

    Useage::

        from fooder.app import create_app
        def run():
            app = create_app(config_name='STAGE')
            app.run(host='0.0.0.0', port=5000, debug=app.debug)

        if __name__=="__main__":
            run()

    :param config_name: manually provide the name of the config object to use
        when creating the :py:class:``flask.Flask`` instance.  Defaults to
        os.environ['fooder_CONFIG']

    :rtype: :py:class:``flask.Flask``
    :returns: A new :py:class:``flask.Flask`` application instance
    """
    global db_session

    app = Flask(__name__)

    if config_name is not None:
        environ['FOODER_CONFIG'] = config_name

    app.config.from_object('fooder.config.settings')
    app.template_folder = app.config.get('TEMPLATE_FOLDER', 'templates')
    app.register_blueprint(api_mod, url_prefix='/v1')

    # Close the db session as app request context is torn down.
    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db_session.remove()

    @app.route('/', defaults={'path': ''})
    @app.route('/<path:path>')
    def catch_all(path):
        return redirect(url_for('api.home'))

    return app
Exemple #45
0
def create_app(environment="DEVELOPMENT"):
    """worldofsfx application factory.

    This function defines a re-usable pattern for instantiating and creating
    application objects.

    :param str environment: Specify the name of the configuration object used
                            to build this application object

    Usage::
        from worldofsfx import create_app
        from unittest import TestCase

        class MyTest(TestCase):

            def setUp(self):
                self.app = create_app(environment="TESTING")

    :returns: flask application
    :rtype: :obj:`flask.Flask`
    """
    if not environment:
        env_name = "DEVELOPMENT"
    else:
        env_name = environment.upper()
    app = Flask(__name__)
    env = Environments(app, default_env=env_name)
    env.from_object("worldofsfx.config")
    wos_privates = os.getenv("WOS_PRIVATES")
    if wos_privates:
        env.from_object(wos_privates)

    app.template_folder = app.config.get("TEMPLATE_FOLDER", "templates")

    app.register_blueprint(wos)
    app.register_blueprint(events)
    app.register_blueprint(buzz)
    app.register_blueprint(beatport)

    db.init_app(app)

    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
def http_worker(lock):
    """The Flask application"""
    app = Flask("cloud_xfd")

    # noinspection PyUnusedLocal
    @app.route("/")
    def index():
        with lock:
            url = get_url()
        return render_template("index.html", url=url)

    # noinspection PyUnusedLocal
    @app.route("/update", methods=["POST"])
    def update():
        address = request.form["url"]
        with lock:
            put_url(address)

        flash("The URL has been successfully updated")
        return redirect(url_for('index'))

    app.template_folder = "/home/pi/extremefeedbacklamp/templates"
    app.secret_key = "notreallyasecret"
    app.run('0.0.0.0')
Exemple #48
0
def create_app(config_name='DEV'):
    """Flask app factory.

    Useage::

        from {{PROJECT_NAME}}.app import create_app
        def run():
            app = create_app(config_name='STAGE')
            app.run(host='0.0.0.0', port=5000, debug=app.debug)

        if __name__=="__main__":
            run()

    :param config_name: manually provide the name of the config object to use
        when creating the :py:class:``flask.Flask`` instance.  Defaults to
        os.environ['{{PROJECT_NAME}}_CONFIG']

    :rtype: :py:class:``flask.Flask``
    :returns: A new :py:class:``flask.Flask`` application instance
    """

    app = Flask(__name__)

    if config_name is not None:
        environ['{{PROJECT_NAME}}_CONFIG'] = config_name

    app.config.from_object('{{PROJECT_NAME}}.config.settings')
    app.template_folder = app.config.get('TEMPLATE_FOLDER', 'templates')
    app.register_blueprint(api_mod, url_prefix='/v1')

    @app.route('/', defaults={'path': ''})
    @app.route('/<path:path>')
    def catch_all(path):
        return redirect(url_for('api.home'))

    return app
Exemple #49
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()
Exemple #50
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')
Exemple #51
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"
    
Exemple #52
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
Exemple #53
0
import yaml
import hashlib
from datetime import datetime, timedelta

# flask dependencies
from flask import Flask
from flask import jsonify
from flask.ext.mako import MakoTemplates, render_template
from werkzeug.exceptions import NotFound

# hflossk
from hflossk.util import count_posts
from hflossk.blueprints import homework, lectures, quizzes

app = Flask(__name__)
app.template_folder = "templates"
mako = MakoTemplates(app)
base_dir = os.path.split(__file__)[0]

# Automatically include site config
@app.context_processor
def inject_yaml():
    with open(os.path.join(base_dir, 'site.yaml')) as site_yaml:
        site_config = yaml.load(site_yaml)
    return site_config

config = inject_yaml()
COURSE_START = datetime.combine(config['course']['start'], datetime.min.time())
COURSE_END = datetime.combine(config['course']['end'], datetime.max.time())

Exemple #54
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Flask, render_template, request, url_for
from datetime import datetime
import hashlib, markdown, operator, pagination, os, sys

app = Flask(__name__)

app.config.from_object('config.ProductionConfig')
app.template_folder = app.config['TEMPLATE_PATH']

# --- routes

@app.errorhandler(404)
def page_not_found():
    # TODO: write to log
    data = content_load('pages/404.md')
    md = markdown.markdown(data)
    return render_template('page.tpl.html', page=md), 404

# @app.route("/")
# def index():
#     return dwarf_render_page('index')

# @app.route("/about/")
# def about():
#     return dwarf_render_page('about')

@app.route("/posts/<slug>")
def blogpost(slug):
Exemple #55
0
    result = []
    cnt = 0
    for item in r:
        cnt += 1
        if cnt > 100:
            break
        result.append((item[0], item[1]))

    print("ok")
    return render_template("search.html", match_torrents_count=counts, 
        total_torrents=torrents_count(), result=result)


def to_magnet(infohash, name):
    magnet_base = "magnet:?xt=urn:btih:" + infohash
    magnet = magnet_base + "&dn=" + name
    return magnet


def torrents_count():
    cmd = "select count(*) from hash_tab"
    r = conn.execute(cmd)
    for item in r:
        return item[0]


if __name__ == "__main__":
    app.template_folder = "simServer/templates"
    app.debug = False
    app.run(host="0.0.0.0", port=5000)
Exemple #56
0
monkey.patch_all()

import time
import json
import os
import signal

from RTKLIB import RTKLIB
from port import changeBaudrateTo230400

from threading import Thread
from flask import Flask, render_template, session, request
from flask.ext.socketio import SocketIO, emit, disconnect

app = Flask(__name__)
app.template_folder = "."
app.debug = False
app.config["SECRET_KEY"] = "secret!"

socketio = SocketIO(app)

# configure Ublox for 230400 baudrate!
changeBaudrateTo230400()

rtk = RTKLIB(socketio)

perform_update = False

# at this point we are ready to start rtk in 2 possible ways: rover and base
# we choose what to do by getting messages from the browser
Exemple #57
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"))
Exemple #58
0
#!/usr/bin/env python
#encoding:utf-8

from os.path import join
from flask import Flask
from settings import BASE_DIR, UPLOAD_FOLDER, DB_URI


app = Flask(__name__)
app.template_folder = join(BASE_DIR, 'src', 'templates')
app.static_folder = join(BASE_DIR, 'src', 'static')

app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


@app.template_filter('upurl')
def upurl(s):
    return u'uploads{}'.format(s.split('uploads')[-1])

@app.template_filter('upname')
def upname(s):
    return s.split('uploads/')[-1]

@app.template_filter('dwurl')
def dwurl(s):
    return u'downloads{}'.format(s.split('downloads')[-1])

@app.template_filter('dwname')
def dwname(s):
    return s.split('downloads/')[-1]
Exemple #59
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json

from os.path import dirname
from os.path import join
from flask import Flask

from app.dashboard.views import DashboardResource

app = Flask(__name__)
app.template_folder = join(dirname(__file__), 'templates')
app.static_folder = join(dirname(__file__), 'static')


class UserConfig(dict):
    """ loads the json configuration file """

    def _string_decode_hook(self, data):
        rv = {}
        for key, value in data.iteritems():
            if isinstance(key, unicode):
                key = key.encode('utf-8')
            if isinstance(value, unicode):
                value = value.encode('utf-8')
            rv[key] = value
        return rv

    def __init__(self):
        dict.__init__(self)