Exemplo n.º 1
0
 def test_init_database(self):
     setting = models.get_uuid(self.session)
     self.assertEqual(None, setting)
     models.init_database(self.session)
     setting = models.get_uuid(self.session)
     uuid_real = uuid.UUID(setting.value)
     self.assertEqual(len(uuid_real.hex), 32)
def main() -> None:
    init_database(settings.database.filename)
    updater = Updater(settings.bot.token)
    dispatcher = updater.dispatcher

    register_controllers(dispatcher)

    updater.start_polling()
    updater.idle()
Exemplo n.º 3
0
def main():
    """
        Méthode de démarrage de l'application
    """
    init_database()
    root = tk.Tk()
    root.wm_title("Simply Movie")
    root.minsize(300, 300)
    SimplyMovie(root)
    root.mainloop()
Exemplo n.º 4
0
def run(db_url, conf=None):
    if conf is not None:
        cherrypy.config.update(conf)

    init_database(db_url)
    create_nonexistent_tables()

    static_conf = {
        '/': {
            'tools.staticdir.root': path.join(path.dirname(path.abspath(__file__)), 'static'),
            'tools.staticdir.on': True,
            'tools.staticdir.dir': '.',
            'tools.staticdir.index': 'index.html'
        }
    }

    cherrypy.tree.mount(StaticServer(), '/', static_conf)
    cherrypy.tree.mount(ApiServer(), '/api')
    cherrypy.engine.start()
    cherrypy.engine.block()
Exemplo n.º 5
0
def main():
    if '--initdatabase' in sys.argv:
        # initialize database
        app.logger.info("initialize database")
        models.init_database(sys.argv)
        sys.exit(0)
    elif '--createadmin' in sys.argv or '--createsuperuser' in sys.argv:
        # creating an admin user from command line
        success, msg = models.create_admin_cli(sys.argv)
        if success:
            app.logger.info('creating admin user "{}"'.format(msg))
            print("success")
        else:
            app.logger.error('problems creating admin user {}')
            print("failed: {}".format(msg))
            sys.exit(1)
        sys.exit(0)
    else:
        # check if the user wants to set port and host from command line
        port = 5000
        host = '127.0.0.1'
        debug = False
        for arg in sys.argv:
            if 'port=' in arg.lower():
                port = int(arg.replace('port=', ''))
            if 'host=' in arg.lower():
                host = arg.replace('host=', '').split(':')
                if len(host) > 1:
                    port = int(host[1])
                host = host[0]
            if 'debug=true' in arg.lower():
                debug = True

        app.logger.info("starting app on host={} port={} debug={}".format(
            host, port, debug))
        app.run(host=host, port=port, debug=debug)
Exemplo n.º 6
0
 def init_database(self):
     """
     Initializes the database tables and relationships
     :return: None
     """
     init_database(self.engine)
Exemplo n.º 7
0
def test_should_raise_error_for_unsupported_databases():
    with pytest.raises(ValueError):
        init_database("")
Exemplo n.º 8
0
            # Create a parser for each low-level module
            module_basename = module.__name__.split('.')[-1]
            module_parser = command_subparsers.add_parser(module_basename)

            # Add default arguments for each fetcher (database configuration)
            module_parser.add_argument(
                '--db',
                default='sqlite',
                help="which type of database to use (postgres, sqlite). Defaults to sqlite."
            )
            module_parser.add_argument(
                '--db-config',
                help="Name of file containing database configuration."
            )

            # Each module defines additional arguments
            module.configure_parser(module_parser)
            module_parser.set_defaults(func=module.main)

    # Parse arguments
    args = parser.parse_args()

    # Initialize database
    init_database(args.db, config_filename=args.db_config)
    create_tables()

    # Invoke the main program that was specified by the submodule
    if args.func is not None:
        args.func(**vars(args))
Exemplo n.º 9
0
from models import init_database

init_database()
Exemplo n.º 10
0
import overpy
import json
import logging
from geofence import Geofences
from models import Gym, init_database
from utils import get_args

args = get_args

app = None
log = logging.getLogger(__name__)
db = init_database(app)


def ex_query(s, w, n, e):

    # Query Overpass for known gym areas
    api = overpy.Overpass(xml_parser=0)
    result = api.query("""
    [out:json]
    [date:"2016-07-10T00:00:00Z"]
    [timeout:620]
    [bbox:{},{},{},{}];
    (
    //Tags that are confirmed to classify gyms as 'parks' for EX Raids
        way[leisure=park];
        way[landuse=recreation_ground];
        way[leisure=recreation_ground];
        way[leisure=pitch];
        way[leisure=garden];
        way[leisure=golf_course];
Exemplo n.º 11
0
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from models import init_database, Post

app = Flask(__name__)
Bootstrap(app)
init_database('postgres', 'postgres-credentials.json')


@app.route('/')
def hello_world():
    #return 'Not dead. Yet.'
    ten = Post.select().where(Post.title.contains('Django')).limit(10)
    print(ten[0].title)
    return render_template('index.html', results=ten)


if __name__ == "__main__":
    app.run()
Exemplo n.º 12
0
    setenv('BALAIO_SETTINGS_FILE', args.configfile)
    if args.alembic_configfile:
        setenv('BALAIO_ALEMBIC_SETTINGS_FILE', args.alembic_configfile)

    activity = args.activity
    if activity == 'syncdb':
        # Creates all database basic structure including
        # Alembic's migration bootstrapping.

        if not args.alembic_configfile:
            sys.exit('%s: error: argument --alembic-config is required' % __file__)

        logger.info('The database infrastructure will be created')
        config = utils.balaio_config_from_env()
        engine = models.create_engine_from_config(config)
        models.init_database(engine)

        print 'Done. All databases had been created'
        sys.exit(0)

    elif activity == 'shell':
        # Places de user on an interactive shell, with a
        # pre-configured Session object.
        local_scope = {}

        def Session_factory():
            engine = models.create_engine_from_config(
                utils.balaio_config_from_env())
            models.Session.configure(bind=engine)
            return models.Session
Exemplo n.º 13
0
            # Add default arguments for each fetcher (database configuration)
            module_parser.add_argument(
                '--db',
                default='sqlite',
                help=
                "which type of database to use (postgres, sqlite). Defaults to sqlite."
            )
            module_parser.add_argument(
                '--db-config',
                help="Name of file containing database configuration.")

            # Each module defines additional arguments
            module.configure_parser(module_parser)
            module_parser.set_defaults(func=module.main)

    # Add command for running unit tests
    test_parser = subparsers.add_parser('tests', description="Run unit tests.")
    test_parser.set_defaults(func=run_tests)

    # Parse arguments
    args = parser.parse_args()

    # Initialize database
    if args.command != 'tests':
        init_database(args.db, config_filename=args.db_config)
        create_tables()

    # Invoke the main program that was specified by the submodule
    if args.func is not None:
        args.func(**vars(args))
Exemplo n.º 14
0
                  env_key='LOG_CFG'):
    """Setup logging configuration """
    path = default_path
    value = os.getenv(env_key, None)
    if value:
        path = value
    if os.path.exists(path):
        with open(path, 'rt') as f:
            config = json.load(f)
        logging.config.dictConfig(config)
    else:
        logging.basicConfig(level=default_level)


if __name__ == "__main__":
    models.init_database()
    '''Script to read data via the RESTBUS API and save to a database. '''
    parser = argparse.ArgumentParser(description='Read the RestBus API')
    parser.add_argument('-o',
                        '--logfile',
                        help='JSON file with the logger configuration',
                        required=True)
    parser.add_argument('-r',
                        '--route',
                        help='The route number to gather data on',
                        required=False,
                        default="1")
    parser.add_argument('-a',
                        '--all',
                        dest='all',
                        action='store_true',
Exemplo n.º 15
0
def start_server(argv=None):
    config = Config()
    logging.debug('starting server with argv : %s' % str(argv))

    init_database()
    bind_address = config.get('bind_address')
    bind_port = config.getint('bind_port')
    try:
        https_port = int(
            config.get('https_port')) if config.get('https_port') else None
    except ValueError:
        logger.warning('https_port is configured, but it is not int, %s' %
                       config.get('https_port'))
        https_port = None

    if https_port:
        https_sockets = tornado.netutil.bind_sockets(https_port, bind_address)

    sockets = tornado.netutil.bind_sockets(bind_port, bind_address)

    # task_id is current process identifier when forked processes, start with 0
    task_id = None
    if not sys.platform.startswith('win'):
        task_id = fork_processes(config.getint('fork_proc_count'))
    else:
        logger.warning(
            'Windows platform does not support forking process, running in single process mode.'
        )

    cluster_sync_obj = None
    if task_id is not None and config.get('cluster_bind_address'):
        cluster_node = ClusterNode(task_id, config)
        cluster_sync_obj = cluster_node.sync_obj

    scheduler_manager = SchedulerManager(config=config,
                                         syncobj=cluster_sync_obj)
    scheduler_manager.init()

    node_manager = NodeManager(scheduler_manager)
    node_manager.init()

    webhook_daemon = WebhookDaemon(config, SpiderSettingLoader())
    webhook_daemon.init()

    app = make_app(scheduler_manager, node_manager, webhook_daemon)

    server = tornado.httpserver.HTTPServer(app)
    server.add_sockets(sockets)

    if https_port:
        check_and_gen_ssl_keys(config)
        if config.getboolean('client_validation'):
            ssl_ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
        else:
            ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        ssl_ctx.load_cert_chain(
            os.path.join('keys', "%s.crt" % config.get('server_name')),
            os.path.join('keys', "%s.key" % config.get('server_name')))
        ssl_ctx.load_verify_locations(cafile='keys/ca.crt')
        ssl_ctx.check_hostname = False
        httpsserver = tornado.httpserver.HTTPServer(app, ssl_options=ssl_ctx)
        httpsserver.add_sockets(https_sockets)
        logger.info('starting https server on %s:%s' %
                    (bind_address, https_port))
    ioloop = tornado.ioloop.IOLoop.current()
    ioloop.start()
Exemplo n.º 16
0
def register_database(app):
    db = init_database(app)
    with app.app_context():
        db.create_all()
Exemplo n.º 17
0
 def init_database(self):
     init_database(self.engine)
Exemplo n.º 18
0
def tests_init_database_sql_alchemy(mocker):
    sqlite3_mock = mocker.patch('models.sqlite3')
    uri = "sqlite:///foo.db"
    init_database(uri)
    sqlite3_mock.connect.assert_called_once_with(database='foo.db')
Exemplo n.º 19
0
def main():
    init_database()
    bot.run(settings.TOKEN)
Exemplo n.º 20
0
def test_init_database_postgresql(uri, called_string, mocker):
    psycopg2_mock = mocker.patch('models.psycopg2')
    init_database(uri)
    psycopg2_mock.connect.assert_called_once_with(called_string)