def main(argv): if '--debug' or '-d' in argv: # run debug mode for development from app.config import DevelopmentConfig as dev_config app = create_app(config=dev_config) else: # run app for production from app.config import Config as config app = create_app(config=config) app.run(host='0.0.0.0', port=5000)
def test_create_prod_app(self): from app import config config.ProductionConfig.ACCOUNT_SERVICE_URL = None with self.assertRaises(ConfigurationError) as ex: create_app(self.config) self.assertIn('not set', ex.exception.args[0]) env.read_envfile(self.env_file) reload(config) self.assertIsInstance(create_app(self.config), Application)
def client(): class Object(object): pass mock_db = Object() mock_db.session = {} return testing.TestClient(create_app(mock_db))
def db_add_user(config, user_email): """Adding user""" if not os.path.isfile(config.DB_FILE): print('[WARNING] File [{}] doesn\'t exist.'.format(config.DB_FILE)) sys.exit(1) app = create_app(config_object=config) with app.app_context(): DB.init_app(app) user = User.query.filter_by(email=user_email).first() if user: print('[WARNING] User [{}] is already added. '.format(user_email)) sys.exit(0) admin = User(email=user_email, password=BCRYPT.generate_password_hash(uuid.uuid4().hex), gdpr_version=config.GDPR_VERSION, is_active=True) DB.session.add(admin) DB.session.commit() print( '[SUCCESS] Admin user was set. For activation, you should reset password.' ) sys.exit(0)
def create_access_rights(config): """Create access rights""" with open('rights.yaml', 'r') as stream: roles_rights = yaml.load(stream) if not os.path.isfile(config.DB_FILE): print('[WARNING] File [{}] doesn\'t exist.'.format(config.DB_FILE)) sys.exit(1) app = create_app(config_object=config) with app.app_context(): DB.init_app(app) for group in roles_rights['rights']: for rule in roles_rights['rights'][group]: rights = Rights(name=get_rights_name(group, rule['permission']), group=group, permission=rule['permission'], description=rule['description']) DB.session.add(rights) DB.session.commit() print('[SUCCESS] Rights imported to [{}] file'.format(config.DB_FILE)) sys.exit(0)
def setUp(self): self.sviewer = create_app(os.path.join('..', 'config_unittest.py')) self.sviewer.logger.setLevel(logging.ERROR) self.sviewer.config['TESTING'] = True self.app = self.sviewer.test_client() with self.sviewer.app_context(): db.create_all()
def setUp(self): """Initialize test variables """ self.app = create_app(config_name="testing") self.client = self.app.test_client self.user_data = { 'name': 'guy', 'email': '*****@*****.**', 'password': '******' } self.bucketlist = { 'name': 'list1', 'date': '01012018', 'description': 'Some description' } self.bucketlist_item1 = { 'name': 'bucketlist_item1', 'description': 'Do stuff' } self.bucketlist_item2 = { 'name': 'bucketlist_item2', 'description': 'Do a little more stuff' } with self.app.app_context(): db.session.close() db.drop_all() db.create_all()
def test_index() -> None: flask_app = create_app() with flask_app.test_client() as test_client: response = test_client.get("/") assert response.status_code == 200 assert b"Articles API" in response.data
def app(): """ Setup the flask test app, this only gets executed once :return: Flask app """ app_db_uri = settings.SQLALCHEMY_DATABASE_URI.split(".db") test_db_uri = f"{app_db_uri[0]}_test.db" params = { "DEBUG": False, "TESTING": True, "WTF_CSRF_ENABLED": False, "SQLALCHEMY_DATABASE_URI": test_db_uri, } _app = create_app(settings_override=params) # Establish an application context before running the tests ctx = _app.app_context() ctx.push() yield _app ctx.pop()
def create_app(self): app = create_app() app.config['TESTING'] = True app.config['DEBUG'] = True app.config['SQLALCHEMY_DATABASE_URI'] = \ 'postgresql://*****:*****@localhost:5432/test' return app
def main(): try: (options, args) = get_cmd_args() if not options.src_cur: raise ValueError("Missing 'input_currency' argument") if not options.amount: raise ValueError("Missing 'amount' argument") config_file_path = os_env.get('DEV_CONFIG', None) or '../configs/production.py' app = create_app(config_file_path) with app.app_context(): print(json_dumps(convert(options.src_cur, options.dst_cur, options.amount), indent = 4, sort_keys = True)) return 0 except Exception as e: print(str(e)) return 1
def start_server(test_dir, db_file): # pylint: disable=unused-argument """Run server""" vls = {} config = TestConfig config.RECAPTCHA_PUBLIC_KEY = '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI' config.RECAPTCHA_PRIVATE_KEY = '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe' config.DB_FILE = db_file config.SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(config.DB_FILE) vls['db_file'] = db_file app = create_app(config_object=config) # pylint: disable=invalid-name vls['server'] = Process(target=app.run) vls['server'].start() vls['client'] = app.test_client() vls['session'] = vls['client'].__enter__() pid_file = open(os.path.join(test_dir, 'flask_server.pid'), 'w') pid_file.write(str(vls['server'].pid)) pid_file.close() return vls
def setUp(self): """Initialise app and define test variables""" self.app = create_app(config_name="testing") self.client = self.app.test_client self.user = { 'username': '******', 'email': '*****@*****.**', 'password': '******', 'confirm_password': '******' } self.shoppinglist = { 'owner_id': '1', 'title': "My favorite meal", 'description': 'Items to cook my favorite meal' } self.shoppinglistitem = { 'owner_id': '1', 'shoppinglist_id': '1', 'item_title': "Vegetables", 'item_description': 'Carrots and Cabbages' } with self.app.app_context(): # create all tables db.create_all()
async def get_application(self): # Monkey patch the session setup function to remove Redis dependency for unit tests session.setup = self.session_storage # Monkey patch request retry wait time for faster tests request.RetryRequest._request_using_pool.retry.wait = wait_exponential(multiplier=0) request.RetryRequest._request_basic.retry.wait = wait_exponential(multiplier=0) return app.create_app('TestingConfig')
def rights_check(config, rights_file): """Check of rights version""" if not os.path.isfile(rights_file): print('[Warning] File [{}] doesn\'t exist.'.format(rights_file)) sys.exit(1) with open(rights_file, 'r') as stream: roles_rights = yaml.load(stream) app = create_app(config_object=config) with app.app_context(): DB.init_app(app) internal = Internal.query.order_by( Internal.rights_version.desc()).first() if internal.rights_version != roles_rights['version']: print( '[WARNING] Rights version [{}] in file [{}] differs from proper [{}].' .format(roles_rights['version'], rights_file, internal.rights_version)) sys.exit(0) print('[SUCCESS] Rights in [{}] file is in correct version [{}].'.format( rights_file, internal.rights_version))
def setUp(self): app = create_app() self.client = app.test_client() self.headers = {'Content-Type': 'application/json', 'Authorization': access_token} # Bug workaround client.app = app
def test_production_config(): """Production config.""" app = create_app(ProdConfig) assert app.config['ENV'] == 'prod' assert app.config['DEBUG'] is False assert app.config['DEBUG_TB_ENABLED'] is False assert app.config['ASSETS_DEBUG'] is False
def setUp(self): app = create_app() with app.app_context(): db.create_all() self.app = app.test_client self.app_context = app.app_context
def setUp(self): """Define test variables and initialize app.""" self.app = create_app(config_name="testing") #set up test client for the application self.client = self.app.test_client self.bucketlist = {'name': 'Go for skydiving'} # bind the app to the current context with self.app.app_context(): # create all tables db.create_all() # Register a that we will use to test self.user_data = json.dumps(dict({ "username": "******", "email": "*****@*****.**", "password": "******"})) self.client().post("/api/bucketlists/auth/register/", data=self.user_data, content_type="application/json") self.login_info = json.dumps(dict({ "email": "*****@*****.**", "password": "******" })) # Log is as the test user and get a token self.login_result = self.client().post("/api/bucketlists/auth/login/", data=self.login_info, content_type="application/json") self.access_token = json.loads( self.login_result.data.decode())['access_token'] self.headers = dict(Authorization="Bearer "+ self.access_token, content_type="application/json")
def setUp(self): """Define test variables and initialize app.""" self.app = create_app(config_name="testing") self.client = self.app.test_client() self.question = {"title": "No module found error", "content": "What is the correct way to fix this ImportError error?" }
def app(request): # Load application settings (environment) config_root = os.environ.get('CONFIG_ROOT', './config') ENV = config.load_settings(config_root=config_root) app = create_app(ENV) return app
def setUp(self): from app.app import create_app self.app = create_app(TestingConfig) self.db = init_modules_from_config() self.app.app_context().push() self.fillup() cache.clear()
def createdb(testdata=True): """Initializes the database """ app = create_app() with app.app_context(): db.drop_all() db.create_all() if testdata: for i in range(1, 50): hotel_details = HotelDetails( name='The Apartments Dubai World Trade Centre', address='United Arab Emirates', badge='Clean Rooms', coordinate='25.224747', cost=590, image= 'https://res.cloudinary.com/esanjolabs/image/upload/hotels/3e4564321d5bbc209fcf215f25404de4.jpg', neighbourhood='Palm Jumeirah', rating=9, star_rating=5, type='hotel', id=i, date_created='2018-07-03 00:00:00', date_modified='2018-07-03 00:00:00') db.session.add(hotel_details) db.session.commit()
def app(): from app.app import create_app app = create_app() app.config["TESTING"] = True return app
def app(): naukari_app = create_app('testing') with naukari_app.app_context(): # db.drop_all() # db.create_all() pass yield naukari_app
def setUp(self): self.app = create_app(config_file='settings.py') self.helper = ApiTestHelper() with self.app.test_request_context(): self.base_url = request.host self.provider1 = helper.add_instance(Provider, name='tomer')
def main(): parser = argparse.ArgumentParser(description="Flask Template") parser.add_argument( "--port", "-p", help="The port to listen on (default 5001)", type=int, default=5001, ) parser.add_argument( "--echo", help="Turn on SQLAlchemy query echoing (convenience function to " "override the `app.db.postgres.echo` setting in your " "settings.yml). To permanently enable echoing, set it in " "settings.yml.", action="store_true", ) args = parser.parse_args() # SQLAlchemy echo overrider. os.environ["APP_ECHO"] = str(args.echo) application = create_app() flask_options = dict( host='0.0.0.0', port=args.port or 5001, threaded=True, ) application.run(**flask_options)
def setUp(self): self.app = create_app(TestingConfig) self.app.config['SQLALCHEMY_DATABASE_URI'] = TEST_DB_URL self.app.config['TESTING'] = True self.client = self.app.test_client self.db = SQLAlchemy() self.db.init_app(self.app)
def client(): app = create_app() app.config["TESTING"] = True app.config["SECRET_KEY"] = "secret_key" app.config["WTF_CSRF_ENABLED"] = False with app.test_client() as client: yield client
def __init__(self): app = create_app(config_object=ProdConfig) app_context = app.app_context() app_context.push() db.drop_all() # drop all tables db.create_all() # create a new schema with open('default.json') as file: self.default_data = json.load(file)
def app(temporary_postgresql_database): """An application for the tests.""" TestConfig.SQLALCHEMY_DATABASE_URI = temporary_postgresql_database.url() _app = create_app(TestConfig) ctx = _app.test_request_context() ctx.push() yield _app ctx.pop()
def setUp(self): """Roda antes de todos os testes.""" self.app = create_app() self.app.testing = True self.app_context = self.app.test_request_context() self.app_context.push() self.client = self.app.test_client() self.app.db.create_all()
def setUp(self): bucket_app = create_app('instance.config.TestingConfig') self.user = {'username': '******', 'password': '******'} self.app = bucket_app self.client = self.app.test_client with bucket_app.app_context(): db.create_all() user = User(**self.user) user.save()
def app(): """An application for the tests.""" _app = create_app(TestConfig) ctx = _app.test_request_context() ctx.push() yield _app ctx.pop()
def app(redis_clean): from app.app import create_app app = create_app('test.cfg') ctx = app.app_context() ctx.push() yield app ctx.pop()
def createdb(testdata=True): """Initializes the database """ app = create_app() with app.app_context(): db.drop_all() db.create_all() if testdata: user = User(username="******", password="******") db.session.add(user) db.session.commit()
def __init__(self, environment): print('Run tests on environment ' + environment) self.app = create_app(environment=environment, port=8080) self.app.config.update( DEBUG=True, SECRET_KEY='secret_key', WTF_CSRF_ENABLED=False ) self.headers = [('Content-Type', 'text/plain')] self.content_json = [('Content-Type', 'application/json')] self.api = self.app.test_client()
def setUpClass(cls): cls.maxDiff = None app = create_app("config") app.config.update( DEBUG=True, SECRET_KEY='secret_key', WTF_CSRF_ENABLED=False ) cls.gate_name = 'test-gate' + str(uuid.uuid4()) cls.headers = [('Content-Type', 'text/plain')] cls.accept_json = [('Accept', 'application/json')] cls.content_json = [('Content-Type', 'application/json')] cls.app = app.test_client()
def app(request): # We add some config overrides specifically for testing. The password # hash is changed to plaintext to speed up user creation. config_override = { 'SQLALCHEMY_DATABASE_URI': 'postgresql://*****:*****@localhost/onekptesting' } app = create_app(config_override) ctx = app.app_context() ctx.push() db.app = app db.create_all() def teardown(): ctx.pop() db.drop_all() request.addfinalizer(teardown) return app
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import subprocess from flask_script import Manager, Shell, Server from flask_migrate import MigrateCommand from app.app import create_app from app.user.models import User from app.settings import DevConfig, Config from app.database import db if os.environ.get("APP_ENV") == 'prod': app = create_app(Config) else: app = create_app(DevConfig) HERE = os.path.abspath(os.path.dirname(__file__)) TEST_PATH = os.path.join(HERE, 'tests') manager = Manager(app) def _make_context(): """Return context dict for a shell session so you can access app, db, and the User model by default. """ return {'app': app, 'db': db, 'User': User} @manager.command def test():
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from flask.ext.script import Manager, Shell, Server from flask.ext.migrate import MigrateCommand from app.app import create_app app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) server = Server() manager.add_command("runserver", server) def make_shell_context(): """Populate stuff in flask shell""" return dict(app=app, db=db) # Populate commands manager.add_command('shell', Shell(make_context=make_shell_context, use_bpython=True)) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()
import sys import csv from app.app import create_app from app.config import config from app.models import * from app.extensions import db from app.models.Question import QuestionTaskAssociation app = create_app(config) db.init_app(app) db.app = app def get_tasks(): tasks = db.session.query(Task).all() tasks_dict = {} for task in tasks: tasks_dict[task.identifier] = task return tasks_dict def load_numeric(file): tasks = get_tasks() questions = [] for row in file: task_name = row[0] if len(task_name) > 0 and task_name in tasks:
#utility module for recreating database in development from app.app import create_app app = create_app() with app.app_context(): from models.user import User from plugins import db print db db.drop_all() db.create_all()
import sys from app.app import create_app app = create_app(sys.argv[1]) app.run(debug=True, use_reloader=False, port=int(sys.argv[2]))
# !/usr/bin/env python3 # -*- coding: utf-8 -*- from flask_script import Manager, Server from log import configure_logging from app.app import create_app from register import db configure_logging() app = create_app('default') manager = Manager(app) manager.add_command("runserver", Server(host="0.0.0.0", port=8000)) @app.before_request def connect_db(): if db.is_closed(): db.connect() @app.teardown_request def close_db(exc): if not db.is_closed(): db.close() @app.route('/') @app.route('/index') def index(): return 'It works!'
# -*- coding: utf-8 -*- """ Module for launching main WSGI app instance. """ from app.app import create_app from app import settings from werkzeug import DebuggedApplication flask_app = create_app(settings) if flask_app.config['DEBUG']: flask_app.debug = True flask_app = DebuggedApplication(flask_app, evalex=True) app = flask_app
def setup_class(cls): cls.app_context = create_app().app_context() cls.app_context.push() db.create_all()
# coding:utf-8 from app.app import create_app from app.settings import Config app = create_app(Config)
def cli(ctx): ctx.obj = create_app()
import os from app.app import create_app app = create_app(os.environ['APP_CONFIG'])
import sys from app.app import create_app environment = sys.argv[1] port = int(sys.argv[2]) debug = sys.argv[3] == "true" app = create_app(environment=environment, port=port) print("\nApplication staring...") print(" Environment: " + str(environment)) print(" Port: " + str(port)) print(" Debug: " + str(debug)) app.run(debug=debug, use_reloader=False, port=port, host='0.0.0.0')
import sys from app.app import create_app environments = { 'test': 'instance.config.TestingConfig', 'development': 'instance.config.DevelopmentConfig', 'production': 'instance.config.ProductionConfig' } try: if sys.argv[1] in environments.keys(): app = create_app(environments.get(sys.argv[1])) # Run the app app.run() else: if sys.argv[1] == '-h' or sys.argv[1] == '--help': print ('Usage: python run.py <environment>') print ('\n Available options') print ('\t -- production \n\t -- development \n\t -- test') except IndexError: # Handle missing arguments or more unfriendly options than required print ("Missing options: use [python run.py -h] \ to get list of available options") exit()
def test_dev_config(): """Development config.""" app = create_app(DevConfig) assert app.config['ENV'] == 'dev' assert app.config['DEBUG'] is True assert app.config['ASSETS_DEBUG'] is True
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, sys from flask_script import Manager, Shell, Server, prompt from flask_migrate import MigrateCommand from app.app import create_app from app.account.models import Account from app.settings import DevConfig, ProdConfig from app.database import db if os.environ.get("HEALTH_ENV") == 'prod': app = create_app(ProdConfig) else: app = create_app(DevConfig) HERE = os.path.abspath(os.path.dirname(__file__)) manager = Manager(app) @manager.command def createsuperuser(): """ Create a super user of the system, requiring Email and password. """ username = prompt('Username') password = prompt('Password') password_confirm = prompt('Password Again') if not password == password_confirm: sys.exit('/n Could not create superuser')
def cli(ctx): ctx.obj = create_app( DEBUG=True, )
def app(request): app = create_app() app.debug = True return app