def main(): from server.app import create_app # Create the app app = create_app() # Need to patch sockets to make requests async monkey.patch_all() host = app.config.get("HOST", "0.0.0.0") port = app.config.get("PORT", 5000) # Start the server pool_size = int(os.environ.get("POOL_SIZE", 10)) pool = Pool(pool_size) http_server = WSGIServer((host, port), app.wsgi_app, spawn=pool) # Start server and catch KeyboardInterrupt to allow for graceful shutdown. try: app.logger.info("Listening on %s:%d" % (host, port)) print "Startup complete..." http_server.serve_forever() except KeyboardInterrupt: # Close mongoDB connection with app.app_context(): app.logger.info("Closing mongoDB connection") app.db.connection.close() app.logger.info("Done") http_server.stop()
def runserver(config, host, port): """Simple Async Web Server.""" # Load configuration try: app_config = load_config(config_file=config, port=port) except (ValueError, FileNotFoundError) as err: log.critical(f'Config error: {err}\n' 'Run: \n ./runserver.py --config=<config_file_name>') return # Create and run Application try: srv_app = app.create_app(config=app_config) srv_app.on_cleanup.append(app.shutdown_tasks) except KeyError: log.critical('Key field missing. Please check config file!', exc_info=True) return except app.CreateAppError as err: log.critical('Can\'t create "%s"\n\n%s\n', SERVICE_NAME, err) return log.info('Starting %s...', SERVICE_NAME) log.debug('Project config: %s', config) web.run_app(srv_app, host=host, port=app_config['PORT']) log.info('%s Stopped!', SERVICE_NAME)
def create_app(self): return create_app( settings_overrides={ 'TESTING': True, 'PRESERVE_CONTEXT_ON_EXCEPTION': False } )
def make_server(config_name=None, gunicorn=False): application = create_app(config_name) configure_logger(application, gunicorn=gunicorn) main.init_app(application) application.app_context().push() return application
def run(app_host: str = '0.0.0.0', app_port: int = 5000, app_workers: int = 1): from server.app import create_app # Create the app app = create_app() # Run the server app.run(host=app_host, port=app_port, workers=app_workers)
def main(): app = create_app() if config.DEBUG: print 'WARNING: DEBUG mode enabled' run_flask(app) #run_cherrypy() else: run_cherrypy(app)
def client(tmpdir, spooldir): dbfile = tmpdir.join('db-test.sqlite') app = create_app(dbfile) app.config['TESTING'] = True app.config['SPOOLDIR'] = spooldir client = app.test_client() with app.app_context(): yield client
def app(api): """An application for the tests.""" _app = create_app(TestConfig, api) ctx = _app.test_request_context() ctx.push() yield _app ctx.pop()
def make_worker(config_name=None): application = create_app(config_name) application.app_context().push() celery = create_celery(application) from server.extensions.celery import tasks tasks.setup() return celery
def client(): flask_app = create_app("test") # Create a test client using the Flask application configured for testing with flask_app.test_client() as testing_client: # Establish an application context with flask_app.app_context(): yield testing_client # this is where the testing happens! clear_db(flask_app.config["DATABASE_URI"])
def new_client(audit_logger): app = create_app( db=neo4j, api_client=api_client, jobs_client=jobs_client, victor_ops_client=victor_ops_client, audit_logger=audit_logger, ).app app.testing = True return app.test_client()
def client(): app = create_app(conf='conf.test.Config') app.config['TESTING'] = True client = app.test_client() # Clear databases mongo.db['articles'].delete_many({}) mongo.db['articles_statistics'].delete_many({}) mongo.db['purchases'].delete_many({}) mongo.db['questions'].delete_many({}) mongo.db['chat_message'].delete_many({}) yield client
def app(request): app = create_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 app(request): app = create_app({ 'TESTING': True }) ctx = app.app_context() ctx.push() def teardown(): ctx.pop() request.addfinalizer(teardown) return app
def app(request): app = create_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 client(): db_file_handle, db_file_path = tempfile.mkstemp() app = create_app() app.testing = True app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_file_path}' with app.app_context(): db.create_all() yield TestClientWrapper(app.test_client()) os.close(db_file_handle) os.unlink(db_file_path)
def app(): """An application for the tests.""" parent = os.path.dirname(__file__) data_path = os.path.join(parent, '..', 'data') _app = create_app({ 'TESTING': True, 'DATA_PATH': data_path, }) ctx = _app.test_request_context() ctx.push() yield _app ctx.pop()
def app(request): parent = os.path.dirname(__file__) #Use the test data as the application's data data_path = os.path.join(parent, 'test_data') app = create_app({'TESTING': True, 'DATA_PATH': data_path}) # 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): app = create_app({ 'TESTING': True, 'DATA_PATH': root + "/test_data", 'FINDER': None }) # 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): app = create_app({ 'TESTING': True }) app.before_first_request_funcs = [] app.products = () app.tags = {} # 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): app = create_app(db_connection_string=request.config.getoption( '--connection-string'), testing=True) app.test_client_class = CustomClient # Establish an application context before running the tests. ctx = app.app_context() ctx.push() def teardown(): TEMPORATY_SQLITE.close() ctx.pop() request.addfinalizer(teardown) app.config['NPLUSONE_RAISE'] = not request.config.getoption( '--ignore-nplusone') return app
def post_active_principle(): app = create_app(conf='conf.test.Config') app.config['TESTING'] = True client = app.test_client() clear_database() active_principle_data = { 'code': '200', 'name': 'paracetamol', 'description': 'analgésicos y antiinflamatorios' } resp = client.post('/active_principle/', data=json.dumps(active_principle_data), content_type='application/json') assert resp.json['ok'] assert resp.status_code == HTTPStatus.CREATED active_principle_data['_id'] = resp.json['data'] yield client, active_principle_data
def app(request): connection_string = request.config.getoption('--connection-string') if not connection_string: connection_string = 'sqlite:///' app = create_app(db_connection_string=connection_string, testing=True) app.test_client_class = CustomClient # Establish an application context before running the tests. ctx = app.app_context() ctx.push() def teardown(): ctx.pop() request.addfinalizer(teardown) app.config['NPLUSONE_RAISE'] = not request.config.getoption( '--ignore-nplusone') return app
def app(request): """Session-wide test `Flask` application.""" parent = os.path.dirname(__file__) data_path = os.path.join(parent, 'data') app = create_app({ 'TESTING': True, 'DATA_PATH': data_path }) # 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(): """ Setup our flask test app, this only gets executed once. :return: Flask app """ db_uri = '{0}_test'.format(settings.SQLALCHEMY_DATABASE_URI) params = { 'DEBUG': False, 'TESTING': True, 'SQLALCHEMY_DATABASE_URI': 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()
""" This creates a docker file for the postgres configuration """ import os from server.app import create_app from setup_environment import setup_environment_variables setup_environment_variables() config_name = os.getenv("FLASK_CONFIG") or "default" app = create_app(config_name) # Postgres Initialization Files docker_file = 'Dockerfile' source_dir = os.path.abspath(os.curdir) destination_dir = os.path.join(source_dir, '../postgresql') # Before creating files, check that the destination directory exists if not os.path.isdir(destination_dir): os.makedirs(destination_dir) # Create the 'Dockerfile' for initializing the Postgres Docker image with open(os.path.join(destination_dir, docker_file), 'w') as postgres_dockerfile: postgres_dockerfile.write('FROM postgres:9.6') postgres_dockerfile.write('\n') postgres_dockerfile.write('\n# Set environment variables for postgres') postgres_dockerfile.write('\nENV POSTGRES_USER {}'.format(app.config.get('POSTGRES_USER'))) postgres_dockerfile.write('\nENV POSTGRES_PASSWORD {}'.format(app.config.get('POSTGRES_PASSWORD'))) postgres_dockerfile.write('\nENV POSTGRES_DB {}'.format(app.config.get('POSTGRES_DB'))) postgres_dockerfile.write('\n')
from server.app import create_app from server.settings import ProdConfig import config if config.DEBUG: app = create_app() else: app = create_app(ProdConfig) if __name__ == '__main__': app.run()
# -*- coding: utf-8 -*- from server.app import create_app from server.settings import override app = create_app(settings_overrides=override) if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)
from server.app import create_app app = create_app() if __name__ == '__main__': app.run(host='0.0.0.0')
def test_create_app(): assert create_app()
from server.model import Base, engine from server.app import create_app if __name__ == '__main__': Base.metadata.create_all(engine) app = create_app() app.run(debug=True)
#!/usr/bin/env python3 import os from server.app import app_celerey, create_app from flask.logging import default_handler socketio, app = create_app(os.getenv('FLASK_CONFIG') or 'default')
import os from flask_script import Manager # class for handling a set of commands from flask_migrate import Migrate, MigrateCommand from server.app import DB, create_app from server.models import users app = create_app(config_name=os.getenv('APP_SETTINGS')) migrate = Migrate(app, DB) manager = Manager(app) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()
'tests/*', 'wsgi.py', 'settings.py', '__init__.py', 'app/*/__init__.py' 'app/static/*' 'app/templates/*' 'app/import_policy/*' 'app/models/*' ] ) COV.start() # create flask application instance socketio, app = create_app ('development') manager = Manager(app) @manager.command def test(): """Runs the unit tests without test coverage.""" test_suite = unittest.TestLoader().discover('tests', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(test_suite) if result.wasSuccessful(): return 0 return 1 @manager.command def cov(): """Runs the unit tests with coverage."""
def main(): app = create_app(Config) manager = Manager(app) manager.add_command('runserver', Server(host='0.0.0.0')) manager.run()
from server import app app = app.create_app() if __name__ == '__main__': pass
# -*- coding: utf-8 -*- """Create an application instance.""" from flask.helpers import get_debug_flag from server.app import create_app from server.settings import DevConfig, ProdConfig CONFIG = DevConfig if get_debug_flag() else ProdConfig app = create_app(CONFIG)
async def cli(loop, aiohttp_client): loop = asyncio.get_event_loop() app = create_app(loop) return await aiohttp_client(app)
COV = coverage(branch=True, include='app/*', omit=[ 'tests/*', 'wsgi.py', 'settings.py', '__init__.py', 'app/*/__init__.py' 'app/static/*' 'app/templates/*' 'app/import_policy/*' 'app/models/*' ]) COV.start() # create flask application instance app = create_app('development') # test websockets #socketio, app = create_app ('development') manager = Manager(app) print("=========== ENVIRONMENT ============") print("FLASK_CONFIG = ", os.environ["FLASK_CONFIG"]) @manager.command def test(): """Runs the unit tests without test coverage.""" test_suite = unittest.TestLoader().discover('tests', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(test_suite)
from twisted.web.util import Redirect from twisted.web.wsgi import WSGIResource from autobahn.twisted.websocket import ( listenWS ) import server.config from server.utils import logger from server.app import create_app from server.websocket_factories import ( WorkspaceServerFactory, BroadcastServerProtocol ) from server.api.modules.upload_reports import RawReportProcessor app = create_app() # creates a Flask(__name__) app logger = server.utils.logger.get_logger(__name__) class CleanHttpHeadersResource(Resource, object): def render(self, request): request.responseHeaders.removeHeader('Server') return super(CleanHttpHeadersResource, self).render(request) class FileWithoutDirectoryListing(File, CleanHttpHeadersResource): def directoryListing(self): return ForbiddenResource() def render(self, request): ret = super(FileWithoutDirectoryListing, self).render(request)