def get_app(): # Import inside the function so that invoke will work before dependencies # are installed from app.factory import create_app from app.settings import DevConfig, ProdConfig if os.environ.get("SCRIBNOTE_ENV") == 'prod': app = create_app(ProdConfig) else: app = create_app(DevConfig) return app
def create_app(self): app = create_app(config=self.BASE_APP_CONFIG.copy()) handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) app.logger.addHandler(handler) return app
def app(): _app = create_app('frink_test') ctx = _app.test_request_context() ctx.push() yield _app model_registry.drop_tables() ctx.pop()
def app(request): app = create_app(TESTING=True, SQLALCHEMY_DATABASE_URI=TEST_DATABASE_URI) ctx = app.app_context() ctx.push() yield app ctx.pop()
def create_app(self): config = self.BASE_APP_CONFIG.copy() config.update( DEBUG=False, WTF_CSRF_ENABLED=False, # This speeds tests up considerably. SECURITY_PASSWORD_HASH='plaintext', CACHE_NO_NULL_WARNING=True, ) return create_app(config=config)
def test_loggers(self): app = create_app(config_file='conf/testing.py') self.assertEqual(len(app.logger.handlers), 1) extra_config = {'SLACK_API_TOKEN': 'token', 'SLACK_CHANNEL': '#general', 'SLACK_USERNAME': '******', 'SLACK_ICON_URL': 'whatever', } app.config.update(extra_config) configure_logging(app) self.assertEqual(len(app.logger.handlers), 2)
def app(request): test_config = { 'SQLALCHEMY_DATABASE_URI': TESTDB_URI, 'TESTING': True, 'SCHEDULER': False, 'ARDUINO_IP': '127.0.0.1' } test_app = create_app(test_config) ctx = test_app.app_context() ctx.push() yield test_app ctx.pop()
def setUp(self): # set up first item app = create_app() self.app = app.test_client() task_1 = { "name": "dummy task", "done": False } self.test_1 = task_manager.create('test', task_1) task_2 = { "name": "dummy task 2", "done": True } self.test_2 = task_manager.create('test', task_2)
def app(provider): app = create_app(**{ 'TESTING': True, 'SQLALCHEMY_DATABASE_URI': TEST_DATABASE_URI, 'PREFERRED_URL_SCHEME': 'http', 'WTF_CSRF_ENABLED': False, 'OIDC_CLIENT': { 'issuer': config['issuer'], 'client_id': 'test-client', 'client_secret': 'test-secret' }, 'OIDC_PROVIDER': { 'issuer': 'https://localhost:5000', 'subject_id_hash_salt': 'salt' } }) ctx = app.app_context() ctx.push() yield app ctx.pop()
# ---------------------------------------------------------------------------------------- # Auteur : Thierry Blais Brossard <*****@*****.**> # Description : # Date : Juillet 2014 # --------------------------------------------------------------------------------------- from app.factory import create_app __author__ = 'thierry' if __name__ == '__main__': app = create_app("0.0.0.0", 5000, "Sketch") app.run()
from app.factory import create_app app = create_app(__name__) if __name__ == "__main__": app.debug = True app.run()
from flask_alchemydumps import AlchemyDumps, AlchemyDumpsCommand from flask_migrate import Migrate, MigrateCommand from flask_script import Manager from flask_security.recoverable import send_reset_password_instructions from random import choice from sqlalchemy.exc import IntegrityError import codecs import os import string import subprocess import yaml app = create_app() #pylint: disable=invalid-name migrate = Migrate(app, db) #pylint: disable=invalid-name manager = Manager(app) #pylint: disable=invalid-name manager.add_command('db', MigrateCommand) #manager.add_command("assets", ManageAssets) alchemydumps = AlchemyDumps(app, db) manager.add_command('alchemydumps', AlchemyDumpsCommand) def gettext_for(text): ''' Generate a jinja2 "{{ gettext() }}" line for text. '''
from app import factory import app app = factory.create_app(celery=app.celery) # app.run(port=5000) # if __name__ == "__main__":
#!/usr/bin/env python import os if os.path.exists('.env'): print('Importing environment from .env...') for line in open('.env'): var = line.strip().split('=') if len(var) == 2: os.environ[var[0]] = var[1] from flask.ext.script import Manager from app.factory import create_app, db from app.models import Users app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) @manager.command def adduser(username): """ Register a new user. """ from getpass import getpass password = getpass() password2 = getpass(prompt='Confirm: ') if password != password2: import sys sys.exit('Error: passwords do not match.') db.create_all() user = Users(username=username, password=password) db.session.add(user)
from app import celery from app.factory import create_app create_app(celery)
def run(): app = create_app() configure_celery(app) app.run(host='localhost', port=5000, debug=True)
def create_app(*args, **kwargs): app = factory.create_app(*args, **kwargs) return add_logging_to_app(app)
def setUp(self): pwd = os.path.abspath(os.path.dirname(os.getcwd())) config_path = os.path.join(pwd, 'config/config.yaml') app = create_app(config_name="DEVELOPMENT", config_path=config_path) app.config['TESTING'] = True self.app = app.test_client()
""" Entry Point for application, running this will run the app """ import argparse from app.config import dev_cli_choices from app.factory import create_app if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", choices=dev_cli_choices, default="Dev", help="Config type to use. (Default: Dev)") parser.add_argument("-H", "--host", type=str, default="127.0.0.1", help="Web Server Host (Default: 127.0.0.1)") parser.add_argument("-p", "--port", type=int, default=8000, help="Web Server Port (Default: 8000)") args = parser.parse_args() app = create_app(args.config) app.run(host=args.host, port=args.port)
def setUp(self): self.app = factory.create_app('test') self.client = self.app.test_client()
def test_dev_config(): app = create_app('dev') assert app.config['MODE'] == 'dev' assert app.config['DEBUG'] assert not app.config['TESTING']
def test_prod_config(): app = create_app('prod') assert app.config['MODE'] == 'prod' assert not app.config['DEBUG'] assert not app.config['TESTING']
# -*- coding: utf-8 -*- from flask_script import Manager, Server from app.factory import create_app app = create_app('dev') manager = Manager(app) manager.add_command('runserver', Server()) if __name__ == '__main__': manager.run()
from app import factory celery = factory.create_app('worker')
def app(): myapp = create_app() myapp.config['TESTING'] = True # response_class return myapp
""" run.py Main entrypoint to app """ import os from app.factory import create_app app = create_app(os.getenv('FLASK_CONFIG') or 'default')
def main(): app = create_app(config_file='conf/development.py') app.run(debug=True)
def create_shortly(info): MODE = os.environ.get('SHORTLY_MODE', 'dev') return create_app(MODE)
from app.factory import create_app, celery_app app = create_app(config_name="PRODUCTION") app.app_context().push()
def setUpClass(self): self.app = create_app() self.client = self.app.test_client() self._ctx = self.app.test_request_context() self._ctx.push() db.create_all()
""" WSGI callable as called by uwsgi. Production equivalent of run.py. """ from app.factory import create_app app = create_app(config_file='conf/production.py')
def _make_context(): return dict( app=create_app(), db=db )
def test_testing_config(): app = create_app('testing') assert app.config['MODE'] == 'testing' assert app.config['DEBUG'] assert app.config['TESTING']
#!/usr/bin/env python # -*- coding: utf-8 -*- """Management script used for database operations. For all other tasks, use invoke. """ import os from flask.ext.script import Manager, Shell from flask.ext.migrate import MigrateCommand from app.factory import create_app from app.settings import DevConfig, ProdConfig if os.environ.get("PSYGIST_ENV") == 'prod': app = create_app(ProdConfig) else: app = create_app(DevConfig) def _make_context(): from app.books.models import Author, Book from app.notes.models import Note from app.users.models import User from app.meta.database import db from flask import url_for, current_app from tests.utils import fake app = current_app return locals() manager = Manager(app) manager.add_command('shell', Shell(make_context=_make_context))
def setUp(self): app = create_app() self.app = app.test_client() r = Redis() self.profile_manager = ProfileManager(db=r)
# coding: utf-8 import logging # call this right away to handle monkey patching before anything happens from app.utils import monkey_patch # noqa from app.extensions.flask_celery import celery # noqa from app.factory import create_app logger = logging.getLogger(__name__) try: app = create_app(__name__) except ImportError as e: logger.error(e) raise from app.tasks import * # noqa
__author__ = 'teddy' from app.factory import socketio, db, create_app from flask.ext.script import Manager from flask.ext.migrate import MigrateCommand from models.users import User manager = Manager(create_app()) manager.add_command('db', MigrateCommand) @manager.command def runserver(): socketio.run(manager.app, host=manager.app.config['SERVER_IP'], port=manager.app.config['SERVER_PORT']) @MigrateCommand.command def setup(): db.create_all(app=manager.app) with manager.app.app_context(): u = User() u.username = '******' u.password = '******' db.session.add(u) db.session.commit() if __name__ == '__main__': manager.run()
import sys from datetime import datetime import random import faker from sqlalchemy import func from app.adresses.models import Address from app.categories.models import Category from app.comments.models import Comment from app.factory import db, create_app, bcrypt from app.file_Uploads.models import ProductImage from app.products.models import Product, PartData from app.roles.models import Role from app.authentication.models import User create_app().app_context().push() fake = faker.Faker() def generate_image(model): # pattern = "".join([random.choice(['?', '#']) for i in range(0, 10)]) + '.png' filename_pattern = "".join( fake.random_choices(elements=('?', '#'), length=fake.random_int(min=16, max=32))) + '.png' # file_name=fake.md5(raw_output=False) + '.png' return model(file_name="".join(fake.random_letters(length=16)) + '.png', file_path=fake.image_url(width=None, height=None), file_size=fake.random_int(min=1000, max=15000), original_name=fake.bothify(text=filename_pattern)) """user and seller seed"""
def app(tmp): return create_app()
from app.factory import create_app, celery_app app = create_app(config_name="DEVELOPMENT") app.app_context().push() if __name__ == "__main__": app.run(host='0.0.0.0', port=8085, debug=True)
#!/usr/bin/env python # -*- coding: utf-8 -*- """Management script used for database operations. For all other tasks, use invoke. """ import os from flask.ext.script import Manager, Shell from flask.ext.migrate import MigrateCommand from app.factory import create_app from app.settings import DevConfig, ProdConfig if os.environ.get("PSYGIST_ENV") == 'prod': app = create_app(ProdConfig) else: app = create_app(DevConfig) def _make_context(): from app.books.models import Author, Book from app.notes.models import Note from app.users.models import User from app.meta.database import db from flask import url_for, current_app from tests.utils import fake app = current_app return locals() manager = Manager(app) manager.add_command('shell', Shell(make_context=_make_context)) manager.add_command('db', MigrateCommand)
# -*- coding: utf-8 -*- from app.factory import create_app from app.settings import config app = create_app(config) if __name__ == '__main__': app.run(host=config.SERVER_HOST, port=config.SERVER_PORT, threaded=True)
def create_app(self): return create_app(config=self.BASE_APP_CONFIG.copy())
import logging import os from app import factory log_format_string = "%(asctime)s PID- %(process)d %(levelname)s %(pathname)s %(funcName)s %(lineno)d %(message)s" # noqa: E501 logging.basicConfig(level=logging.INFO, format=log_format_string) app = factory.create_app(os.getenv("FLASK_ENV"))
def create_app(settings_override=None): """Return only the flask app instance""" app = factory.create_app(__name__, __path__, settings_override) return app
import os from flask_cors import CORS from flask_script import Manager from app.factory import create_app config_name = os.getenv('FLASK_CONFIG', 'base') app = create_app(config_name) CORS(app, supports_credentials=True) manage = Manager(app) if __name__ == '__main__': manage.run()
def app(): app = create_app(testing=True) yield app
def create_app(self): return create_app(config_file='conf/testing.py')
# _*_ coding: utf-8 _*_ from __future__ import absolute_import from celery import Celery from app.factory import create_app flask_app = create_app(register_blueprints=False) flask_app.app_context().push() def make_celery(app): celery_ = Celery('celery_app') celery_.config_from_object('config') TaskBase = celery_.Task celery_.app = app class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) celery_.Task = ContextTask return celery_ app = make_celery(flask_app) # app = Celery('celery_app', backend='redis://localhost:6379/0') if __name__ == '__main__': with flask_app.app_context(): app.start()
def test_create_app_with_broken_config(): CONFIG_MAPPGING["broken-import-config"] = "broken-import-config" with pytest.raises(FileNotFoundError): create_app(ENABLED_MODULES, "broken-import-config") del CONFIG_MAPPGING["broken-import-config"]
def test_app(app, db, credstash, aws_env): app_backup = app yield create_app() app = app_backup db.app = app
def run(): BASE_DIR = os.path.abspath(os.path.dirname(__file__)) application = factory.create_app(os.path.join(BASE_DIR, 'config.py')) application.run(host=config.HOST, port=config.PORT)
# TODO: __SHORT TERM__ # TODO: Figure out flask versioning. # TODO: CompareText get list, get single, post and delete # TODO: User get list, get single, post and delete # TODO: TwoWayDiff get list, get single, post and delete # TODO: 201 created - created a new resource # TODO: 202 accepted - successfully set the request to perform long running task # TODO: 304 not modified - performed a conditional GET request and access is allowed, but nothing was done. # TODO: 400 bad request - could not understand request # TODO: 401 not auth - does not correct auth for action # TODO: 403 forbidden - although authed, not allowed to perform action # TODO: 404 not found - not found anything matching the Request-URI. # TODO: 500 internal server error - app = create_app(__name__, 'config') app.config['TRAP_HTTP_EXCEPTIONS'] = True db = SQLAlchemy(app) api = Api(app, prefix='/v1', catch_all_404s=True) from app.routes import routes # TODO: Remove when database migrations are in place. db.drop_all() db.create_all() routes.map_login_route(api) routes.map_user_routes(api)
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() self.client = self.app.test_client()
from flask.ext.script import Manager from app.factory import create_app app = create_app() manager = Manager(app) if __name__ == '__main__': manager.run()
from app.factory import create_app app = create_app(config_file='conf/twelvefactor.py')
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all()
''' Created on Apr 25, 2016 @author: gonzalo ''' from app.factory import create_app from extensions import db app = create_app("local") from model import User import json @app.route('/user', methods=['POST']) def create(): user = User(name="John", surname="Connor") try: db.session.add(user) db.session.commit() except Exception, ex: db.session.rollback() raise ex return json.dumps(user.to_json()) @app.route('/user', methods=['PUT']) def change(): user = User.query.filter_by(name="John").first() user.surname = "Lewis" try:
from app import celery from app.factory import create_app from app.utils.celery_util import init_celery app = create_app() init_celery(app, celery)