def get_app(settings_module='awsmanager.settings'): app = Flask(__name__) app.config.from_object(settings_module) app.register_module(frontend) return app
def create_app(environment=None): ''' Create an app instance ''' app = Flask('backend') app.url_map.converters['ObjectId'] = BSONObjectIdConverter # Config app for environment if not environment: environment = os.environ.get('BACKEND_ENVIRONMENT', 'Local') app.config.from_object('backend.backend.settings.%s' % environment) # convert exceptions to JSON def make_json_error(ex): response = jsonify(message=str(ex)) response.status_code = (ex.code if isinstance(ex, HTTPException) else 500) return response for code in default_exceptions.iterkeys(): app.error_handler_spec[None][code] = make_json_error from backend.backend.views.api import api app.register_module(api) # initialize modules admin.init_app(app) db.init_app(app) login_manager.setup_app(app) mail.init_app(app) return app
def create_app(environment=None): """ Create an app instance """ app = Flask('core') # Allow CORS for all domains on all routes CORS(app) # Config app for environment if not environment: environment = os.environ.get('BACKEND_ENVIRONMENT', 'Dev') app.config.from_object('core.api.settings.%s' % environment) # convert exceptions to JSON def make_json_error(ex): response = jsonify( message=str(ex) ) response.status_code = ( ex.code if isinstance(ex, HTTPException) else 500 ) return response for code in default_exceptions.items(): app.error_handler_spec[None][code] = make_json_error from core.api.views.endpoints import api app.register_module(api) API.app = app
def create_app(environment=None): app = Flask('veritrans') app.url_map.converters['ObjectId'] = BSONObjectIdConverter # Config app for environment if not environment: environment = os.environ.get('BACKEND_ENVIRONMENT', 'Prod') app.config.from_object('core.api.settings.%s' % environment) # convert exceptions to JSON def make_json_error(ex): response = jsonify( message=str(ex) ) response.status_code = (ex.code if isinstance(ex, HTTPException) else 500) return response for code in default_exceptions.items(): app.error_handler_spec[None][code] = make_json_error from core.api.views.endpoints import api app.register_module(api) return app
def create_app(database): global app # create our little application :) app = Flask(__name__) app.debug = True app.config.from_object(__name__) app.secret_key = '^]CUCqFL6;wVz-w4%#ZYKTIB]kWT+3rfAq@_}(p;r%Mjq6umt9\>8-.){.u!uA*' # db import from libs.db import init_connection # db setup init_connection(database) # presenters from presenters.listing import listing from presenters.doc import doc # register modules app.register_module(listing) app.register_module(doc) # template filters @app.template_filter('test_format') def test_format(input): return input[::-1] return app
def create_app(): app = Flask(__name__) app.debug = config.IS_DEBUG app.url_map.converters['re'] = helpers.RegexConverter app.register_module(basemod) configure_handlers(app) return app
def create_app(): app = Flask(__name__) app.register_module(pkgmod.mod) app.register_module(modmod.mod) genshi = Genshi(app) return app
def create_app(config=None): app = Flask(__name__) app.config.from_object(latte_setting) db.init_app(app) app.register_module(admin) return app
def create_app(): """Create your application.""" app = Flask(__name__) app.config.from_object(settings) app.register_module(views) db.app = app db.init_app(app) db.create_all() return app
def create_app(): """ Create your application. Files outside the app directory can import this function and use it to recreate your application -- both bootstrap.py and the test directory do this. """ app = Flask(__name__) app.config.from_object(settings) app.register_module(views) return app
def create_app(app_name=APP_NAME): app = Flask(__name__) app.config.from_object(__name__) cur = os.path.abspath(__file__) sys.path.append(os.path.dirname(cur) + '/apps') for a in APPS: app.register_module(__import__('%s.views' % a).module) return app
def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'blahblah' app.config['ODESK_KEY'] = '56adf4b66aaf61444a77796c17c0da53' app.config['ODESK_SECRET'] = 'e5864a0bcbed2085' app.register_module(odesk, url_prefix='/odesk') ctx = app.test_request_context() ctx.push() self.app = app self.tc = self.app.test_client()
def setUp(self): app = Flask(__name__) app.config['SECRET_KEY'] = 'blahblah' app.config['ODESK_KEY'] = 'some_key' app.config['ODESK_SECRET'] = 'some_secret' app.debug = True app.register_module(odesk, url_prefix='/odesk') ctx = app.test_request_context() ctx.push() self.app = app self.tc = self.app.test_client()
def create_app(config_filename): app = Flask(__name__) app.config.from_pyfile(config_filename) @app.before_request def auth(): g.user = session.get('user_id', None) from .views import frontend app.register_module(frontend) return app
def Mojology (config_file = None, config_object = None): app = Flask (__name__) app.config.from_object ("mojology.default_config") app.config.from_envvar ("MOJOLOGY_SETTINGS", True) if config_file: app.config.from_pyfile (config_file) if config_object: app.config.from_object (config_object) app.register_module (browser) app.register_module (statsm, url_prefix = "/stats") def version (): try: import os from dulwich.repo import Repo repo = Repo (os.path.join (os.path.dirname (__file__), "..")) return repo.refs['refs/heads/master'] except: return None @app.template_filter ('datetime') def datetimeformat (value, format='%Y-%m-%d %H:%M:%S'): return value.strftime(format) @app.errorhandler (404) def handler_404 (error): return render_template ('http_error.html', error = error), 404 @app.errorhandler (500) def handler_500 (error): return render_template ('http_error.html', error = error), 500 @app.errorhandler (503) def handler_503 (error): return render_template ('http_error.html', error = error), 503 @app.route ("/about") @app.route ("/about/") @templated () def about (): return None @app.route ("/") def dashboard (): redirect (url_for ("browser.index")) app.version = version () return app
def create_app(database_uri, debug=False): app = Flask(__name__) app.debug = debug # set up your database app.engine = create_engine(database_uri) # add your modules app.register_module(frontend) # other setup tasks return app
def make_app(): app = Flask(__name__) from admin import admin from frontend import frontend config = app_config() app.config.from_object(config) app.register_module(frontend) app.register_module(admin) return app
def create_app(): app = Flask(__name__) if DEV: app.config.from_object('settings.Dev') else: app.config.from_object('settings.Prod') sys.path.append(os.path.join(BASE_DIR, APPS_DIR)) for module_name in APPS: app.register_module(load_module(module_name)) return app
def create_app(): """ Create your application. Files outside the app directory can import this function and use it to recreate your application -- both bootstrap.py and the `tests` directory do this. """ app = Flask(__name__) app.config.from_object(settings) app.register_module(views) app.jinja_env.filters['format_date'] = format_date app.jinja_env.filters['pygments_markdown'] = pygments_markdown app.jinja_env.filters['link_tags'] = link_tags app.jinja_env.filters['get_comment_count'] = get_comment_count return app
def make_app(config=None): app = Flask(__name__) if config: app.config.from_object(config) try: app.config.from_envvar(ENVVAR_NAME) except RuntimeError: print ENVVAR_NAME, 'not set. Using default configuration.' app.register_module(httpqueue.views.queue.view, url_prefix='/queue') httpqueue.views.queue.view.logger = app.logger httpqueue.model.init_model(app) return app
def create_app(): app = Flask(__name__) app.config.from_object('portal.settings') app.config['MONGOALCHEMY_DATABASE'] = 'portal' from portal.models import db db.init_app(app) from portal.login import door app.register_module(door) from portal.users import portal app.register_module(portal) return app
def create_app(wof_inst, soap_service_url=None): app = Flask(__name__) app.config.from_object(config.Config) app.wof_inst = wof_inst if not 'SOAP_SERVICE_URL' in app.config and soap_service_url: app.config['SOAP_SERVICE_URL'] = soap_service_url if USE_BLUEPRINTS: app.register_blueprint(rest) app.register_blueprint(wsdl) else: app.register_module(rest) app.register_module(wsdl) return app
def create_app(config=None): app = Flask(__name__) app.config.from_object('stutuz.configs') if config is not None: app.config.from_object(config) app.config.from_envvar('STUTUZ_CONFIG', silent=True) @app.context_processor def global_context(): return dict(locale=get_locale(), Markup=Markup, # Flask's seems to be superior to Genshi's ) handlers = NestedSetup(app.config.get('LOGBOOK_HANDLERS')) @app.before_request def push_handlers(): handlers.push_thread() @app.after_request def pop_handlers(response): handlers.pop_thread() return response for extension in genshi, db: extension.init_app(app) babel = Babel(app) @babel.localeselector def best_locale(): if 'locale' in request.args: return request.args['locale'] return request.accept_languages.best_match( map(str, babel.list_translations())) for middleware in app.config.get('MIDDLEWARES', ()): app.wsgi_app = middleware(app.wsgi_app) app.url_map.converters.update(CONVERTERS) for url_prefix, module in MODULES: module = import_string(module).mod app.register_module(module, url_prefix=url_prefix) return app
def init_app(defer_init_app=False): app = Flask(__name__) app.register_module(admin_module, url_prefix='/admin') if defer_init_app: freezer = Freezer() else: freezer = Freezer(app) @app.route('/') def index(): return 'Main index' @app.route('/page/<name>/') def page(name): return u'Hello\xa0World! ' + name @app.route('/where_am_i/') def where_am_i(): return (url_for('where_am_i') + ' ' + url_for('where_am_i', _external=True)) @app.route('/robots.txt') def robots_txt(): content = 'User-agent: *\nDisallow: /' return app.response_class(content, mimetype='text/plain') @app.route('/product_<int:product_id>/') def product(product_id): return 'Product num %i' % product_id @freezer.register_generator def product(): # endpoint, values yield 'product', {'product_id': 0} # Just a `values` dict. The endpoint defaults to the name of the # generator function, just like with Flask views yield {'product_id': 1} # single string: url yield '/product_2/' yield 'page', {'name': u'I løvë Unicode'} if defer_init_app: freezer.init_app(app) return app, freezer
def create_app(database, drop=False): # create our little application :) app = Flask(__name__) app.debug = True app.config.from_object(__name__) app.secret_key = 'DtJe0TW8ZQqLWT7UVE7alBN6vxxI6xBCDjVbcgY3' # db import from db import init_connection, table_drop # db setup init_connection(database) # db cleanup? if drop: table_drop('goals') # presenters from presenters.goals import goals from presenters.cdn import cdn # register modules app.register_module(goals) app.register_module(cdn) # template filters @app.template_filter('timestamp_format') def timestamp_format(timestamp): return utils.timestamp_format(timestamp) @app.template_filter('timestamp_distance') def timestamp_distance(timestamp): r = (utils.timestamp_new() - timestamp) / 60 / 60 / 24 if r > 0: if r > 1: return ''.join([str(r), ' days ago']) else: return 'yesterday' elif r < 0: if r < -1: return ''.join(['in ', str(abs(r)), ' days']) else: return 'tomorrow' else: return 'today' return app
def create_app(database, drop=False): # create our little application :) app = Flask(__name__) app.debug = True app.config.from_object(__name__) app.secret_key = 'DtJe0TW8ZQqLWT7UVE7alBN6vxxI6xBCDjVbcgY3' # db import from db import init_connection, table_drop # db setup init_connection(database) # db cleanup? if drop: table_drop('goals') # presenters from presenters.goals import goals from presenters.cdn import cdn # register modules app.register_module(goals) app.register_module(cdn) # template filters @app.template_filter('timestamp_format') def timestamp_format(timestamp): return utils.timestamp_format(timestamp) @app.template_filter('timestamp_distance') def timestamp_distance(timestamp): r = (utils.timestamp_new() - timestamp)/60/60/24 if r > 0: if r > 1: return ''.join([str(r), ' days ago']) else: return 'yesterday' elif r < 0: if r < -1: return ''.join(['in ', str(abs(r)), ' days']) else: return 'tomorrow' else: return 'today' return app
def create_app(config=None): app = Flask(__name__) app.config.from_object(human_settings) if config: app.config.from_object(config) db.init_app(app) @app.context_processor def inject_static(): """Make the static helper function available inside the templates""" return dict(static=static) app.register_module(admin) app.register_module(main) return app
def create_app(): app = Flask(__name__) app.config.from_object('polipoly2.default_settings') app.config.from_envvar('POLIPOLY2_SETTINGS', silent=True) register_converters(app) init_engine(app.config['DATABASE_URI']) def shutdown_session(response): session.remove() return response app.after_request(shutdown_session) from polipoly2.views import views app.register_module(views) return app
def create_app(config=None): app = Flask(__name__) app.config.from_object(default_settings) app.config.from_envvar('SIMBLIN_SETTINGS', silent=True) if config: app.config.from_object(config) db.init_app(app) @app.context_processor def inject_static(): """Make the static helper function available inside the templates""" return dict(static=static) app.register_module(admin) app.register_module(main) return app
def create_app(config=None): app = Flask(__name__) app.config.from_object(__name__) if config: app.config.from_object(config) # Configure logging here # Configure extensions # Error handlers if not app.debug: @app.errorhandler(404) def page_not_found(error): return render_template('404.html', error=error) @app.errorhandler(500) def server_error(error): return render_template('500.html', error=error) # Before and after handlers @app.before_request def before_request(): pass @app.after_request def after_request(request): # Play with your request here return request # Register modules app.register_module(views.front, url_prefix='') return app
def create_app(configuration_file=None): app = Flask(__name__) app.plugins = [] # cannot use namespace here, weak signals will disappear app.plugin_signals = { 'plugin-loaded': Signal(), 'page-loaded': Signal(), 'special-loaded': Signal(), 'page-preprocess': Signal(), 'page-postmarkdown': Signal(), 'page-treeprocess': Signal(), 'page-postprocess': Signal(), } # load a default config, and from configuration file app.config.from_object(defaults) if configuration_file: app.config.from_pyfile(configuration_file) app.db = WikiDb(app.config['REPOSITORY_PATH']) app.cache = Cache(app) app.register_module(frontend) # load plugins for plugin_name in app.config['PLUGINS']: import_name = 'qwappplugin.%s' % plugin_name qwappplugin = __import__('qwappplugin.%s' % plugin_name) plugin_module = getattr(qwappplugin, plugin_name) app.logger.debug('loading plugin %s' % plugin_module.plugin.version_string) plugin_module.plugin.register_app(app) return app
def create_app(configuration_file = None): app = Flask(__name__) app.plugins = [] # cannot use namespace here, weak signals will disappear app.plugin_signals = { 'plugin-loaded': Signal(), 'page-loaded': Signal(), 'special-loaded': Signal(), 'page-preprocess': Signal(), 'page-postmarkdown': Signal(), 'page-treeprocess': Signal(), 'page-postprocess': Signal(), } # load a default config, and from configuration file app.config.from_object(defaults) if configuration_file: app.config.from_pyfile(configuration_file) app.db = WikiDb(app.config['REPOSITORY_PATH']) app.cache = Cache(app) app.register_module(frontend) # load plugins for plugin_name in app.config['PLUGINS']: import_name = 'qwappplugin.%s' % plugin_name qwappplugin = __import__('qwappplugin.%s' % plugin_name) plugin_module = getattr(qwappplugin, plugin_name) app.logger.debug('loading plugin %s' % plugin_module.plugin.version_string) plugin_module.plugin.register_app(app) return app
def create_agent_app (): app = Flask(__name__) app.jinja_env.variable_start_string = '((' app.jinja_env.variable_end_string = '))' app.config.from_pyfile('agentconfig.py') # app.register_module(svn_repo_info) app.register_module(zentao) app.register_module(nexusServer) app.register_module(nexus) return app
def create_app(config_filename): app = Flask(__name__) app.config.from_pyfile(config_filename) # register views from einfachjabber.apps.mainsite.views import mainsite from einfachjabber.apps.blog.views import blog from einfachjabber.apps.stats.views import stats app.register_module(mainsite) app.register_module(blog, url_prefix="/blog") app.register_module(stats, url_prefix="/stats") # initiate flask-extensions mail.init_app(app) db.setup(app) # template filter setup @app.template_filter("to_mdown") def to_mdown(s): return Markup(markdown(s)) # set up logging if not app.debug: import logging from logging import FileHandler from logging.handlers import SMTPHandler mail_handler = SMTPHandler( app.config["MAIL_SERVER"], app.config["DEFAULT_MAIL_SENDER"], app.config["ADMINS"], "[einfachJabber.de] Failed", (app.config["MAIL_USERNAME"], app.config["MAIL_PASSWORD"]), ) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) file_handler = FileHandler(app.config["LOG_PATH"]) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) @app.errorhandler(404) def not_found(e): """Handles 404s""" pagetitle = "404 - Seite nicht gefunden" return render_template("404.html", pagetitle=pagetitle), 404 return app
def create_app(): """ Create your application. Files outside the app directory can import this function and use it to recreate your application -- both bootstrap.py and the `tests` directory do this. """ app = Flask(__name__) app.config.from_object(settings) babel = Babel(app, configure_jinja=True) babel.localeselector(_localeselector) babel.timezoneselector(_timezoneselector) app.register_module(views) app.register_module(rpc) app.register_module(tasks) app.secret_key = settings.secret_key return app
from cupcakes import settings from cupcakes.data import RECENT_SORT, tv_lookup from cupcakes.forms import ContactForm, SubmissionForm from cupcakes.geo import YahooGeocoder from cupcakes.views.search import search from cupcakes.views.submission import submission from flask import Flask, Response, g, json, render_template, redirect, request, session, url_for from pymongo import Connection, GEO2D import flask import urllib import urllib2 app = Flask(__name__) app.register_module(search) app.register_module(submission) # jinja2 loading @app.template_filter('datetimeformat') def datetimeformat_filter(value, format='%b %d %I:%M %p'): return value.strftime(format) @app.template_filter('airedon') def datetimeformat_filter(s): mt = s.get('mediatype', None) if mt == 'radio': return s.get('radio_callsign') elif mt == 'television': return u"%s (%s)" % (s.get('tv_channel', ''), s.get('tv_provider', ''))
from flask import Flask from vlasisku.extensions import genshi, database from vlasisku import components app = Flask(__name__) genshi.init_app(app) database.init_app(app) ETAG = database.etag app.config.from_object(__name__) app.register_module(components.app) app.register_module(components.general) app.register_module(components.opensearch) app.register_module(components.pages, url_prefix='/page')
from feather.helpers import mentions from feather import config from feather.databases import Bill, Bank, City, User, Nodeclass, Node, \ Topic, Reply, Notify import sys reload(sys) sys.setdefaultencoding('utf-8') app = Flask(__name__) #app.config.from_object('feather.config.DevConfig') # SQLite app.config.from_object('feather.config.ProConfig') # MySQL app.config.from_envvar('FEATHER_SETTINGS', silent=True) Markdown(app) app.register_module(blog) app.register_module(love) app.register_module(topic) app.register_module(account) app.register_module(reply) app.register_module(node) app.register_module(city) app.register_module(timesystem) db.init_app(app) cache.init_app(app) @app.before_request def before_request(): g.un = 1
import config.conf as conf from util import readable_time, linkify, clean app = Flask(__name__) app.config.from_object("ezlog2.config.conf") from ezlog2.blueprints.admin import admin admin.init_app(app) admin.base_template = 'admin/my_master.html' #assets = fassets.Environment(app) #assets.versions = 'hash:32' @app.before_request def something_before_request(): pass @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') return response import controllers import blueprints app.register_module(controllers.useraction.user_action, url_prefix="/useraction") app.jinja_env.filters['timesince'] = readable_time app.jinja_env.filters['linkify'] = linkify app.jinja_env.filters['clean'] = clean
import urllib from flask import Flask from route53.views.zones import zones from route53.views.main import main from route53.views.records import records from route53.views.slicehost import slicehost from auth import FlaskRealmDigestDB, AuthMiddleware app = Flask(__name__) app.register_module(main) app.register_module(zones, url_prefix='/zones') app.register_module(records, url_prefix='/records') app.register_module(slicehost, url_prefix='/slicehost') # load configuration app.config.from_pyfile('application.cfg') @app.template_filter('shortid') def shortid(s): return s.replace('/hostedzone/', '') @app.template_filter('urlencode') def urlencode(s): return urllib.quote(s, '/') #authentication
def create_app(): from controller.twitter import twitter_endpoint app = Flask(__name__) Bootstrap(app) app.register_module(twitter_endpoint, url_prefix='/') return app
from flask import Flask, request, url_for from app.db import session_remove from app.controller.project import app as project app = Flask(__name__) app.config.from_pyfile('settings.py') app.register_module(project) @app.after_request def shutdown_session(response): session_remove() return response def url_for_other_page(page): args = request.view_args.copy() args['page'] = page return url_for(request.endpoint, **args) app.jinja_env.globals['url_for_other_page'] = url_for_other_page
return user # HTTP error handling @app.errorhandler(404) def page_not_found(error): return render_template('errors/404.html'), 404 # Load views from .views.session import user_session from .views.default import default from .views.account import account # Register views app.register_module(default) app.register_module(user_session) app.register_module(account) # Additional setup import hooks import context_processors ''' Development environment setup Enables logging and fixes serving static files from the dev server (runserver.py). ''' if app.config['DEBUG']: import logging working_dir = os.path.dirname(os.path.abspath(__file__)) if not os.path.exists('%s/logs' % working_dir):
login_manager = LoginManager() login_manager.init_app(app) bcrypt = Bcrypt(app) toolbar = DebugToolbarExtension(app) bootstrap = Bootstrap(app) mail = Mail(app) db = SQLAlchemy(app) try: from app_server.views.base import base from app_server.views.user import user except ImportError as error_message: MESSAGE = '\n{0}\n{1}\n'.format(__file__, error_message) sys.exit(MESSAGE) # Force close python ATS ############################## app.register_module(base) app.register_module(user) try: from app_server.models.model_user import User except ImportError as error_message: MESSAGE = '\n{0}\n{1}\n'.format(__file__, error_message) sys.exit(MESSAGE) # Force close python ATS ############################## __author__ = 'Vladimir Roncevic' __copyright__ = 'Copyright 2017, Free software to use and distributed it.' __credits__ = ['Vladimir Roncevic'] __license__ = 'GNU General Public License (GPL)' __version__ = '1.4.0' __maintainer__ = 'Vladimir Roncevic' __email__ = '*****@*****.**'
class TestUrlAndDirectory(object): """By default, the 'url' and 'directory' settings of webassets are not used in Flask-Assets; that is, the values are automatically handled based on the configuration of the Flask app and the modules used. The user can disable the automatic handling by setting these values if he needs to for some reason. Let's test the different scenarios to ensure everything works. """ def setup(self): self.app = Flask(__name__, static_path='/app_static') import test_module if not Blueprint: self.module = Module(test_module.__name__, name='module', static_path='/mod_static') self.app.register_module(self.module) else: self.blueprint = Blueprint('module', test_module.__name__, static_url_path='/mod_static', static_folder='static') self.app.register_blueprint(self.blueprint) self.env = Environment(self.app) def test_config_values_not_set_by_default(self): assert not 'directory' in self.env.config assert not 'url' in self.env.config assert_raises(KeyError, self.env.config.__getitem__, 'directory') assert_raises(KeyError, self.env.config.__getitem__, 'url') def test_directory_auto(self): """Test how we handle file references if no root 'directory' is configured manually. """ assert not 'directory' in self.env.config root = self.app.root_path assert get_all_bundle_files(Bundle('foo'), self.env) == [root + '/static/foo'] # Modules prefixes in paths are handled specifically. assert get_all_bundle_files(Bundle('module/bar'), self.env) == [ root + '/test_module/static/bar' ] # Prefixes that aren't valid module names are just considered # subfolders of the main app. assert get_all_bundle_files(Bundle('nomodule/bar'), self.env) == [ root + '/static/nomodule/bar' ] # In case the name of a app-level subfolder conflicts with a # module name, you can always use this hack: assert get_all_bundle_files(Bundle('./module/bar'), self.env) == [root + '/static/module/bar'] # Custom static folder self.app.static_folder = '/' assert get_all_bundle_files(Bundle('foo'), self.env) == ['/foo'] def test_directory_custom(self): """A custom root directory is configured.""" self.env.directory = '/tmp' assert get_all_bundle_files(Bundle('foo'), self.env) == ['/tmp/foo'] # We do not recognize references to modules. assert get_all_bundle_files(Bundle('module/bar'), self.env) == ['/tmp/module/bar'] def test_url_auto(self): """Test how urls are generated if no 'url' is configured manually. """ assert not 'url' in self.env.config assert Bundle('foo').urls(self.env) == ['/app_static/foo'] # Urls for files that point to a module use that module's url prefix. assert Bundle('module/bar').urls(self.env) == ['/mod_static/bar'] # Try with a prefix that's not actually a valid module assert Bundle('nomodule/bar').urls( self.env) == ['/app_static/nomodule/bar'] # [Regression] Ensure that any request context we may have added # to the stack has been removed. from flask import _request_ctx_stack assert _request_ctx_stack.top is None def test_url_custom(self): """A custom root url is configured.""" self.env.url = '/media' assert Bundle('foo').urls(self.env) == ['/media/foo'] # We do not recognize references to modules. assert Bundle('module/bar').urls(self.env) == ['/media/module/bar'] def test_existing_request_object_used(self): """[Regression] Check for a bug where the url generation code of Flask-Assets always added a dummy test request to the context stack, instead of using the existing one if there is one. We test this by making the context define a custom SCRIPT_NAME prefix, and then we check if it affects the generated urls, as it should. """ with self.app.test_request_context( '/', environ_overrides={'SCRIPT_NAME': '/yourapp'}): assert Bundle('foo').urls(self.env) == ['/yourapp/app_static/foo']
import os from flask import Flask from flaskext.babel import Babel app = Flask(__name__) if os.getenv('DEV') == 'yes': app.config.from_object('urbanjungle.config.DevelopmentConfig') elif os.getenv('TEST') == 'yes': app.config.from_object('urbanjungle.config.TestConfig') else: app.config.from_object('urbanjungle.config.ProductionConfig') babel = Babel(app) from urbanjungle.controllers.frontend import frontend app.register_module(frontend) from urbanjungle.controllers.backend import backend app.register_module(backend, url_prefix='/admin')
from flask import Flask, redirect, url_for # application app = Flask(__name__) app.secret_key = 'foo' # modules from jsonifier.views.api import api from jsonifier.views.fluff import fluff from jsonifier.views.paste import paste app.register_module(fluff) app.register_module(api, url_prefix='/api') app.register_module(paste, url_prefix='/paste') # 404 redirect @app.errorhandler(404) def page_not_found(error): return redirect(url_for('paste.create'))
except ImportError: app.logger.warning('No config.py, using defaults or from envvar!') app.config.from_object(config_default) app.config.from_object(config) app.config.from_envvar('GRUF_CONFIG', silent=True) oid = OpenID(app) from gruf.views.main import main from gruf.views.login import login from gruf.views.qlist import qlist from gruf.views.abyss import abyss from gruf.views.quote import quote from gruf.views.users import users from gruf.views.releases import releases app.register_module(main) app.register_module(login, url_prefix='/login') app.register_module(qlist, url_prefix='/list') app.register_module(abyss, url_prefix='/abyss') app.register_module(quote, url_prefix='/quote') app.register_module(users, url_prefix='/users') app.register_module(releases, url_prefix='/releases') if not app.debug: import logging from gruf.logmail import PipeMailHandler from gruf.database import User mail_handler = PipeMailHandler(User.admin_mails(), 'GRuF: Error') mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler)
#!/usr/bin/python # coding: UTF-8 from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop import os from config import * from controllers import client as client_controller from controllers import server as admin_controller from flask import Flask, request, make_response, render_template_string app = Flask(__name__) app.secret_key = SECRET_KEY app.register_module(admin_controller.server, url_prefix='/server') app.register_module(client_controller.client) if not os.path.exists(upload_dir): os.mkdir(upload_dir, 0700) if not os.path.exists(download_dir): os.mkdir(download_dir, 0700) if __name__ == "__main__": http_server = HTTPServer(WSGIContainer(app)) http_server.listen(port) IOLoop.instance().start() #app.run(host="0.0.0.0", port=port, debug=True)
from views.pasteapp import pasteapp from views.userapp import userapp from views.tagapp import tagapp from views.rankapp import rankapp from views.database import db_session from views.forms import PasteForm #from utils import getCaptcha from views.filters import * from views.functions import * RECAPTCHA_PUBLIC_KEY = '6LeaILoSAAAAAOB1s0b5uGqDZ6Xbn1IkAR4wQpqJ' RECAPTCHA_PRIVATE_KEY = '6LeaILoSAAAAAAKm48RO9VK5_Knup3Z3glfJ9Of8' app = Flask(__name__) app.config.from_object(__name__) app.register_module(pasteapp, url_prefix="/paste") app.register_module(userapp, url_prefix="/user") app.register_module(tagapp, url_prefix="/tag") app.register_module(rankapp, url_prefix="/rank") app.secret_key = 'sdaghasdhsdh2346234uyqahg' app.jinja_env.filters['dateformat'] = dateformat app.jinja_env.filters['avatar'] = avatar d = {} @app.route('/') def index(): form = PasteForm(request.form, csrf_enabled=False) d['form'] = form d['syntax_list'] = getSyntaxList()
""" Author: Jan Palach Contact: [email protected] """ from flask import Flask from vtkweb.persistence.database import db_session app = Flask(__name__) app.config.from_object('settings') from vtkweb.controllers.admin import admin from vtkweb.controllers.frontend import frontend app.register_module(admin) app.register_module(frontend) @app.after_request def shutdown_session(response): db_session.remove() return response
from flask import Flask, render_template, session from flaskext.odesk import odesk app = Flask(__name__) app.config.from_pyfile('settings.py') app.register_module(odesk, url_prefix='/odesk') @app.route('/') def home(): return render_template('home.html') @app.route('/team') @odesk.login_required def team(): c = odesk.get_client() teamrooms = c.team.get_teamrooms_2() teams = [t for t in teamrooms if not t.update({'snapshots': c.team.get_snapshots_2(t.get('id'), online='all')})] return render_template('team.html', teams=teams) @odesk.after_login def save_user_session(): u = odesk.get_client().hr.get_user('me') session['user'] = { 'name': u'%s %s' % (u.get('first_name'), u.get('last_name')), 'url': u.get('public_url'), }
import numpy as np """ Add a places field to each study. On populating, use mongodb's update append to add it To pull a random place, simply load the study obj, look at the places, and choose a random ID. """ # TODO: Move from modules to blueprints, see http://flask.pocoo.org/docs/blueprints/ from root import root from admin import admin from login import login from matching import matching from results import results from study import study app.register_module(root) app.register_module(admin) app.register_module(login) app.register_module(matching) app.register_module(results) app.register_module(study) app.secret_key = "a10ad1a40b754a4d9b663fac60556a78" @app.route("/") def main(): studyObj = Database.getRandomStudy() if studyObj is None: return "Uh oh.. no study found in database." votesCount = Database.getVotesCount()
# -*- coding: utf-8 -*- from flask import Flask, session from view import heroes, items, rest, nav, maps, admin, tweet from sina import oauth #SERVER_PATH='http://dotabook.info/' #STATIC_PATH='http://1.dotabook.sinaapp.com/static/' #LOCAL_PATH='/home/deploy/DotABook/' SERVER_PATH = 'http://localhost:5000/' STATIC_PATH = 'http://localhost/static/' LOCAL_PATH = '/home/conan/workspace/app/DotABook/' app = Flask(__name__) app.debug = True app.config.from_object(__name__) app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' app.register_module(nav.view, url_prefix='') app.register_module(oauth.view, url_prefix='/oauth') app.register_module(heroes.view, url_prefix='/heroes') app.register_module(items.view, url_prefix='/items') app.register_module(rest.view, url_prefix='/rest') app.register_module(maps.view, url_prefix='/maps') app.register_module(admin.view, url_prefix='/admin') app.register_module(tweet.view, url_prefix='/tweet') if __name__ == '__main__': app.run()
# coding: utf-8 from restful.api import api from flask import Flask app = Flask(__name__) app.register_module(api, url_prefix='/myrestapi/')
fotojazz_processes = {} from flask import Flask app = Flask(__name__) app.config.from_object('project.settings') from project.fotojazz.views import mod app.register_module(mod)
class TestUrlAndDirectory(TempEnvironmentHelper): """By default, the 'url' and 'directory' settings of webassets are not used in Flask-Assets; that is, the values are automatically handled based on the configuration of the Flask app and the modules used. The user can disable the automatic handling by setting these values if he needs to for some reason. Let's test the different scenarios to ensure everything works. """ def setup(self): TempEnvironmentHelper.setup(self) self.app = Flask(__name__, static_path='/app_static') import test_module if not Blueprint: self.module = Module(test_module.__name__, name='module', static_path='/mod_static') self.app.register_module(self.module) else: self.blueprint = Blueprint('module', test_module.__name__, static_url_path='/mod_static', static_folder='static') self.app.register_blueprint(self.blueprint) self.env = Environment(self.app) def test_config_values_not_set_by_default(self): assert not 'directory' in self.env.config assert not 'url' in self.env.config assert_raises(KeyError, self.env.config.__getitem__, 'directory') assert_raises(KeyError, self.env.config.__getitem__, 'url') def test_directory_auto(self): """Test how we resolve file references through the Flask static system by default (if no custom 'env.directory' etc. values have been configured manually). """ assert not 'directory' in self.env.config root = self.app.root_path assert get_all_bundle_files(Bundle('foo'), self.env) == [root + '/static/foo'] # Modules prefixes in paths are handled specifically. assert get_all_bundle_files(Bundle('module/bar'), self.env) == [ root + '/test_module/static/bar' ] # Prefixes that aren't valid module names are just considered # subfolders of the main app. assert get_all_bundle_files(Bundle('nomodule/bar'), self.env) == [ root + '/static/nomodule/bar' ] # In case the name of a app-level subfolder conflicts with a # module name, you can always use this hack: assert get_all_bundle_files(Bundle('./module/bar'), self.env) == [root + '/static/module/bar'] # Custom static folder self.app.static_folder = '/' assert get_all_bundle_files(Bundle('foo'), self.env) == ['/foo'] def test_url_auto(self): """Test how urls are generated via the Flask static system by default (if no custom 'env.url' etc. values have been configured manually). """ assert not 'url' in self.env.config assert Bundle('foo').urls(self.env) == ['/app_static/foo'] # Urls for files that point to a module use that module's url prefix. assert Bundle('module/bar').urls(self.env) == ['/mod_static/bar'] # Try with a prefix that's not actually a valid module assert Bundle('nomodule/bar').urls( self.env) == ['/app_static/nomodule/bar'] # [Regression] Ensure that any request context we may have added # to the stack has been removed. from flask import _request_ctx_stack assert _request_ctx_stack.top is None def test_custom_load_path(self): """A custom load_path is configured - this will affect how we deal with source files. """ self.env.append_path(self.tempdir, '/custom/') self.create_files(['foo', 'module/bar']) assert get_all_bundle_files(Bundle('foo'), self.env) == [self.path('foo')] # We do not recognize references to modules. assert get_all_bundle_files(Bundle('module/bar'), self.env) == [self.path('module/bar')] assert Bundle('foo').urls(self.env) == ['/custom/foo'] assert Bundle('module/bar').urls(self.env) == ['/custom/module/bar'] # [Regression] With a load path configured, generating output # urls still works, and it still uses the flask system. self.env.debug = False self.env.url_expire = False assert Bundle('foo', output='out').urls(self.env) == ['/app_static/out'] def test_custom_directory_and_url(self): """Custom directory/url are configured - this will affect how we deal with output files.""" # Create source source file, make it findable (by default, # static_folder) is set to a fixed subfolder of the test dir (why?) self.create_files({'a': ''}) self.app.static_folder = self.tempdir # Setup custom directory/url pair for output self.env.directory = self.tempdir self.env.url = '/custom' self.env.debug = False # Return build urls self.env.url_expire = False # No query strings assert Bundle('a', output='foo').urls(self.env) == ['/custom/foo'] # We do not recognize references to modules. assert Bundle('a', output='module/bar').urls( self.env) == ['/custom/module/bar'] def test_existing_request_object_used(self): """[Regression] Check for a bug where the url generation code of Flask-Assets always added a dummy test request to the context stack, instead of using the existing one if there is one. We test this by making the context define a custom SCRIPT_NAME prefix, and then we check if it affects the generated urls, as it should. """ with self.app.test_request_context( '/', environ_overrides={'SCRIPT_NAME': '/yourapp'}): assert Bundle('foo').urls(self.env) == ['/yourapp/app_static/foo'] def test_glob(self): """Make sure url generation works with globs.""" self.app.static_folder = self.tempdir self.create_files({'a.js': 'foo', 'b.js': 'bar'}) assert list(sorted(self.mkbundle('*.js').urls( self.env))) == ['/app_static/a.js', '/app_static/b.js']
import sys import subprocess import argparse from flask.ext.cors import CORS, cross_origin from flask import Flask, make_response, request, abort, redirect, url_for, make_response app = Flask(__name__) cors = CORS(app) #=================================================# # Flask setting #=================================================# from APIs import root app.register_module(root.app, url_prefix="/") from APIs import document app.register_module(document.app, url_prefix="/api") from APIs import ElpisAPI app.register_module(ElpisAPI.app, url_prefix="/api/") #=================================================# # Command parser #=================================================# parser = argparse.ArgumentParser(description='=== Elpis Framework ===') parser.add_argument('--host', action="store", dest="host") parser.add_argument('--port', action="store", dest="port", type=int) parser.add_argument('--autodoc', action="store_true",