Пример #1
1
def app():
    app = Flask(__name__)
    app.jinja_loader = FunctionLoader(load_template)

    Obscurity(app)

    return app
Пример #2
0
def app_error_handler(request):
    """Flask app error handler fixture."""
    app = Flask('myapp')

    # Creation of a fake theme error template file.
    temp_dir = tempfile.mkdtemp()
    invenio_theme_dir = os.path.join(temp_dir, 'invenio_theme')
    os.mkdir(invenio_theme_dir)
    fake_file = open(os.path.join(invenio_theme_dir, 'fake.html'), 'w+')
    fake_file.write("{# -*- coding: utf-8 -*- -#}"
                    "<!DOCTYPE html>{% block message %}"
                    "{% endblock message %}")
    fake_file.close()

    # Adding the temporal path to jinja engine.
    app.jinja_loader = jinja2.ChoiceLoader([
        jinja2.FileSystemLoader(temp_dir),
        app.jinja_loader
    ])

    # Setting by default fake.html as a THEME_ERROR_TEMPLATE
    app.config['THEME_ERROR_TEMPLATE'] = 'invenio_theme/fake.html'

    # Tear down method to clean the temp directory.
    def tear_down():
        shutil.rmtree(temp_dir)
    request.addfinalizer(tear_down)

    app.testing = True
    Babel(app)
    InvenioI18N(app)
    InvenioTheme(app)
    return app
Пример #3
0
def create_app():
    """
    Creates the Flask app instance

    @return: Flask app
    @rtype: flask.Flask
    """
    from flask import Flask
    app = Flask(__name__)
    # set debug to true so we see error dumps in the browser
    app.debug = settings.APP_DEBUG
    app.secret_key = settings.APP_SECRET_KEY
    app.config['SQLALCHEMY_DATABASE_URI'] = settings.DATABASE[env]['uri']
    app.config['BASE_URL'] = settings.BASE_URL
    app.config['SQLALCHEMY_ECHO'] = settings.DATABASE[env]['echo']
    app.config['RECAPTCHA_PUBLIC_KEY'] = settings.RECAPTCHA_PUBLIC_KEY
    app.config['RECAPTCHA_PRIVATE_KEY'] = settings.RECAPTCHA_PRIVATE_KEY
    app.config['SERVER_NAME'] = settings.BASE_URL

    app.jinja_options['extensions'].append('jinja2.ext.loopcontrols')
    my_loader = jinja2.ChoiceLoader([
        app.jinja_loader,
        jinja2.FileSystemLoader([os.path.dirname(os.path.abspath(__file__)) + '/static']),
    ])
    app.jinja_loader = my_loader

    return app
Пример #4
0
def create_app(package_name='ticketting_system'):
    """Returns a :class:`Flask` application instance configured with common
    functionality for the korath platform.

    :param package_name: application package name
    :param package_path: application package path
    :param config_name: can have one of [production, development, testing]
    """
    global app, admin
    app = Flask(package_name, instance_relative_config=True)

    config_name = os.environ.get('ticketting_system_CONFIG_NAME', 'Production')

    app.config.from_object('configurations.%s'%config_name.title())

    app.jinja_loader = jinja2.ChoiceLoader([
        app.jinja_loader,
        jinja2.FileSystemLoader('ticketting_system/templates/'),
    ])

    db.init_app(app)
    admin = Admin(app, 'Ticketing System Admin Panel')

    from . import views
    from views import api_blueprint
    app.register_blueprint(api_blueprint)


    from . import models

    # for admin panel
    from . import admin_panel
    return app
Пример #5
0
def makeApp(rootpath, configFileName='webgenerator.yaml'):
    # If configFileName is unusable for any reason we want this to fail
    # the point of this method is to bootstrap app from configFile
    with open(os.path.join(rootpath, configFileName), 'r') as configFile:
        config = yaml.load(configFile)

    app = Flask(__name__)

    # Todo, this should be possible as a list, so we could include
    # external templates as well
    if 'template_folder' in config:
        # load templates first from the directory defined by the repository, then
        # by the default loader i.e. from the app.
        jinja2_loader = jinja2.ChoiceLoader([
            # first local
            jinja2.FileSystemLoader(os.path.join(rootpath, config['template_folder'])),
            # then the default
            app.jinja_loader
        ])
        app.jinja_loader = jinja2_loader

    app.config['rootpath'] = rootpath
    targets = buildRoutes(app, config)
    timezone = pytz.timezone(config.get('timezone', 'UTC'))
    app.config['fileDataCache'] = FileDataCache( tz=timezone )
    menu = Menu(app, targets)
    app.config['menu'] = menu
    app.config['generator_config'] = config
    return app, menu
Пример #6
0
 def make_app(self):
     app = Flask('clay', static_folder=None, template_folder=self.source_dir)
     app.jinja_loader = self.get_jinja_loader()
     app.jinja_options = self.get_jinja_options()
     app.debug = True
     self.set_template_context_processors(app)
     self.set_urls(app)
     return app
Пример #7
0
def init_flaskadmin(urlprefix="",secret="fKY7kJ2xSrbPC5yieEjV",override_admin=None,override_flaskadminapp=None):
    global flaskadminapp, admin
    
    if not override_flaskadminapp:
        flaskadminapp = Flask(__name__)
        flaskadminapp.debug=True
        flaskadminapp.secret_key = secret
        flaskadminapp.config.update(dict(
            PREFERRED_URL_SCHEME = 'https'
        ))
    else:
        flaskadminapp = override_flaskadminapp

        # lets add our template directory
        my_loader = jinja2.ChoiceLoader([
            flaskadminapp.jinja_loader,
            jinja2.FileSystemLoader(resole_uri("gengine:templates")),
        ])
        flaskadminapp.jinja_loader = my_loader
        
    flaskadminapp.add_url_rule('/static_gengine/<path:filename>',
                               endpoint='static_gengine',
                               view_func=get_static_view('gengine:flask_static',flaskadminapp))
    
    @flaskadminapp.context_processor
    def inject_version():
        return { "gamification_engine_version" : pkg_resources.get_distribution("gamification-engine").version }
    
    if not override_admin:
        admin = Admin(flaskadminapp,
                      name="Gamification Engine - Admin Control Panel",
                      base_template='admin_layout.html',
                      url=urlprefix+"/admin"
                     )
    else:
        admin = override_admin
            
    admin.add_view(ModelViewAchievement(DBSession, category="Rules"))
    admin.add_view(ModelViewGoal(DBSession, category="Rules"))
    admin.add_view(ModelView(AchievementAchievementProperty, DBSession, category="Rules", name="Achievement Property Values"))
    admin.add_view(ModelView(AchievementReward, DBSession, category="Rules", name="Achievement Reward Values"))
    admin.add_view(ModelView(GoalGoalProperty, DBSession, category="Rules", name="Goal Property Values"))
    admin.add_view(ModelViewTranslationVariable(DBSession, category="Rules"))
    admin.add_view(ModelView(Translation,DBSession, category="Rules"))
    
    admin.add_view(ModelViewAchievementCategory(DBSession, category="Settings"))
    admin.add_view(ModelViewVariable(DBSession, category="Settings"))
    admin.add_view(ModelViewAchievementProperty(DBSession, category="Settings", name="Achievement Property Types"))
    admin.add_view(ModelViewReward(DBSession, category="Settings", name="Achievement Reward Types"))
    admin.add_view(ModelViewGoalProperty(DBSession, category="Settings", name="Goal Property Types"))
    admin.add_view(ModelView(Language, DBSession, category="Settings"))
    admin.add_view(MaintenanceView(name="Maintenance", category="Settings", url="maintenance"))
    
    admin.add_view(ModelViewValue(DBSession, category="Debug"))
    admin.add_view(ModelViewGoalEvaluationCache(DBSession, category="Debug"))
    admin.add_view(ModelViewUser(DBSession, category="Debug"))
    admin.add_view(ModelView(AchievementUser, DBSession, category="Debug"))
Пример #8
0
def create_app(conf):
    """
    A factory function for creating Flask apps given a configuration 
    dictionary.

    The factory will initialise all Flask plugins, as well as change the 
    template directory and load all blueprints.

    The factory function also sets up logging and adds the `wiki` variable
    to the template globals.
    """
    app = Flask(__name__)
    app.config.update(conf)

    # Tell flask to get all templates from our template dir
    my_loader = jinja2.ChoiceLoader([
        app.jinja_loader,
        jinja2.FileSystemLoader(conf['TEMPLATE_DIR']),
    ])
    app.jinja_loader = my_loader

    bootstrap.init_app(app)
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    
    # Attach routes and custom error pages
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

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

    from .pages import pages as pages_blueprint
    app.register_blueprint(pages_blueprint, url_prefix='/pages')

    import logging
    from logging.handlers import RotatingFileHandler
    file_handler = RotatingFileHandler(
            app.config.get('LOG_FILE'), 
            maxBytes=1024 * 1024 * 100, 
            backupCount=20)
    file_handler.setLevel(logging.INFO)
    formatter = logging.Formatter(
            "%(asctime)s - %(name)s - %(levelname)s: %(message)s",
            datefmt='%Y/%m/%d %I:%M:%S %p')
    file_handler.setFormatter(formatter)
    app.logger.addHandler(file_handler)

    # Catch the requests behind the scenes from werkzeug
    logger = logging.getLogger('werkzeug')
    logger.addHandler(file_handler)

    # Inject the app metadata into all our templates
    app.jinja_env.globals['wiki'] = conf['METADATA']

    return app
Пример #9
0
    def _create_app(self):
        app = Flask(__name__)
        app.debug = self.conf.FLASK_DEBUG

        if not self.conf.STATIC_RESOURCE:
            raise Exception('STATIC_RESOURCE setting not configured.')
        if not self.conf.TEMPLATE_RESOURCE:
            raise Exception('TEMPLATE_RESOURCE setting not configured.')

        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
            '/': self.conf.STATIC_RESOURCE
        })
        if type(self.conf.TEMPLATE_RESOURCE) == tuple:  # package, not filepath
            app.jinja_loader = PackageLoader(*self.conf.TEMPLATE_RESOURCE)
        else:
            app.jinja_loader = FileSystemLoader(self.conf.TEMPLATE_RESOURCE)
        if self.conf.ALLOW_DEFERREDS:
            self._enable_deferreds(app)
        return app
Пример #10
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
Пример #11
0
def create_app(object_name):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. appname.settings.ProdConfig
    """
    app = Flask(__name__)

    app.config.from_object(object_name)
    if os.environ.get('KAKU_SETTINGS', None) is not None:
        app.config.from_envvar('KAKU_SETTINGS')

    if not app.debug:
        handler   = logging.handlers.RotatingFileHandler(app.config['LOG_FILE'], maxBytes=100000000, backupCount=9)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(pathname)s:%(lineno)d -- %(message)s')
        handler.setFormatter(formatter)
        handler.setLevel(logging.DEBUG)

        app.logger.addHandler(handler)
        app.logger.setLevel(logging.DEBUG)

        wzlog = logging.getLogger('werkzeug')
        wzlog.setLevel(logging.DEBUG)
        wzlog.addHandler(handler)

    if app.config['SITE_TEMPLATES'] is not None:
        app.jinja_loader = jinja2.FileSystemLoader(app.config['SITE_TEMPLATES'])

    # initialize the cache
    cache.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    app.dbRedis = FlaskRedis.from_custom_provider(StrictRedis, app)

    # register our blueprints
    app.register_blueprint(main)
    app.register_blueprint(auth)

    app.logger.info('Flask app [%s] created' % __name__)

    return app
Пример #12
0
    def __init__(self, server, debug=False, address='127.0.0.1', port=3855, enabled=True, **kwargs):
        """ Handles implementing default configurations """
        logger = server.register_logger('monitor')
        wsgi_logger = server.register_logger('monitor_wsgi')
        if not enabled:
            logger.info("HTTP monitor not enabled, not starting up...")
            return
        else:
            logger.info("HTTP monitor enabled, starting up...")
        app = Flask('monitor')
        app = Flask('monitor', static_folder='../static', static_url_path='/static')
        # set our template path and configs
        app.jinja_loader = FileSystemLoader(os.path.join(root, 'templates'))
        app.config.update(kwargs)
        app.config['DEBUG'] = debug
        app.register_blueprint(main)

        # Monkey patch the wsgi logger
        Logger.logger = wsgi_logger
        app.real_logger = logger

        @app.template_filter('duration')
        def time_format(seconds):
            # microseconds
            if seconds > 3600:
                return "{}".format(timedelta(seconds=seconds))
            if seconds > 60:
                return "{:,.2f} mins".format(seconds / 60.0)
            if seconds <= 1.0e-3:
                return "{:,.4f} us".format(seconds * 1000000.0)
            if seconds <= 1.0:
                return "{:,.4f} ms".format(seconds * 1000.0)
            return "{:,.4f} sec".format(seconds)

        # setup localproxy refs
        app.server = server
        WSGIServer.__init__(self, (address, port), app, log=Logger())

        @app.template_filter('datetime')
        def jinja_format_datetime(value, fmt='medium'):
            if fmt == 'full':
                fmt = "EEEE, MMMM d y 'at' HH:mm"
            elif fmt == 'medium':
                fmt = "EE MM/dd/y HH:mm"
            return value.strftime(fmt)
Пример #13
0
def create_app():
    application = Flask(__name__, static_folder=EG_STATIC_FOLDER)
    my_loader = jinja2.ChoiceLoader([application.jinja_loader, jinja2.FileSystemLoader(EG_SYSTEM_TEMPLATE_FOLDER)])

    application.jinja_loader = my_loader
    application.secret_key = APP_SECRET_KEY
    application.config.from_object('config')

    application.jinja_env.filters['date'] = datetime_filter

    # Initialize Babel
    Babel(application)
    application.config['BABEL_DEFAULT_LOCALE'] = BABEL_DEFAULT_LOCALE

    # Initialize database
    from therm.models import db
    db.init_app(application)

    return application
Пример #14
0
def serve(py_exec=None):
    log_set_up(True)
    parser = argparse.ArgumentParser()
    parser.add_argument("--python", default="python")
    args = parser.parse_args()

    py_exec = args.python

    app = Flask("touchandgo")
    template_path = join(dirname(__file__), "templates")
    app.jinja_loader = FileSystemLoader(template_path)

    def get_torrent(name, season=None, episode=None):
        interface = get_interface()
        path = abspath(__file__)
        dir_path = dirname(path)
        exec_ = join(dir_path, "__init__.py")
        command = '%s %s \"%s\" ' % (py_exec, exec_, name)
        if season is not None:
            command += "%s %s " % (season, episode)
        lock = Lock(LOCKFILE)
        if lock.is_same_file(name, season, episode) and \
                is_process_running(lock.get_pid()):
            data = lock._get_file_data()
            port = data[4]
        else:
            port = get_free_port()
            command += "--daemon --port %s " % port
            log.debug(command)
            process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)
            sleep(1)

        redirect_url = "http://%s:%s" % (interface, port)
        serving = False
        while not serving:
            try:
                req = requests.get("%s/status" % redirect_url)
                serving = True
            except requests.ConnectionError, e:
                sleep(1)
        log.info("redirecting to %s" % redirect_url)
        return redirect(redirect_url)
Пример #15
0
def init(cfg):
    from yaml import load as yaml_load
    from jinja2 import FileSystemLoader
    from os.path import join as path_join, exists
    from hicode import setting
    from pygments.lexers import get_all_lexers
    from pygments.styles import get_all_styles

    if exists(cfg):
        users = yaml_load(file(cfg).read())
        setting.update(users)

    setting['styles'] = list(get_all_styles())
    setting['langs'] = dict(map(lambda x: (x[0], x[1]), get_all_lexers()))

    app = Flask('hicode')
    app.jinja_loader = FileSystemLoader(setting['template_directory'])
    app.debug = setting['debug']

    return app
Пример #16
0
def create_app(config='QATrainingFrontend.config'):
    app = Flask(__name__)
    with app.app_context():
        app.config.from_object(config)
        app.jinja_loader = ThemeLoader(os.path.join(app.root_path, app.template_folder), followlinks=True)

        from QATrainingFrontend.models import db, Users, Solves, Challenges, WrongKeys, Keys, Tags, Files, Tracking

        ## sqlite database creation is relative to the script which causes issues with serve.py
        if not database_exists(app.config['SQLALCHEMY_DATABASE_URI']) and not app.config['SQLALCHEMY_DATABASE_URI'].startswith('sqlite'):
            create_database(app.config['SQLALCHEMY_DATABASE_URI'])

        db.init_app(app)
        db.create_all()

        app.db = db

        if not get_config('ctf_theme'):
            set_config('ctf_theme', 'original')

        #Session(app)

        from QATrainingFrontend.views import views
        from QATrainingFrontend.challenges import challenges
        from QATrainingFrontend.scoreboard import scoreboard
        from QATrainingFrontend.auth import auth
        from QATrainingFrontend.admin import admin
        from QATrainingFrontend.utils import init_utils, init_errors, init_logs

        init_utils(app)
        init_errors(app)
        init_logs(app)

        app.register_blueprint(views)
        app.register_blueprint(challenges)
        app.register_blueprint(scoreboard)
        app.register_blueprint(auth)
        app.register_blueprint(admin)

        return app
Пример #17
0
    def app(self):
        """ derive flask app based on the combination of command-line
            options and the contents of the .ini files
        """

        ## set flask specific things that are non-optional
        error = lambda k: 'Fatal: You need to specify a "flask" section ' + \
                'with an entry like  "'+k+'=..." in your .ini file'
        try: app_name = self['flask.app']
        except KeyError: raise SystemExit(error('app'))
        try: secret_key = self['flask.secret_key']
        except KeyError: raise SystemExit(error('secret_key'))
        app = Flask(app_name)
        app.secret_key = secret_key

        ## set flask specific things that are optional
        if 'flask.template_path' in self:
            app.jinja_loader = FileSystemLoader(self['template_path'])
        if 'flask.before_request' in self:
            before_request = self['flask.before_request']
            before_request = namedAny(before_request)
            app.before_request(before_request)
        if 'flask.after_request' in self:
            after_request = self['flask.after_request']
            after_request = namedAny(after_request)
            app.after_request(after_request)

        ## setup views
        try: view_holder = self['corkscrew.views']
        except KeyError:
            error = 'Fatal: could not "view=<dotpath>" entry in your .ini file'
            raise SystemExit(error)
        else:
            view_list = namedAny(view_holder)
            [ v(app=app, settings=self) for v in view_list]

            return app
Пример #18
0
def create_app(package_name='mordor', config_name='Development'):
    """Returns a :class:`Flask` application instance configured with common
    functionality for the mordor platform.

    :param package_name: application package name
    :param package_path: application package path
    :param config_name: can have one of [production, development, testing]
    """
    
    app = Flask(package_name, instance_relative_config=True)
    if os.environ.get('mordor_CONFIG_NAME') == 'Production':
        config_name = 'Production'

    app.config.from_object('configurations.%s'%config_name.title())

    app.jinja_loader = jinja2.ChoiceLoader([
        app.jinja_loader,
        jinja2.FileSystemLoader('mordor/templates/'),
    ])

    db.init_app(app)
    rc.init_app(app)
    es.init_app(app)
    admin.init_app(app)
    
    rscripts.init_app(app, rc)
    from views import main as main_blueprint
    app.register_blueprint(main_blueprint)

    mail_handler = SMTPHandler((app.config['MAIL_SERVER'], app.config['MAIL_PORT']), 
        'admin@reviews42.com', app.config['ADMINS'], '[mordor] phat gaya', 
        (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']),(None, None))
    mail_handler.setLevel(logging.ERROR)
    app.logger.addHandler(mail_handler)
    
    return app
Пример #19
0
# encoding: utf-8

from flask import Flask, render_template, jsonify, request
from jinja2 import FileSystemLoader
import os
from utils.decorators import stacktraceable
from utils.marshall import dumps
from datetime import *


ROOT_PATH = os.path.dirname(__file__)
template_path = 'templates'
app = Flask(__name__)
app.jinja_loader = FileSystemLoader(os.path.join(ROOT_PATH, template_path))

# Base de datos
import models

# Test purposue
from random import seed, randrange
seed(os.getpid())
from utils.datatable import parseparams
#--------------------------------------------------------------------
# Contex processors y cosas para los temapltes
#--------------------------------------------------------------------

@app.context_processor
def static_url():
    return dict(STATIC_URL = '/static/')

@app.context_processor
Пример #20
0
from flask.ext import restful
from flask.ext.pymongo import PyMongo
from flask.ext.assets import Environment, Bundle
from bson.json_util import dumps
import jinja2

# basic paths
MONGO_URL = "mongodb://localhost:27017/violence"
ASSETS_DIR=os.path.join(os.path.dirname(os.path.abspath(__file__)), '../static')

# app
app = Flask(__name__)
app._static_folder = ASSETS_DIR
app.config['SECRET_KEY'] = 'secret!'
app.debug = True
app.jinja_loader=jinja2.FileSystemLoader('templates')

# compass config
assets = Environment(app)

main_scss = Bundle('scss/style.scss', 'scss/media.scss', filters='compass', output='css/style.css')
assets.register('main_scss', main_scss)

# mongo db
app.config['MONGO_URI'] = MONGO_URL
mongo = PyMongo(app)

def output_json(obj, code, headers=None):
    resp = make_response(dumps(obj), code)
    resp.headers.extend(headers or {})
    return resp
Пример #21
0
import os

import jinja2
from flask import Flask
from flask_sockets import Sockets

CURRENT_DIRECTORY = os.path.dirname(__file__)
STATIC_FOLDER = os.path.join("twidder", "static")
MEDIA_FOLDER = os.path.join("twidder", "media")

ALLOWED_MEDIA = {"jpg", "png", "mp4", "mp3", "wav"}

app = Flask(__name__, static_url_path='', static_folder=STATIC_FOLDER)
app.config["SECRET_KEY"] = os.urandom(24)
app.config['UPLOAD_FOLDER'] = MEDIA_FOLDER
app.root_path = os.getcwd()

app.jinja_loader = jinja2.ChoiceLoader([
    app.jinja_loader,
    jinja2.FileSystemLoader(os.path.join(CURRENT_DIRECTORY, "static"))
])

sockets = Sockets(app)

from . import twidder
Пример #22
0
from flask import Flask, render_template, request
from jinja2 import FileSystemLoader
from .utils import curry
from .services import Service
from exceptions import ImportError 
import os, sys


# Setup the app and load the settings
app = Flask(__name__)
app.config.from_envvar('NARCISSIST_SETTINGS')
app.root_path = app.config["ROOT_PATH"]

main_template_path = os.path.join(app.root_path, "themes")
app.jinja_loader = FileSystemLoader(main_template_path)

# We will hold the mapped URLS in config so we can access them in the templates
app.config["URLS"] = []


def _endpoint(service):
    """ Helper for XHR requests. If the request is XHR, omit the layout. """

    if request.is_xhr:
        return self.service.render()
    else:
        return render_template(app.config["THEME"] + "/main.html", 
                content = service.render(), title = app.config["TITLE"], 
                sub_title = app.config["SUB_TITLE"], urls = app.config["URLS"])
Пример #23
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"))
Пример #24
0
from flaskext.markdown import Markdown
import jinja2
from datetime import datetime

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

# Include docs folder in templates
my_loader = jinja2.ChoiceLoader([
    app.jinja_loader,
    jinja2.FileSystemLoader(['sni/templates/',
    						 'sni/templates/blog/',
    						 'sni/templates/docs/',
                             'sni/templates/podcast/']),
])
app.jinja_loader = my_loader

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

Markdown(app)

manager = Manager(app)
manager.add_command('db', MigrateCommand)

cache = Cache(app,config={'CACHE_TYPE': 'simple'})

from models import DonationAddress

@app.context_processor
def utility_processor():
Пример #25
0
CORS(app, resources=r'/developmentcontrol/*', allowed_headers=['Content-Type', 'X-Requested-With'])

# Configure logging to stderr
log_handler = StreamHandler()
log_handler.setLevel(logging.INFO)
app.logger.addHandler(log_handler)

# Add the to the template search path so that we can treat our built hubmap.js
# as a template without having to manually copy it to the standard template
# directory
DIST_DIR = os.path.join(app.static_folder, 'hubmap/dist')
template_loader = ChoiceLoader([
    app.jinja_loader,
    FileSystemLoader([DIST_DIR])
])
app.jinja_loader = template_loader

# Expose additional functions in templates
app.jinja_env.globals.update(url_unquote_plus=url_unquote_plus)

if 'CONNECTION_STRING' in os.environ:
    app.config['CONNECTION_STRING'] = os.environ['CONNECTION_STRING']


def sql_in(s):
    return ', '.join(map(str, map(psycopg2.extensions.adapt, s)))


def sql_date_range(val):
    token_to_days = {'last_7_days': 6, 'last_14_days': 13, 'last_30_days': 29, 'last_90_days': 89}
    val = datetime.now() - timedelta(days=token_to_days.get(val[0]))
Пример #26
0
from flask import Flask, render_template, request, session, Response
import jinja2
import json
import os
import time

app = Flask(__name__)

loader = jinja2.ChoiceLoader([
		app.jinja_loader,
		jinja2.FileSystemLoader('/root/discord/templates'),
])
app.jinja_loader = loader

queue = {}

@app.route("/queue", methods=["POST"])
def q():
	if all(x in request.form for x in ('id', 'channel_id', 'message', 'key', 'embed')) and len(request.form) == 5:
		try:
			if request.form['key'] != '':
				return render_template("index.html", RESPONSE='heck off')
			key = str(request.form['id'])
			channel_id = str(request.form['channel_id'])
			utc = int(time.time())
			msg = str(request.form['message'])
			embed = str(request.form['embed'])
			queue.update({key:[channel_id, msg, utc, embed]})
			return render_template("index.html", RESPONSE='added')
		except Exception as e:
			print(e)
Пример #27
0
# Create Flask instance
from flask import Flask
app = Flask(__name__)

# If frozen, we need define static and template paths
if check_frozen():
    app.root_path = rundir
    app.static_path = '/static'
    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(rundir, 'templates'))


def import_modules():
    """All modules that are available in Maraschino are at this point imported."""
    import modules.applications
    import modules.controls
    import modules.couchpotato
    import modules.currently_playing
    import modules.diskspace
    import modules.headphones
    import modules.index
    import modules.library
    import modules.log
    import modules.nzbget
    import modules.recently_added
Пример #28
0
import os
from flask import Flask
import jinja2


app=Flask(__name__)
app.config.from_pyfile("../settings.cfg")

app.jinja_loader = jinja2.FileSystemLoader([app.config["TEMPLATES_PATH"],
                                            '/work/QA/',
                                            app.config["STATIC_PATH"],
                                          ])

from app import views
Пример #29
0
app.config.update(
    CELERY_ALWAYS_EAGER=True,
    CELERY_CACHE_BACKEND="memory",
    CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
    CELERY_RESULT_BACKEND="cache",
    DEBUG=True,
    SEARCH_UI_SEARCH_API='http://localhost:5000/records',
    SEARCH_UI_BASE_TEMPLATE='invenio_theme/page.html',
)

FlaskCLI(app)
Babel(app)

# Set jinja loader to first grab templates from the app's folder.
app.jinja_loader = jinja2.ChoiceLoader([
    jinja2.FileSystemLoader(join(dirname(__file__), "templates")),
    app.jinja_loader
 ])

InvenioDB(app)
InvenioTheme(app)
InvenioRecords(app)
InvenioRecordsUI(app)
search = InvenioSearch(app)
search.register_mappings('records', 'data')
InvenioSearchUI(app)
InvenioIndexer(app)
InvenioPIDStore(app)

InvenioRecordsREST(app)

assets = InvenioAssets(app)
Пример #30
0
UPDATE_RATE = 1. / 30  # seconds
MAX_SAFE_PID_DISTANCE = 0.25 # how far off do we really think the loop time is before we just give up? - avoid weird edges and reset

logging.basicConfig(format='%(asctime)s %(levelname)s (%(name)s) %(message)s', level=logging.DEBUG)
_logger = logging.getLogger(__file__)

app = Flask(__name__)
app.config['SECRET_KEY'] = '8f86c03170811938fd9f798a60ad9ed4d4eed080'
socketio = SocketIO(app, debug=False)

app_path = os.path.join(os.path.dirname(os.path.abspath(__file__)))
static_path = os.path.join(app_path, 'static')

# make flask load from 'static/' instead of 'templates/'
app.jinja_loader = jinja2.FileSystemLoader(static_path)

app.network_state = None

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

@app.route('/sim')
def sim_index():
    return render_template('flask_sim.html')


@socketio.on('connect')
def handle_connect():
    _logger.info('connected')