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(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 #3
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)
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)

    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
Beispiel #5
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
Beispiel #6
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
Beispiel #7
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 #8
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
Beispiel #9
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)
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 #11
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
Beispiel #12
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 #13
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()
Beispiel #14
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
Beispiel #15
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
Beispiel #16
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
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 #18
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
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')
Beispiel #20
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 #21
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 #22
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 #23
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 #24
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())

Beispiel #25
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):
Beispiel #26
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)
Beispiel #27
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
Beispiel #28
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"))
Beispiel #29
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)
Beispiel #30
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]