Esempio n. 1
0
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()
Esempio n. 2
0
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)
Esempio n. 3
0
 def create_app(self):
     return create_app(
         settings_overrides={
             'TESTING': True,
             'PRESERVE_CONTEXT_ON_EXCEPTION': False
         }
     )
Esempio n. 4
0
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)
Esempio n. 6
0
def main():
    app = create_app()
    if config.DEBUG:
        print 'WARNING: DEBUG mode enabled'
        run_flask(app)
        #run_cherrypy()
    else:
        run_cherrypy(app)
Esempio n. 7
0
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
Esempio n. 8
0
def app(api):
    """An application for the tests."""
    _app = create_app(TestConfig, api)
    ctx = _app.test_request_context()
    ctx.push()

    yield _app

    ctx.pop()
Esempio n. 9
0
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
Esempio n. 10
0
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"])
Esempio n. 11
0
 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()
Esempio n. 12
0
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
Esempio n. 13
0
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
Esempio n. 14
0
def app(request):
    app = create_app({
        'TESTING': True
    })

    ctx = app.app_context()
    ctx.push()

    def teardown():
        ctx.pop()

    request.addfinalizer(teardown)
    return app
Esempio n. 15
0
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
Esempio n. 16
0
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)
Esempio n. 17
0
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()
Esempio n. 18
0
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
Esempio n. 19
0
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
Esempio n. 20
0
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
Esempio n. 21
0
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
Esempio n. 23
0
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
Esempio n. 24
0
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
Esempio n. 25
0
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()
Esempio n. 26
0
"""
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')
Esempio n. 27
0
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()
Esempio n. 28
0
# -*- 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)
Esempio n. 29
0
from server.app import create_app

app = create_app()

if __name__ == '__main__':
    app.run(host='0.0.0.0')
Esempio n. 30
0
def test_create_app():
    assert create_app()
Esempio n. 31
0
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)
Esempio n. 32
0
#!/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')
Esempio n. 33
0
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()
Esempio n. 34
0
        '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."""
Esempio n. 35
0
def main():
    app = create_app(Config)
    manager = Manager(app)
    manager.add_command('runserver', Server(host='0.0.0.0'))
    manager.run()
Esempio n. 36
0
from server import app


app = app.create_app()

if __name__ == '__main__':
    pass
Esempio n. 37
0
# -*- 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)
Esempio n. 38
0
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)
Esempio n. 40
0
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)