Example #1
0
 def test_envvar_config_load(self):
     old = os.environ.get('EQUANIMITY_SERVER_SETTINGS')
     os.environ['EQUANIMITY_SERVER_SETTINGS'] = '../config/test.py'
     try:
         create_app()
     except Exception:
         raise
     finally:
         if old is not None:
             os.environ['EQUANIMITY_SERVER_SETTINGS'] = old
Example #2
0
 def test_config_dev_default_load(self):
     old = os.environ.get('EQUANIMITY_SERVER_SETTINGS')
     if old is not None:
         del os.environ['EQUANIMITY_SERVER_SETTINGS']
     try:
         create_app(config=None)
     except Exception:
         raise
     finally:
         if old is not None:
             os.environ['EQUANIMITY_SERVER_SETTINGS'] = old
    def test_prod_config(self):
        """ Tests if the production config loads correctly """

        app = create_app('server.settings.ProdConfig', env='prod')

        assert app.config['SQLALCHEMY_DATABASE_URI'] == 'sqlite:///../database.db'
        assert app.config['CACHE_TYPE'] == 'simple'
Example #4
0
 def test_logger_setup_no_debug(self):
     # There's nothing to really test besides to make sure the code
     # doesn't crash.  This only affects the logging levels set
     app = create_app(config='test')
     app.config['DEBUG'] = False
     app.config['DEBUG_LOGGING'] = False
     attach_loggers(app)
Example #5
0
def startTornado():
    global http_server
    http_server = HTTPServer(WSGIContainer(create_app("settings.DevelopmentConfig")))
    http_server.listen(80)
    ioloop = IOLoop.instance()
    autoreload.start(ioloop)
    ioloop.start()
Example #6
0
def init_db():
    '''
        Create tables necessary for this app to work.
    '''
    app = create_app()
    db.init_app( app )
    with app.test_request_context():
        db.create_all()
    def test_dev_config(self):
        """ Tests if the development config loads correctly """

        app = create_app('server.settings.DevConfig', env='dev')

        assert app.config['DEBUG'] is True
        assert app.config['SQLALCHEMY_DATABASE_URI'] == 'sqlite:///../database.db'
        assert app.config['CACHE_TYPE'] == 'null'
    def test_test_config(self):
        """ Tests if the test config loads correctly """

        app = create_app('server.settings.TestConfig', env='dev')

        assert app.config['DEBUG'] is True
        assert app.config['SQLALCHEMY_ECHO'] is True
        assert app.config['CACHE_TYPE'] == 'null'
def start_app():
    """
    Run in development mode, never used in production.
    """
    port = int(os.getenv("PORT", 5000))
    try:
        app = create_app()
        app.run(host='0.0.0.0', port=port)
    except APIException as e:
        print ("Application failed to register with Service Discovery")
Example #10
0
def export(path=None, gfm=False, context=None, username=None, password=None,
           render_offline=False, out_filename=None):
    """Exports the rendered HTML to a file."""
    app = create_app(path, gfm, context, username, password, render_offline,
                     render_inline=True)

    if out_filename is None:
        out_filename = os.path.splitext(app.config['GRIP_FILE'])[0] + '.html'
    print 'Exporting to', out_filename

    content = render_app(app)
    with io.open(out_filename, 'w', encoding='utf-8') as f:
        f.write(content)
Example #11
0
    def test_api_status_code_handling(self):
        app = create_app(config='test')
        b = Blueprint('test', __name__, url_prefix='/test')

        @b.route('/')
        @api
        def status_return():
            return dict(msg='ok'), 666

        app.register_blueprint(b)
        client = app.test_client()
        with app.test_request_context('/'):
            url = url_for('test.status_return')
        r = client.get(url)
        self.assertEqual(r.status_code, 666)
Example #12
0
    def test_non_jsonifiable_return_value(self):
        app = create_app(config='test')
        bad = Blueprint('test', __name__, url_prefix='/test')

        @bad.route('/hey')
        @api
        def bad_view():
            return ['hey']

        app.register_blueprint(bad)
        client = app.test_client()
        with app.test_request_context('/'):
            url = url_for('test.bad_view')
        r = client.get(url)
        self.assertEqual(r.status_code, 500)
Example #13
0
def testapp(request):
    app = create_app('server.settings.TestConfig', env='dev')
    client = app.test_client()

    db.app = app
    db.create_all()

    if getattr(request.module, "create_user", True):
        admin = User('admin', 'supersafepassword')
        db.session.add(admin)
        db.session.commit()

    def teardown():
        db.session.remove()
        db.drop_all()

    request.addfinalizer(teardown)

    return client
Example #14
0
def cli(loop, test_client):
    app = server.create_app()
    return loop.run_until_complete(test_client(app))
Example #15
0
    def setUp(self):
        self.USER_GNUPGHOME = tempfile.TemporaryDirectory()
        self.ADMIN_GNUPGHOME = tempfile.TemporaryDirectory()
        self.INVALID_GNUPGHOME = tempfile.TemporaryDirectory()
        self.NEW_USER_GNUPGHOME = tempfile.TemporaryDirectory()
        self.config = ConfigParser()
        self.config.read_string("""
            [mtls]
            min_lifetime=60
            max_lifetime=0

            [ca]
            key = secrets/certs/authority/RootCA.key
            cert = secrets/certs/authority/RootCA.pem
            issuer = My Company Name
            alternate_name = *.myname.com

            [gnupg]
            user={user_gnupghome}
            admin={admin_gnupghome}

            [storage]
            engine=sqlite3

            [storage.sqlite3]
            db_path=:memory:
            """.format(
            user_gnupghome=self.USER_GNUPGHOME.name,
            admin_gnupghome=self.ADMIN_GNUPGHOME.name,
        ))
        self.key = generate_key()
        self.engine = storage.SQLiteStorageEngine(self.config)
        cur = self.engine.conn.cursor()
        cur.execute("DROP TABLE IF EXISTS certs")
        self.engine.conn.commit()
        self.engine.init_db()
        self.user_gpg = gnupg.GPG(gnupghome=self.USER_GNUPGHOME.name)
        self.admin_gpg = gnupg.GPG(gnupghome=self.ADMIN_GNUPGHOME.name)
        self.invalid_gpg = gnupg.GPG(gnupghome=self.INVALID_GNUPGHOME.name)
        self.new_user_gpg = gnupg.GPG(gnupghome=self.NEW_USER_GNUPGHOME.name)
        app = create_app(self.config)
        self.app = app.test_client()
        self.users = [
            User("user@host", gen_passwd(), generate_key(), gpg=self.user_gpg),
            User("user2@host", gen_passwd(), generate_key(),
                 gpg=self.user_gpg),
            User("user3@host", gen_passwd(), generate_key(),
                 gpg=self.user_gpg),
        ]
        self.invalid_users = [
            User("user4@host",
                 gen_passwd(),
                 generate_key(),
                 gpg=self.invalid_gpg)
        ]
        self.admin_users = [
            User("admin@host",
                 gen_passwd(),
                 generate_key(),
                 gpg=self.admin_gpg)
        ]
        self.new_users = [
            User("newuser@host",
                 gen_passwd(),
                 generate_key(),
                 gpg=self.new_user_gpg),
            User("newuser2@host",
                 gen_passwd(),
                 generate_key(),
                 gpg=self.new_user_gpg),
        ]
        for user in self.users:
            self.user_gpg.import_keys(
                self.user_gpg.export_keys(user.fingerprint))
            self.user_gpg.trust_keys([user.fingerprint], "TRUST_ULTIMATE")
        for user in self.admin_users:
            # Import to admin keychain
            self.admin_gpg.import_keys(
                self.admin_gpg.export_keys(user.fingerprint))
            self.admin_gpg.trust_keys([user.fingerprint], "TRUST_ULTIMATE")
            # Import to user keychain
            self.user_gpg.import_keys(
                self.admin_gpg.export_keys(user.fingerprint))
            self.user_gpg.trust_keys([user.fingerprint], "TRUST_ULTIMATE")
        for user in self.invalid_users:
            self.invalid_gpg.import_keys(
                self.invalid_gpg.export_keys(user.fingerprint))
            self.invalid_gpg.trust_keys([user.fingerprint], "TRUST_ULTIMATE")
        for user in self.new_users:
            self.new_user_gpg.import_keys(
                self.new_user_gpg.export_keys(user.fingerprint))
            self.new_user_gpg.trust_keys([user.fingerprint], "TRUST_ULTIMATE")
Example #16
0
# Script to run server; pass port option to change listening port
# Place one level outside of directory server/
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.options import define, options
from server import create_app
from server.config import ProductionConfig

define("port", default=5000, help="Port to listen on", type=int)
#app = create_app(config=ProductionConfig)
app = create_app() #DebugConfig
http_server = HTTPServer(WSGIContainer(app))
http_server.listen(options.port)
IOLoop.instance().start()
Example #17
0
File: base.py Project: MACSIFS/IFS
 def create_app(self):
     return create_app({'SQLALCHEMY_DATABASE_URI': 'sqlite://'})
Example #18
0
import server
from config import DefaultConfig

application = server.create_app(DefaultConfig)

if __name__ == "__main__":
    application.run()

 def setUp(self):
     self.app = create_app()
     self.ctx = self.app.app_context()
     self.ctx.push()
Example #20
0
 def create_app(self):
     app = create_app('settings/test.py')
     # Default port is 5000
     app.config['LIVESERVER_PORT'] = 8943
     return app
Example #21
0
 def setUp(self):
     '''
     Setup function
     '''
     self.app = create_app('config.Test')
     self.tester_app = self.app.test_client()
Example #22
0
#!/usr/bin/env python
# encoding: utf-8

from server import create_app

if __name__ == '__main__':
    MAIN = create_app()
    MAIN.run()
Example #23
0
import server

app = server.create_app()

if __name__ == "__main__":
    app.run()
Example #24
0
#! /usr/bin/env python
""" Initializes the database schema. """

from server import create_app
from database import db
from models import *

app = create_app("settings.DevelopmentConfig")
db.create_all(app=app)
Example #25
0
import unittest

from flask_assets import ManageAssets
from flask_rq import get_worker
from flask_script import Manager, Server, Command
from flask_script.commands import ShowUrls, Clean

from flask_migrate import Migrate, MigrateCommand

from server import create_app, generate
from server.models import db, User, Course, Version
from server.extensions import assets_env, cache

# default to dev config
env = os.getenv('OK_ENV', 'dev')
app = create_app(env)

migrate = Migrate(app, db)
manager = Manager(app)

class RunTests(Command):

    def run(self):
        test_loader = unittest.defaultTestLoader
        test_runner = unittest.TextTestRunner()
        test_suite = test_loader.discover('tests/')
        test_runner.run(test_suite)


manager.add_command("server", Server(host='localhost'))
manager.add_command("show-urls", ShowUrls())
Example #26
0
# -*- encoding:utf-8 -*-
from flask.ext.script import Manager
from flask.ext.assets import ManageAssets
from flask.ext.zen import Test, ZenTest

from server import create_app
from server.db import (
        CreateDbCommand,
        CreateUserCommand,
        CreateUserDbCommand,
        ImportDataCommand,
        )

manager = Manager(create_app())
manager.add_command("assets", ManageAssets())
manager.add_command("test", Test())
manager.add_command("zen", ZenTest())
manager.add_command("create_user_db", CreateUserDbCommand())
manager.add_command("create_data_db", CreateDbCommand(None))
manager.add_command("create_user", CreateUserCommand())
manager.add_command("import_data", ImportDataCommand())


if __name__ == "__main__":
    manager.run()
Example #27
0
def app():
    os.environ["TODOS_FS_MODE"] = "testing"
    flask_app = create_app()
    return flask_app
Example #28
0
def app():
    return create_app('test')
Example #29
0
#!/usr/bin/env python3
"""
For WSGI Server
To run:
$ gunicorn -b 0.0.0.0:5000 wsgi:app
OR
$ export FLASK_APP=wsgi
$ flask run
"""
import os
from server import create_app

env = os.environ.get('FLASK_ENV', 'prod')
app = create_app('server.settings.%sConfig' % env.capitalize())
Example #30
0
import logging
import os
from dotenv import load_dotenv
from server import create_app, socketio

for file in [x.strip() for x in os.getenv('CONFIG_ENV', default='').split(',')]:
    load_dotenv(file)
#print(os.environ.values())

logging.basicConfig(level=logging.INFO)

app = create_app(debug=True)

if __name__ == '__main__':
    socketio.run(app)
Example #31
0
from server import create_app

app = create_app()

if __name__ == "__main__":
    app.run()
Example #32
0
    # Get the locationless users
    no_location_users = db.session.query(User)\
        .filter(User.lat==None)\
        .filter(User.lng==None)\
        .filter(User._location!=None)\
        .execution_options(show_all=True)\
        .all()

    for u in no_location_users:
        _set_user_gps_from_location(u.id, u._location, user_obj=u)
    db.session.commit()


# from app folder: python ./migations/seed.py
if __name__ == '__main__':
    current_app = create_app()
    ctx = current_app.app_context()
    ctx.push()

    create_ussd_menus()
    create_business_categories()

    reserve_token = create_reserve_token(current_app)
    create_master_organisation(current_app, reserve_token)

    create_float_transfer_account(current_app)

    refresh_user_locations(current_app)

    ctx.pop()
Example #33
0
 def setUp(self):
     self.app = create_app("dev")
     db = SQLAlchemy(self.app, {'expire_on_commit': False})
     db.create_all()
     self.app_context = self.app.app_context()
     self.app_context.push()
Example #34
0
import os

from server import db, create_app

os.system('export FLASK_APP=./server')
db.create_all(app=create_app())
# export FLASK_APP=
os.system('export FLASK_APP=./server')
Example #35
0
from server import create_app

application = create_app()
Example #36
0
            chain_config = app.config['CHAINS'][app.config['DEFAULT_CHAIN']]

            float_transfer_account = TransferAccount(
                private_key=chain_config['FLOAT_PRIVATE_KEY'],
                account_type=TransferAccountType.FLOAT,
                token=t,
                is_approved=True)
            db.session.add(float_transfer_account)
            db.session.flush()
            t.float_account = float_transfer_account
        t.float_account.is_public = True
        db.session.commit()
    print_section_conclusion('Done Creating/Updating Float Wallet')


# from app folder: python ./migations/seed.py
if __name__ == '__main__':
    current_app = create_app(skip_create_filters=True)
    ctx = current_app.app_context()
    ctx.push()

    create_ussd_menus()
    create_business_categories()

    reserve_token = create_reserve_token(current_app)
    create_master_organisation(current_app, reserve_token)

    create_float_transfer_account(current_app)

    ctx.pop()
Example #37
0
#!/usr/bin/env python3
# To run:
# gunicorn -b 0.0.0.0:5000 wsgi:app
import os
from server import create_app

env = os.environ.get('OK_ENV', 'dev')
app = create_app(env)
Example #38
0
from server import create_app

app = create_app()
Example #39
0
def lambda_handler(event, context):
    print("Lambda event", event)
    return awsgi.response(create_app(), event, context, base64_content_types={"application/octet-stream"})
Example #40
0
#!/usr/bin/env python3

import logging

from logging.handlers import TimedRotatingFileHandler
from server import create_app

app, _args, _task_runner = create_app()


def _configure_logging():
    # System wide logging
    logger = logging.getLogger()

    log_fh = TimedRotatingFileHandler('logs/log', when='midnight', backupCount=30)
    log_fh.suffix = '%Y_%m_%d'
    formatter = logging.Formatter('[%(asctime)s] [%(levelname)8s] --- %(message)s (%(filename)s:%(lineno)s)"')
    log_fh.setFormatter(formatter)

    stderr_fh = logging.StreamHandler()

    logger.addHandler(log_fh)
    logger.addHandler(stderr_fh)
    logger.setLevel(logging.DEBUG)

if __name__ == '__main__':
    _configure_logging()

    if _task_runner:
        logging.info('Starting task runner')
        _task_runner.start()
Example #41
0
def create_cli_app(info):
    return create_app()
Example #42
0
 def create_app(self):
     return create_app('settings/test.py')
Example #43
0
import os
from server import create_app

app = create_app(os.environ.get('CONFIG_MODE'))

if __name__ == "__main__":
    print("eeee")
    app.run(ssl_context="adhoc")
Example #44
0
import os
import server

env_flask_env = os.environ.get('FLASK_ENV') or 'development'
env_conn_string = os.environ.get('DATABASE_CONNECTION_STRING') or 'postgresql://postgres@db:5432/'


server.create_app({
    'SQLALCHEMY_DATABASE_URI': env_conn_string
})
server.load_db()
server.app.run(host='0.0.0.0', debug=(env_flask_env == 'development'))
Example #45
0
from server import create_app

create_app().run(debug=True, threaded=True)
Example #46
0
        configs = {
            'SCREEN_WIDTH': width,
            'SCREEN_HEIGHT': height,
            'CARLA_HOST': servername,
            'CARLA_PORT': carlaport,
            'AUTO_PILOT': autopilot,
            'ROLENAME': car_name,
            'FILTER': car_type,
            'WORLD_NAME': world,

            'RCNN_MODEL_PATH': rcc_model_path,
            'RCNN_MAP_PATH': rcnn_map_path,
            'RCNN_NET_DIM': rcnn_net_dim,
            'RCNN_MAX_PROPOSALS': rcnn_max_proposals,
            'RCNN_POSITIVE_CLASS': rcc_positive_class,
            'RCNN_THRESHOLD': rcnn_threshold,
            'RCNN_LOOP_COUNTER': rcnn_loop_counter,
        }

        
        create_app(width,height,debug)

        init(configs)
        loop()
        stop()

        print("Service started")
    except Exception as e:
        show_traceback(override=True)
        print("Service failed: " + str(e))
Example #47
0
def cli(loop, aiohttp_client):
    return loop.run_until_complete(aiohttp_client(create_app()))
Example #48
0
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import server
import config


app = server.create_app(config)


# This is only used when running locally. When running live, gunicorn runs
# the application.
if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080, debug=True)
def check_recent_transaction_sync_status(interval_time, time_to_error):
    # Create app and get context, since this is running in new background processes on a timer!
    from server import create_app
    app = create_app(skip_create_filters=True)
    with app.app_context():
        _check_recent_transaction_sync_status(interval_time, time_to_error)
Example #50
0
from flask import Flask, render_template, jsonify, request, Blueprint
from server.models.client import *
from server.config import config
from server import create_app

debug = __name__ == '__main__'

app = create_app(config, debug)

if __name__ == '__main__':
    app.run(debug=debug, port=5000)
Example #51
0
def test_request_context():
    flask_app = create_app()

    # can be used in combination with the WITH statement to activate a request context temporarily.
    # with this you can access the request, g and session objects in view functions
    yield flask_app.test_request_context
Example #52
0
from server import create_app
from gevent.wsgi import WSGIServer
from gevent import monkey

# Change the host and port here
HOST = '0.0.0.0'
PORT = 8888

app = create_app('development') 
kwargs = {
            'host':HOST,
            'port':PORT,
         }

if __name__ == '__main__':
    #app.run(**kwargs)
    monkey.patch_socket()
    server = WSGIServer((HOST, PORT), app)
    server.serve_forever()

Example #53
0
#!/usr/bin/env python

from common import hack_syspath
hack_syspath(__file__)
import argparse
from equanimity.world import init_db
from server import create_app


def get_args():
    p = argparse.ArgumentParser()
    p.add_argument('--reset', action='store_true', help='Reset original world')
    p.add_argument('-v', '--verbose', action='store_true',
                   help='Verbose output')
    p.add_argument('--grid-radius', type=int, default=8,
                   help='Radius of world and field grids')
    p.add_argument('--square-grid', action='store_true',
                   help='Use a square grid')
    return p.parse_args()


if __name__ == '__main__':
    args = get_args()
    with create_app().test_request_context():
        init_db(reset=args.reset, verbose=args.verbose,
                grid_radius=args.grid_radius, square_grid=args.square_grid)
Example #54
0
 def setUp(self):
     if not self.is_setup:
         self.__class__.app = server.create_app(Testing).test_client()
         self.__class__.is_setup = True
         self.__class__.data_directory = os.path.join(
             os.getcwd(), 'tests/data')
Example #55
0
from server import create_app
import config


print dir(config)
# initialize the application
app = create_app(config, debug=True)
Example #56
0
    def create_test_app(self):

        app = create_app(
            {'SQLALCHEMY_DATABASE_URI': self.SQLALCHEMY_DATABASE_URI})

        return app
Example #57
0
 def create_app(self, mongo, dropbox, datastore_manager):
     app = create_app()
     app.config['TESTING'] = True
     self.db = mongo().db.geonauts
     return app
Example #58
0
from server import create_app
from config import ProductionConfig
from routes.notes_routes import notes
from routes.users_routes import users

app = create_app(ProductionConfig, users, notes)

if __name__ == "__main__":
    app.run()