def application(): app_obj = create_app('TestConfig') #app_obj.config.from_object('config.TestConfig') #db.create_all() #g.db = sqlite3.connect(app_obj.config['SQLALCHEMY_DATABASE_URI']) return app_obj
def main(): container = WSGIContainer( factory.create_app('lafeeclotilde_api', 'LAFEECLOTILDE_API_SETTINGS')) server = Application([(r'.*', FallbackHandler, dict(fallback=container))], autoreload=True) server.listen(6101) IOLoop.instance().start()
def create_app(settings_override=None, register_security_blueprint=False): """Returns the Overholt API application instance""" app, apis = factory.create_app(__name__, __path__, settings_override, register_security_blueprint=register_security_blueprint) return app
def drop_db(): """Initialize database""" from factory import db, app app = create_app('default') app_context = app.app_context() app_context.push() db.drop_all() app_context.pop()
def __init__(self, filename): self.filename = filename self.core = Musicfinderby() self.app = create_app() thread = threading.Thread(target=self.run, args=()) thread.daemon = True thread.start()
def create_app(settings_override=None, register_security_blueprint=False): """Returns the Overholt API application instance""" app, apis = factory.create_app(__name__, __path__, settings_override, register_security_blueprint=register_security_blueprint) debug_log = logging.getLogger("debug") debug_log.info("Started up Service Components, Authorization_Management module successfully.") return app
def app(): try: args = {'prefix': 'test', 'settings': ''} app = create_app(args) app.testing = True return app except: raise
def init_db(): """Initialize database""" from factory import db, app app = create_app('default') app_context = app.app_context() app_context.push() db.create_all() from catalog.init_db import database_init x = database_init.fill_examples x() app_context.pop()
def app(request): app = create_app('TestConfig') ctx = app.app_context() ctx.push() def teardown(): ctx.pop() request.addfinalizer(teardown) return app
def app(request): app = create_app("config.TestingConfig") # Establish an application context before running the tests. ctx = app.app_context() ctx.push() def teardown(): ctx.pop() request.addfinalizer(teardown) return app
def app(request): """Session-wide test `Flask` application.""" app = create_app(db_path=TEST_DATABASE_URI) # Establish an application context before running the tests. ctx = app.app_context() ctx.push() def teardown(): ctx.pop() request.addfinalizer(teardown) return app
def app(): _app = create_app({ 'SERVER_NAME': 'testingapplication', 'TESTING': True, 'PY2NEO_BOLT': None, # without this, creating a relationship off the OGM threw an error 'PY2NEO_HOST': TEST_DB_URI, 'PY2NEO_HTTP_PORT': TEST_DB_HTTP, 'PY2NEO_BOLT_PORT': TEST_DB_BOLT }) with _app.app_context(): yield _app
def app(): try: args = { 'prefix': 'test/hiera', 'instance': 'api' } app = create_app(args) app.testing = True return app except: raise
def app(request): """Session-wide test `Flask` application writing to test database.""" app = create_app() app.testing = True # Establish an application context before running the tests. ctx = app.app_context() ctx.push() def teardown(): ctx.pop() request.addfinalizer(teardown) return app
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() self.client = self.app.test_client(use_cookies=True) # signup a new user response = self.client.post(url_for('catalog.signup'), data= { 'username': '******', 'password': '******', 'verify': '123', }) self.assertTrue(response.status_code == 302)
def create_app(settings_override=None, register_security_blueprint=True): """Returns the Overholt API application instance""" app = factory.create_app(DefaultConfig.PROJECT_NAME, DefaultConfig.PROJECT_ROOT, settings_override, register_security_blueprint=register_security_blueprint) @app.route("/") def index(): return render_template('index.html', active_nav_band = "Home", total_users=User.query.count()) return app
def create_app(settings_override=None, register_security_blueprint=False): """Returns the Overholt API application instance""" app, apis = factory.create_app(__name__, __path__, settings_override, register_security_blueprint=register_security_blueprint) debug_log = logging.getLogger("debug") debug_log.info("Started up Service Components, Service_Mgmnt module successfully.") # @app.after_request # def magic(response): # print("It happens") # return response return app
def sendmail(email,serstr): with create_app().app_context(): msg = Message(subject="账号注册激活邮件", recipients=[email]) msg.body = "testing" msg.html = "<a href='http://127.0.0.1:5000/active/%s'>点击激活</a>" % (serstr,) mail.send(msg) # print("发送成功!") # @app.task() # def sendmail(email,serstr): # # with.current_app().app_context(): # msg = Message(subject="账号注册激活邮件", recipients=[email]) # msg.body = "testing" # msg.html = "<a href='http://127.0.0.1:5000/active/%s'>点击激活</a>" % (serstr,) # mail.send(msg)
def app(request): """Session-wide test `Flask` application.""" settings_override = { 'TESTING': True, 'SQLALCHEMY_DATABASE_URI': TEST_DATABASE_URI } app = create_app(__name__, settings_override) # Establish an application context before running the tests. ctx = app.app_context() ctx.push() def teardown(): ctx.pop() request.addfinalizer(teardown) return app
def test_app(): settings = Settings({ 'database_engine_dsn': 'sqlite://', 'identity_server': 'http://localhost', 'secret_key': 'fake_secret', }) app = create_app( settings=settings, components=[ SettingsComponent(settings), SQLAlchemyEngineComponent(), SQLAlchemySessionComponent(), # RequestSessionComponent(), MockProvider(AuthProviderComponent), ], ) yield app
def create_app(settings_override=None, register_security_blueprint=False): """Returns the Overholt API application instance""" app, apis = factory.create_app( __name__, __path__, settings_override, register_security_blueprint=register_security_blueprint) #app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0' #app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0' #celery = Celery(__name__, broker=app.config['CELERY_BROKER_URL']) #celery.conf.update(api_CR_blueprint.config) #app.config["CELERY_INSTANCE"] = debug_log = logging.getLogger("debug") debug_log.info( "Started up Operator Components, Operator_CR module successfully.") return app
def main(): project_path = os.path.dirname(os.path.realpath(__file__)) container = WSGIContainer( factory.create_app( 'lafeeclotilde_admin', 'LAFEECLOTILDE_ADMIN_SETTINGS', template_folder=f'/{project_path}/templates', static_folder=f'/{project_path}/static' ) ) server = Application( [ (r'/websocket/', socket_handler.WebSocket), (r'.*', FallbackHandler, dict(fallback=container)) ], autoreload=True ) server.listen(6100) IOLoop.instance().start()
def setUp(self): sqlite_in_memory_uri = 'sqlite://' config = {'SQLALCHEMY_DATABASE_URI': sqlite_in_memory_uri, 'TESTING': True, 'WTF_CSRF_ENABLED': False} app = create_app(config) self.test_user_email = 'tester@test_users.com' self.test_user_password = '******' with app.app_context(): db.create_all() self.test_user = User(self.test_user_email, self.test_user_password, 'Mr. Tester', timezone=-5) db.session.add(self.test_user) db.session.add(PostState(name='draft')) db.session.add(PostState(name='published')) db.session.commit() self.app = app.test_client() self.get_context = app.app_context
def create_app(settings_override=None, register_security_blueprint=False): """Returns the Overholt API application instance""" app, apis = factory.create_app( __name__, __path__, settings_override, register_security_blueprint=register_security_blueprint) debug_log = logging.getLogger("debug") debug_log.info( "Started up Operator Components, Operator_SLR module successfully.") # for api in apis: # @api.representation('application/xml') # def output_xml(data, code, headers=None): # if isinstance(data, dict): # xm = {"response": data} # resp = make_response(xmltodict.unparse(xm, pretty=True), code) # resp.headers.extend(headers) # return resp return app
from flask.ext.script import Manager from factory import create_app from app.models import * app = create_app('app','config.DevConfig') # Initialize Manager manager = Manager(app) @manager.command def create_db(): with app.app_context(): app.db.create_all() @manager.command def drop_db(): user_input = '' while user_input not in ['YES','q']: user_input = raw_input("DROP Database Tables? [YES,q]") if user_input == 'YES': with app.app_context(): app.db.drop_all() else: return if __name__ == '__main__': manager.run()
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from flask import request, jsonify from flask.views import MethodView from factory import create_app from models import Post app = create_app() @app.route('/') def hello_rest(): return ''' <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Code Service</title> <link href="//cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1>Flask RESTful API Example</h1><hr> <p>Welcome to Flask RESTful API Example!</p> </div>
import argparse from factory import create_app, register_blueprints if __name__ == '__main__': parser = argparse.ArgumentParser('Launch the application') parser.add_argument('--config',dest='config',default='dev',help='App configiguration') args = parser.parse_args() conf = args.config config = None if conf == 'dev': config = 'config.DevConfig' elif conf == 'prod': config = 'config.ProdConfig' app = create_app('app',config) with app.app_context(): from app.resources.jrnls import jrnls register_blueprints(app,jrnls) app.run()
from factory import create_app app = create_app('ProdConfig')
''' This file is the acting web server. @host, tells the OS (guest VM) to accept connections from all public IP addresses. Note: both the handler, and logger has levels. If the level of the logger is higher than that of the handler, no messages will be handled by the corresponding handler. ''' import sys import pytest from factory import create_app # run unit test if sys.argv[1] == 'test': pytest.main([ '--cov', '.', 'test/live_server' ]) # run application else: app = create_app() app.run(host='0.0.0.0')
#!/usr/bin/env python import os import sys COV = None if os.environ.get('FLASK_COVERAGE'): import coverage COV = coverage.coverage(branch=True, source=['/vagrant/Projects/junzhou365/catalog/', '/vagrant/Projects/junzhou365/home/']) COV.start() from factory import create_app from flask.ext.script import Manager app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) @manager.command def init_db(): """Initialize database""" from factory import db, app app = create_app('default') app_context = app.app_context() app_context.push() db.create_all() from catalog.init_db import database_init x = database_init.fill_examples x() app_context.pop() @manager.command def drop_db():
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() self.client = self.app.test_client(use_cookies=True)
Note: both the handler, and logger has levels. If the level of the logger is higher than that of the handler, no messages will be handled by the corresponding handler. ''' import sys import pytest from factory import create_app # run unit test if len(sys.argv) > 1: if sys.argv[1] == 'test': pytest.main([ '--cov', '.', 'test/live_server' ]) elif sys.argv[1] == 'run-api': args = { 'prefix': 'test/hiera', 'instance': 'programmatic' } app = create_app(args) app.run(host='0.0.0.0') # run application else: app = create_app() app.run(host='0.0.0.0')
from factory import create_app app = create_app('CONFIG_DEV', 'app') if __name__ == '__main__': app.run(port=app.config['PORT'])
from flask import Flask from flask import jsonify from config import DevConfig from factory import create_app app = create_app(DevConfig) if __name__ == '__main__': app.run()
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all()
import platform from factory import create_app if platform.system() == 'Windows': application = create_app(env='development') application.run() if platform.system() == 'Linux': pass
from factory import create_app from flask.ext.sqlalchemy import SQLAlchemy application = create_app() application.template_folder = 'app/templates' application.static_folder = 'app/static' class UnLockedAlchemy(SQLAlchemy): def apply_driver_hacks(self, app, info, options): if not "isolation_level" in options: options["isolation_level"] = "READ COMMITTED" return super(UnLockedAlchemy, self).apply_driver_hacks(app, info, options) db = UnLockedAlchemy(application) import tasks from models import *
def app(): app = create_app() app.testing = True return app
''' This file may by called: - Directly during developement or - The WSGI during production ''' import os from factory import create_app app = create_app(os.getenv('CONFIG_NAME', default='default')) if __name__ == '__main__': app.run(port=6060, host='0.0.0.0', debug=True)
"""RQ tasks.""" import os from factory import create_app if os.environ.get('DEV_ENV', None): env = 'dev' else: env = 'prod' app = create_app(env).app app.app_context().push()
""" Flask-Script Manager commands to be run from command line. Examples python manager.py --help python manager.py create_db """ from flask_script import Manager from extensions import db from models import User from factory import create_app manager = Manager(create_app()) @manager.command def gen_secret(): """Generate a secret_key for Flask-Login security and write it into secret.py.""" import os import binascii key = binascii.hexlify(os.urandom(24)) with open('secret.py', 'wt') as f: f.write("SECRET_KEY = '{}'".format(key)) @manager.command def create_db(): """Create database and its schema. Add post states 'draft' and 'published'""" db.create_all()
''' Created on Apr 25, 2016 @author: gonzalo ''' from factory import create_app from model import User from extensions import db if __name__ == '__main__': app = create_app("local") db.create_all(app=app)
from .bootstrap import bootstrap from factory import create_app from flask import redirect,url_for app = create_app(__name__,'config.py') bootstrap(app) @app.route('/') def index(): return redirect('/common/')
import web import factory app, sse = factory.create_app() web.app = app web.sse = sse
import requests import time import validators from factory import create_app from flask import request, render_template, current_app, session # Set root dir APP_ROOT = os.path.dirname(os.path.abspath(__file__)) config_path = os.path.join(APP_ROOT, 'config.json') device_str = os.environ.get("BERTRON_DEVICE") # Define Flask app app = create_app(APP_ROOT, config_path, device_str) app.secret_key = "super secret key" # Define apps home page @app.route('/') def index(): if 'id' not in session: # initialize session defaults session['id'] = datetime.now().strftime("%Y%m%d%H%M%S%f") session['visualize'] = True session['top_n'] = 25 return render_template('index.html', generated_audio=False, visualize=session['visualize'], top_n=session['top_n']) # Define submit function
# -*- coding: utf-8 -*- import functools from flask import redirect, request, render_template, make_response, g from factory import create_app from model import db, Tenant app = create_app('multitenant') def requires_tenant(*args, **kwargs): def wrapper(f): @functools.wraps(f) def wrapped(*args, **kwargs): tenant_id = request.cookies.get('tenant_id', None) if not tenant_id: return redirect('/') tenant_name = request.headers.get('X-TENANT-NAME', None) lookup_made = False if not tenant_name: db.session.execute('SELECT pg_sleep(1)') tenant = Tenant.query.filter_by(id=tenant_id).first() g.tenant_name = tenant.name lookup_made = True resp = make_response(f(*args, **kwargs)) resp.headers['X-TENANT-LOOKUP'] = 'yes' if lookup_made else 'no' return resp return wrapped return wrapper
#-*- coding: utf-8 -*- from flask import g, request, url_for, redirect, render_template from flask.ext.login import LoginManager, current_user from factory import create_app from urls import register_blueprint from config import config_object from flask_debugtoolbar import DebugToolbarExtension from models.user import UserHandBook from models.account.data import Notice, PersonNotice app = create_app(config_object) # toolbar = DebugToolbarExtension(app) login_manager = LoginManager() login_manager.login_message = None login_manager.init_app(app) login_manager.login_view = "user.login" def page_recipe(pages, adjacent_pages=3): paginator = pages.paginator page_numbers = [n for n in range( pages.number - adjacent_pages, pages.number + adjacent_pages + 1) if n > 0 and n <= paginator.num_pages] return page_numbers app.jinja_env.filters['page_recipe'] = page_recipe
import re from datetime import timedelta import flask_excel as excel from flasgger import Swagger from flask import jsonify, session, request, current_app from flask_cors import CORS import factory from model.result import Result app = factory.create_app() Swagger(app) excel.init_excel(app) CORS(app, supports_credentials=True) app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=1) @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 @app.errorhandler(400) def page_not_found(error): return 'param error', 400 @app.errorhandler(500)
def app(): app = create_app(DevConfig) return app
Note: both the handler, and logger has levels. If the level of the logger is higher than that of the handler, no messages will be handled by the corresponding handler. ''' import sys import pytest from factory import create_app # run unit test if len(sys.argv) > 1: if sys.argv[1] == 'test': pytest.main([ '--cov', '.', 'test/live_server' ]) elif sys.argv[1] == 'run': args = { 'prefix': 'test', 'settings': '' } app = create_app(args) app.run(host='0.0.0.0') # run application else: app = create_app() app.run(host='0.0.0.0')
import os from flask_migrate import Migrate from factory import create_app from objects.database import db app = create_app(os.getenv('FLASK_CONFIG_STATUS')) migrate = Migrate(app, db) if __name__ == '__main__': app.run()
def make_app(): import factory application = factory.create_app(app_name, cwd, settings_override=config) db.init_app(application) return application
from factory import create_app from flask import render_template application = create_app() @application.route('/home') def home(): """ This function just responds to the browser URL localhost:5000/ :return: the rendered template 'home.html' """ return render_template('home.html') if __name__ == "__main__": application.run(debug=True)
def setUp(self): self.app = factory.create_app()