Beispiel #1
0
    def test_global_option_value(self):

        def create_app(config_name='Empty'):
            print config_name
            return self.app

        manager = Manager(create_app)
        manager.add_option('-c', '--config', dest='config_name', required=False, default='Development')
        manager.add_command('simple', SimpleCommand())

        assert isinstance(manager._commands['simple'], SimpleCommand)

        stdout, code = run('manage.py simple', lambda: manager.run())
        assert code == 0
        assert 'Empty' not in stdout  # config_name is overwritten by default option value
        assert 'Development' in stdout
        assert 'OK' in stdout

        stdout, code = run('manage.py -c Before simple', lambda: manager.run())
        assert code == 0
        assert 'Before' in stdout
        assert 'OK' in stdout

        stdout, code = run('manage.py simple -c After', lambda: manager.run())
        assert code == 0
        assert 'After' in stdout
        assert 'OK' in stdout

        stdout, code = run('manage.py -c DoNotShow simple -c NewValue', lambda: manager.run())
        assert code == 0
        assert 'DoNotShow' not in stdout  # first parameter is ignored
        assert 'NewValue' in stdout       # second on is printed
        assert 'OK' in stdout
Beispiel #2
0
def main():
    manager = Manager(create_app)
    manager.add_option('-c', '--config', dest='config', required=False)
    manager.add_command('routes', ShowUrls())
    manager.add_command('send_talk_emails',
                        SendTalkEmails())

    manager.add_command('send_speaker_emails',
                        SendSpeakerEmails())

    manager.add_command('send_invitation_to_previous_speakers',
                        SendInvitationToPreviousSpeakers())

    manager.add_command('rungunicorn', RunGunicorn())

    @manager.command
    def import_xml(filename):
        pythonfosdem.tools.import_xml(filename)

    @manager.command
    def db_create():
        db.create_all()

    @manager.command
    def db_drop():
        db.drop_all()

    @manager.command
    def db_reset():
        pythonfosdem.tools.reset_db()

    manager.run()
Beispiel #3
0
	def test_global_option_provided_before_and_after_command(self, capsys):

		manager = Manager(self.app)
		manager.add_option('-c', '--config', dest='config_name', required=False, default='Development')
		manager.add_command('simple', SimpleCommand())

		assert isinstance(manager._commands['simple'], SimpleCommand)

		code = run('manage.py -c Development simple', manager.run)
		out, err = capsys.readouterr()
		assert code == 0
		assert 'OK' in out
def main():
    manager = Manager(create_app)
    conf_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'config', 'local.conf'))
    manager.add_option('-c', '--config', dest='config', default=conf_path, required=False)
    manager.add_option('-d', '--debug', dest='debug', default=False, required=False, action='store_true')
    asset_manager = ManageAssets(assets_env)
    manager.add_command("assets", asset_manager)

    def _make_context():
        return dict(app=current_app, db=models.db, models=models)
    manager.add_command("shell", Shell(make_context=_make_context))

    manager.run()
Beispiel #5
0
    def test_global_option_provided_before_and_after_command(self):

        manager = Manager(self.app)
        manager.add_option('-c', '--config', dest='config_name', required=False, default='Development')
        manager.add_command('simple', SimpleCommand())

        assert isinstance(manager._commands['simple'], SimpleCommand)

        stdout, code = run('manage.py -c Development simple', lambda: manager.run())
        assert code == 0
        assert 'OK' in stdout

        stdout, code = run('manage.py simple -c Development', lambda: manager.run())
        assert code == 0
        assert 'OK' in stdout
Beispiel #6
0
def create_script():
    manager = Manager(create_app, with_default_commands=True)
    manager.add_option('-c', '--config-file', dest='config_file',
                       required=False)

    @manager.shell
    def _make_context():
        return dict(app=_request_ctx_stack.top.app, db=db, Paste=Paste, Ip=Ip)

    manager.add_command('generatepw', GeneratePw())
    manager.add_command('db_version_control', DbVersionControl())
    manager.add_command('db_upgrade', DbUpgrade())
    manager.add_command('db_downgrade', DbDowngrade())
    manager.add_command('db_version', DbVersion())
    return manager
Beispiel #7
0
    def test_submanager_has_options(self):

        sub_manager = Manager()
        sub_manager.add_command('simple', SimpleCommand())

        manager = Manager(self.app)
        manager.add_command('sub_manager', sub_manager)
        manager.add_option('-c', '--config', dest='config', required=False)

        stdout, code = run('manage.py sub_manager simple', lambda: manager.run())
        assert code == 0
        assert 'OK' in stdout

        stdout, code = run('manage.py -c Development sub_manager simple', lambda: manager.run())
        assert code == 0
        assert 'OK' in stdout
Beispiel #8
0
    def test_submanager_separate_options(self, capsys):

        sub_manager = Manager(TestApp(verbose=True), with_default_commands=False)
        sub_manager.add_command('opt', CommandWithOptionalArg())
        sub_manager.add_option('-n', '--name', dest='name_sub', required=False)

        manager = Manager(TestApp(verbose=True), with_default_commands=False)
        manager.add_command('sub_manager', sub_manager)
        manager.add_option('-n', '--name', dest='name_main', required=False)

        code = run('manage.py -n MyMainName sub_manager -n MySubName opt -n MyName', manager.run)
        out, err = capsys.readouterr()
        assert code == 0
        assert 'APP name_main=MyMainName' in out
        assert 'APP name_sub=MySubName' in out
        assert 'OK name=MyName' in out
Beispiel #9
0
    def test_submanager_overrides_app(self, capsys):
        def gen_app(app, **kwargs):
            return SubAppForTesting(verbose=True)
        sub_manager = Manager(gen_app, with_default_commands=False)
        sub_manager.add_command('opt', CommandWithOptionalArg())
        sub_manager.add_option('-n', '--name', dest='name_sub', required=False)

        manager = Manager(AppForTesting(verbose=True), with_default_commands=False)
        manager.add_command('sub_manager', sub_manager)
        manager.add_option('-n', '--name', dest='name_main', required=False)

        code = run('manage.py -n MyMainName sub_manager -n MySubName opt -n MyName', manager.run)
        out, err = capsys.readouterr()
        assert code == 0
        assert 'APP name_main=MyMainName' in out
        assert 'SUB name_sub=MySubName' in out
        assert 'OK name=MyName' in out
Beispiel #10
0
def binder_app():
    manager = Manager(create_app)
    manager.add_option(
        '-c',
        '--config',
        dest='config',
        required=False,
        help='Path to configuration file'
    )
    manager.add_option(
        '-m',
        '--mode',
        dest='mode',
        required=False,
        help='App running mode. One of Development, Testing, and Production'
    )
    # We are off to the races
    manager.run()
Beispiel #11
0
    def test_global_option_value(self, capsys):

        def create_app(config_name='Empty'):
            print(config_name)
            return self.app

        manager = Manager(create_app)
        manager.add_option('-c', '--config', dest='config_name', required=False, default='Development')
        manager.add_command('simple', SimpleCommand())

        assert isinstance(manager._commands['simple'], SimpleCommand)

        code = run('manage.py simple', lambda: manager.run())
        out, err = capsys.readouterr()
        assert code == 0
        assert 'Empty' not in out  # config_name is overwritten by default option value
        assert 'Development' in out
        assert 'OK' in out
Beispiel #12
0
    def test_submanager_has_options(self, capsys):

        sub_manager = Manager()
        sub_manager.add_command('simple', SimpleCommand())

        manager = Manager(self.app)
        manager.add_command('sub_manager', sub_manager)
        manager.add_option('-c', '--config', dest='config', required=False)

        code = run('manage.py sub_manager simple', manager.run)
        out, err = capsys.readouterr()
        assert code == 0
        assert 'OK' in out

        code = run('manage.py -c Development sub_manager simple', manager.run)
        out, err = capsys.readouterr()
        assert code == 0
        assert 'OK' in out
Beispiel #13
0
def main():
    env = 'dev'
    try:
        env_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'use_env')
        env = open(env_file).read().strip()
        if env != 'dev':
            config_module = env + '_config'
            __import__('address_normalizer.' + config_module)
    except IOError:
        pass

    manager = Manager(create_app)
    manager.add_option('-e', '--env', required=False, default=env)
    manager.add_option('-c', '--config', required=False)

    manager.add_command('serve', GeventServer(manager))

    signal.signal(signal.SIGTERM, sigterm_handler)

    manager.run()
Beispiel #14
0
def create_script():
    """Script object factory

    :param repo_path: the path to the mercurial repository.
    :return: the script object (Flask-Script' Manager instance).
    """

    script = Manager(create_app, with_default_commands=False)
    script.add_option('--repo-path', dest='repo_path',
                      default=os.getcwd(), required=False,
                      help='Repository path')
    script.add_option('-e', '--disable-embedded-extensions',
                      action='store_false', dest='embedded_extensions',
                      default=True, help='disable the loading of extensions '
                      'from the mercurial repository')
    server = Server(use_debugger=True, use_reloader=True)
    server.description = 'runs the blohg local server.'
    script.add_command('runserver', server)
    script.add_command('initrepo', InitRepo())
    script.add_command('freeze', Freeze())

    return script
Beispiel #15
0
def main(default_command='moin', wiki_config=None):
    """
    console_script entry point
    """
    from MoinMoin.app import create_app
    from flask.ext.script import Manager, Server

    manager = Manager(create_app)
    manager.add_option('-c', '--config', dest='config', required=False, default=wiki_config)
    manager.add_option('-i', '--index-create', action='store_true', dest='create_index',
                       required=False, default=False)
    manager.add_option('-s', '--storage-create', action='store_true', dest='create_storage',
                       required=False, default=False)
    manager.add_command("moin", Server(host='127.0.0.1', port=8080))

    from MoinMoin.script.maint import index
    manager.add_command("index-create", index.IndexCreate())
    manager.add_command("index-build", index.IndexBuild())
    manager.add_command("index-update", index.IndexUpdate())
    manager.add_command("index-destroy", index.IndexDestroy())
    manager.add_command("index-move", index.IndexMove())
    manager.add_command("index-optimize", index.IndexOptimize())
    manager.add_command("index-dump", index.IndexDump())
    from MoinMoin.script.maint import serialization
    manager.add_command("save", serialization.Serialize())
    manager.add_command("load", serialization.Deserialize())
    from MoinMoin.script.account.create import Create_User
    manager.add_command("account-create", Create_User())
    from MoinMoin.script.account.disable import Disable_User
    manager.add_command("account-disable", Disable_User())
    from MoinMoin.script.account.resetpw import Set_Password
    manager.add_command("account-password", Set_Password())
    from MoinMoin.script.maint.reduce_revisions import Reduce_Revisions
    manager.add_command("maint-reduce-revisions", Reduce_Revisions())
    from MoinMoin.script.maint.set_meta import Set_Meta
    manager.add_command("maint-set-meta", Set_Meta())
    from MoinMoin.script.maint import modify_item
    manager.add_command("item-get", modify_item.GetItem())
    manager.add_command("item-put", modify_item.PutItem())
    from MoinMoin.script.migration.moin19.import19 import ImportMoin19
    manager.add_command("import19", ImportMoin19())

    from MoinMoin.script.maint.moinshell import MoinShell
    manager.add_command("shell", MoinShell())

    return manager.run(default_command=default_command)
Beispiel #16
0
#! /usr/bin/env python3
import logging
from flask.ext.script import Manager, Command

from App.App import create_app
from commands.get_deps import GetDeps
from commands.dbutils import InitDB, UpdateDB, FixFont
from commands.run_tests import RunTests

from colorama import init as init_colorama
from colorama import Fore, Back, Style
init_colorama(autoreset=True)

from flask.ext.assets import ManageAssets

manager = Manager(create_app)
manager.add_option('-c', '--app-config', dest='config', required=False)
manager.add_command('get_deps', GetDeps())
manager.add_command("assets", ManageAssets())
manager.add_command('initdb', InitDB())
manager.add_command('updatedb', UpdateDB())
manager.add_command('fixfont', FixFont())
manager.add_command('test', RunTests)

if __name__ == '__main__':
    log_fmt = '[notMyType][%(levelname)s] %(lineno)d in %(funcName)s - %(message)s'
    logging.basicConfig(format=log_fmt,
                        level=logging.DEBUG)
    manager.run()
Beispiel #17
0

# Global constants
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'scrappyr', 'static')
KARMA_EXEC = os.path.join(STATIC_ROOT, 'node_modules',
                          'karma-cli', 'bin', 'karma')
KARMA_CONFIG = os.path.join(STATIC_ROOT, 'karma.conf.js')
WEBPACK_DEV_SERVER_EXEC = os.path.join(STATIC_ROOT, 'node_modules',
                                       '.bin', 'webpack-dev-server')


manager = Manager(create_app)

# Options passed to `create_app`.
manager.add_option('-c', '--config-file',
                   help="Configuration file (*.py or *.json) for Flask app.")
manager.add_option('-d', '--db-uri',
                   help="SQLAlchemy database URI.")
manager.add_option('-w', '--with-webpack-dev-server', action='store_true',
                   help="Configure Flask app to run with webpack dev server")


manager.add_command('server', Server())
manager.add_command('db', MigrateCommand)
manager.add_command('show-urls', ShowUrls())
manager.add_command('clean', Clean())


class StartAndOpenServer(Server):

    help = description = ("Runs the Flask development server i.e. app.run() "
Beispiel #18
0
from flask.ext.script import Manager
import nose
import requests

from orvsd_central import create_app
from orvsd_central.database import (create_db_session, create_admin_account,
                                    init_db)


def setup_app(config=None):
    return create_app(config) if config else create_app()


# Setup our manager
manager = Manager(setup_app)
manager.add_option('-c', '--config', dest='config')


@manager.command
def gather_siteinfo():
    """
    Gather SiteInfo

    This is a nice management wrapper to the util method that grabs moodle
    sitedata from the orvsd_siteinfo webservice plugin for all sites in
    orvsd_central's database
    """

    with current_app.app_context():
        from orvsd_central.models import Site
        from orvsd_central.util import gather_siteinfo
Beispiel #19
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask.ext.script import Manager, Server
from flask.ext.collect import Collect
from quokka import create_app
from quokka.core.db import db
from quokka.ext.blueprints import load_blueprint_commands

app = create_app()
manager = Manager(app)
manager.add_option("-c", "--config",
                   dest="config", required=False,
                   default='quokka.settings')

collect = Collect()
collect.init_script(manager)


@manager.shell
def make_shell_context():
    " Update shell. "
    return dict(app=app, db=db)


@manager.command
def check():
    """Prints app status"""
    from pprint import pprint
    print("Extensions.")
    pprint(app.extensions)
Beispiel #20
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import urlparse
import subprocess

from flask.ext.script import Manager

from {{PROJECT_NAME}} import create_app


app = create_app()

manager = Manager(create_app)
manager.add_option('-e', '--environment', dest='evironment', required=False)


@manager.command
def dbshell():

    url = urlparse.urlparse(app.config['SQLALCHEMY_DATABASE_URI'])
    params = {
        'db_name': url.path.strip('/'),
        'user': url.username,
        'host': url.hostname,
    }
    cmd = "psql {db_name} -U {user} -h {host}".format(**params)
    subprocess.call(cmd, shell=True)


if __name__ == "__main__":
Beispiel #21
0
#
# Copyright 2011 Microsoft Corporation
#
# 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.
#

# Set the path
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from flask.ext.script import Manager, Server
import resourceprovider

manager = Manager(resourceprovider.create_app)
manager.add_option("-e", "--env", dest="env", required=False)

# Turn on debugger by default and reloader
manager.add_command(
    "runserver", Server(use_debugger=True, use_reloader=True, host='0.0.0.0'))

if __name__ == "__main__":
    manager.run()
Beispiel #22
0
#!/usr/bin/env python
from app import create_app, db
from app.models import User, Role
from config import config
from flask.ext.script import Manager, Shell
from flask.ext.migrate import MigrateCommand
import commands

manager = Manager(create_app)
manager.add_option("-c",
                   "--config",
                   dest="config_name",
                   required=False,
                   default=config['development'])


@manager.command
def test():
    """Run the unit tests"""
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)


def make_shell_context():
    return dict(app=create_app('development'), db=db, User=User, Role=Role)


#    return dict(app=app, db=db, User=User, Follow=Follow, Role=Role,
#Permission=Permission, Post=Post, Comment=Comment)
Beispiel #23
0
#!flask/bin/python
from app import db, create_app
from flask.ext.script import Manager
from app.commands import CreateStaticData

manager = Manager(create_app)

@manager.command
def create_db():
    db.create_all()

@manager.command
def drop_db():
    db.drop_all()

@manager.command
def recreate_db():
    drop_db()
    create_db()
    CreateStaticData().run()

manager.add_command('create_static_data', CreateStaticData())

manager.add_option('-c', '--config', dest='config', required=False)

if __name__ == '__main__':
    manager.run()
Beispiel #24
0
        db.session.rollback()


@manager.option('-t', '--txid', dest='transaction_id')
def confirm_trans(transaction_id):
    """ Manually confirms a transaction. Shouldn't be needed in normal use. """
    trans = Transaction.query.filter_by(txid=transaction_id).first()
    trans.confirmed = True
    db.session.commit()


def make_context():
    """ Setup a coinserver connection fot the shell context """
    app = _request_ctx_stack.top.app
    import simplecoin.models as m
    return dict(app=app, currencies=currencies, powerpools=powerpools, m=m, db=db)
manager.add_command("shell", Shell(make_context=make_context))


manager.add_command("runserver", Server())
manager.add_command('db', MigrateCommand)
manager.add_command('scheduler', SchedulerCommand)
manager.add_option('-c', '--config', dest='configs', action='append',
                   type=argparse.FileType('r'))
manager.add_option('-l', '--log-level',
                   choices=['DEBUG', 'INFO', 'WARN', 'ERROR'], default='INFO')


if __name__ == "__main__":
    manager.run()
Beispiel #25
0
import logging

from flask import current_app
from flask.ext.script import Shell, Manager, Server, prompt_bool

from {{ cookiecutter.app_name }} import db, create_app

log = logging.getLogger(__name__)

manager = Manager(create_app)
manager.add_command('runserver', Server(host="0.0.0.0", port=8000))
manager.add_option(
    '-c', '--config', dest='config', default='config.py', required=False)


def _make_context():
    from flask import current_app

    return dict(
        app=current_app,
        drop=drop,
        create=create,
        recreate=recreate,
        populate=populate,
    )


manager.add_command('shell', Shell(make_context=lambda: _make_context()))


@manager.command
Beispiel #26
0
manager = Manager(create_app)

@manager.command
def test():
    """Run tests"""
    nose.run(argv=["-w ."])



@manager.command
def dumpconfig():
    """Dumps config"""
    pprint.pprint(current_app.config)

manager.add_option("-c", "--config",
                   dest="config",
                   help="config file",
                   required=False)
manager.add_option("-d", "--debug",
                   dest="debug",
                   help="run in debug mode",
                   default=False)

manager.add_command("runservernoreload", Server(use_reloader=False))
manager.add_command("urls", ShowUrls())
manager.add_command("clean", Clean())

if __name__ == "__main__":
    manager.run()
        env_path = os.path.join(os.path.dirname(os.path.dirname(__file__)),
                                '.env', 'default')
        env.update(load_config(env_path))
    except IOError:
        # e.g. running in Heroku
        print 'No default env file'
    if config is not None:
        env.update(load_config(config))
    os.environ.update(env)
    return mim_create_app()


manager = Manager(create_app)
manager.add_option(
    '-c',
    '--config',
    dest='config',
    required=False,
    help='Foreman-style env file that will be loaded into app\'s ENV')
manager.add_command('debug', Server(use_debugger=True))
manager.add_command('clean', Clean())
manager.add_command('database', database.manager)


@manager.command
def config():
    """Pretty prints the app's config"""
    pprint.pprint(dict(current_app.config))


@manager.command
def imgur_auth():
Beispiel #28
0
    choices = (
        (1, "member"),
        (2, "moderator"),
        (3, "admin"),
    )

    role = prompt_choices("role", choices=choices, resolve=int, default=1)
    print("ROLE:", role)


@manager.option('-n', '--name', dest='name', help="your name")
@manager.option('-u', '--url', dest='url', help="your url")
def optional(name, url):
    "print name and url"
    print(name, url)


manager.add_option("-c",
                   "--config",
                   dest="config",
                   help="config file",
                   required=False)

manager.add_command("runservernoreload", Server(use_reloader=False))
manager.add_command("urls", ShowUrls())
manager.add_command("clean", Clean())

if __name__ == "__main__":
    manager.run()
Beispiel #29
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask.ext.script import Manager

from osrc import create_app
from osrc.manage import (
    CreateTablesCommand,
    DropTablesCommand,
    UpdateCommand,
)

if __name__ == "__main__":
    manager = Manager(create_app)
    manager.add_option("-f",
                       "--filename",
                       dest="config_filename",
                       required=False)

    manager.add_command("create", CreateTablesCommand())
    manager.add_command("drop", DropTablesCommand())
    manager.add_command("update", UpdateCommand())

    manager.run()
Beispiel #30
0
        else:
            empty = 0

        if not simulate:
            print "deleting {}!".format(key)
            print redis_conn.delete(key)
        else:
            print "would delete {}".format(key)


def make_context():
    """ Setup a coinserver connection fot the shell context """
    app = _request_ctx_stack.top.app
    import simplecoin.models as m
    return dict(app=app, currencies=currencies, powerpools=powerpools, m=m)
manager.add_command("shell", Shell(make_context=make_context))
manager.add_command('db', MigrateCommand)
manager.add_command('scheduler', SchedulerCommand)
manager.add_option('-c', '--config', default='config.yml')
manager.add_option('-l', '--log-level',
                   choices=['DEBUG', 'INFO', 'WARN', 'ERROR'], default='INFO')


@manager.command
def runserver():
    current_app.run(debug=True, host='0.0.0.0')


if __name__ == "__main__":
    manager.run()
Beispiel #31
0
                    obj.spent_tx = tx_obj
                    tx_obj.total_in += obj.amount
            else:
                tx_obj.coinbase = True

            block_obj.total_in += tx_obj.total_in
            block_obj.total_out += tx_obj.total_out

        highest = block_obj
        db.session.commit()
        block_times.append(time.time() - t)

        # Display progress information
        time_per = sum(block_times) / len(block_times)
        time_remain = datetime.timedelta(seconds=time_per *
                                         (server_height - curr_height))
        current_app.logger.info("{:,}/{:,} {} estimated to catchup".format(
            curr_height, server_height, time_remain))

    db.session.commit()


manager.add_option('-c', '--config', default='/config.yml')
manager.add_option('-l',
                   '--log-level',
                   choices=['DEBUG', 'INFO', 'WARN', 'ERROR'],
                   default='INFO')

if __name__ == "__main__":
    manager.run()
Beispiel #32
0
    if not app.config.get('SSL_MODE'):
      # remove SSL context
      del self.server_options['ssl_context']

    # run the original ``__call__`` function
    super(SecureServer, self).__call__(app, *args, **kwargs)


@manager.shell
def make_shell_context():
  """Return context dict for a shell session.

  This enables quick access to the Flask ``app`` object.

  Returns:
    dict: context object for the Shell session.
  """
  return dict(app=app())


manager.add_option(
  '-c', '--config', dest='config', required=False, help='config file path')
# command meant to be run in a Vagrant environment during development
manager.add_command('vagrant', Server(host='0.0.0.0', use_reloader=True))
# command meant to be run in production using SSL encryption
manager.add_command('serve', SecureServer(ssl_context=ctx, host='0.0.0.0'))


if __name__ == '__main__':
  manager.run()
Beispiel #33
0
from config.application import AVAILABLE_CONFIGS, DEFAULT_CONFIG
from test import factories

manager = Manager(failsafe(create_app), with_default_commands=False)


def _make_context():
    context = dict(app=manager.app, db=db)
    # Add models to the context
    context.update(getmembers(
        models, lambda m: isclass(m) and issubclass(m, db.Model)
    ))
    # Add factories to the context
    context.update(getmembers(
        factories,
        lambda m: isclass(m) and issubclass(m, SQLAlchemyModelFactory)
    ))
    return context

manager.add_option('-c', '--config', dest='config',
                   choices=list(AVAILABLE_CONFIGS), default=DEFAULT_CONFIG)
manager.add_command('clean', Clean())
manager.add_command('server', Server(host='0.0.0.0'))
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('urls', ShowUrls())
manager.add_command('db', MigrateCommand)
manager.add_command("assets", ManageAssets())

if __name__ == '__main__':
    manager.run()
Beispiel #34
0

class SyncDB(Command):
    """Create the database schema and load join tables."""
    def run(self):
        from flask import current_app
        db_uri = current_app.config['SQLALCHEMY_DATABASE_URI']
        print "Creating schemas..."
        data.create_schemas(db_uri)
        print "Loading code sheet..."
        data.load_code_sheet(db_uri)
        print "Downloading & loading MSA data..."
        cbsa.load_cbsa(db_uri)
        print "Downloading & loading geographic data..."
        geo.load_all(db_uri)


manager = Manager(create_app)
manager.add_option('-c', '--config',
                   dest='config',
                   required=False,
                   help='Path to configuration file.',
                   default='sample_config.py')
manager.add_command("runserver", Server())
manager.add_command("assets", ManageAssets())
manager.add_command("syncdb", SyncDB())


if __name__ == "__main__":
    manager.run()
Beispiel #35
0
                       locale_code="en_UG")
    db.session.add(english)
    luganda = Language(name="Luganda",
                       iso639_1="lg",
                       iso639_2="lug",
                       locale_code="lg_UG")
    db.session.add(luganda)

    db.session.commit()
    alembic_cfg = Config("alembic.ini")
    command.stamp(alembic_cfg, "head")


manager.add_option('-c',
                   '--config',
                   dest="config",
                   required=False,
                   help="config file")


@manager.command
def demo_data(schedule=0):
    from rootio import demo_data
    demo_data.setup(db, int(schedule))


@manager.command
def drop_db_hard():
    #for when db.drop_all won't cut it, particularly with postgres on server

    print "WARNING: This will drop all database tables."
Beispiel #36
0
from flask.ext.script import Manager
from flask import current_app
from geordi import create_app
from geordi.data import model
from geordi.data.manage import data_manager
from geordi.resources import resources_manager

manager = Manager(create_app)
manager.add_option('-l', '--log-debug', dest='log_debug', required=False, action='store_true')
manager.add_option('-s', '--log-sql', dest='log_sql', required=False, action='store_true')

manager.add_command('data', data_manager)
manager.add_command('resources', resources_manager)

@manager.command
def create_tables():
    model.create_tables(current_app)

if __name__ == "__main__":
    manager.run()
Beispiel #37
0
#!/usr/bin/env python
from commands.runserver import Server
from flask.ext.script import Manager
from flask.ext.migrate import MigrateCommand
from jia import config

manager = Manager(config)
manager.add_option('--config', dest='settings_file', required=False)
manager.add_command('runserver', Server())
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
  manager.run()
Beispiel #38
0
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals

import os.path as p

from subprocess import call, check_call
from pprint import pprint

from flask import current_app as app
from flask.ext.script import Server, Manager
from tabutils import fntools as ft

from app import create_app, db, models, utils


manager = Manager(create_app)
manager.add_option("-m", "--cfgmode", dest="config_mode", default="Development")
manager.add_option("-f", "--cfgfile", dest="config_file", type=p.abspath)
manager.main = manager.run  # Needed to do `manage <command>` from the cli


@manager.option("-h", "--host", help="The server host", default=None)
@manager.option("-p", "--port", help="The server port", default=None)
@manager.option("-t", "--threaded", help="Run multiple threads", action="store_true")
def runserver(**kwargs):
    # Overriding the built-in `runserver` behavior
    """Runs the flask development server"""

    with app.app_context():
        skwargs = {
            "host": kwargs.get("host") or app.config["HOST"],
            "port": kwargs.get("port") or app.config["PORT"],
Beispiel #39
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask.ext.script import Manager

from magic_api.app.extensions import db
from magic_api.app import create_app
from magic_api.api import ResourcesMaker

manager = Manager(create_app)
manager.add_option('-i', '--inst', dest='instance_folder', required=False)
manager.add_option('-b', '--backend', dest='backend', required=False)
manager.add_option('-d', '--datapackage', dest='datapackage', required=True)


@manager.command
def run():
    """Run in local machine."""
    manager.app.run()


@manager.command
def test():
    """Run tests."""
    pass


@manager.command
def initdb():
    """Init or reset database."""
    with manager.app.app_context():
Beispiel #40
0
@manager.command
def getrole():

    choices = (
        (1, "member"),
        (2, "moderator"),
        (3, "admin"),
    )

    role = prompt_choices("role", choices=choices, resolve=int, default=1)
    print "ROLE:", role


@manager.option('-n', '--name', dest='name', help="your name")
@manager.option('-u', '--url', dest='url', help="your url")
def optional(name, url):
    "print name and url"
    print name, url

manager.add_option("-c", "--config",
                   dest="config",
                   help="config file",
                   required=False)

manager.add_command("runservernoreload", Server(use_reloader=False))
manager.add_command("urls", ShowUrls())
manager.add_command("clean", Clean())

if __name__ == "__main__":
    manager.run()
Beispiel #41
0
            print("Directory \"%s\" was not found in project root." %
                start_discovery)


class Clean(Command):
    """Clean generated binary files"""

    def run(self):
        """Cleans all .pyc files from the source tree"""
        findcmd = 'find %s -name "*.pyc" -print' % '.'
        count = 0
        for f in os.popen(findcmd).readlines():
            count += 1
            print str(f[:-1])
            os.remove(str(f[:-1]))
        print "Removed %d .pyc files" % count


manager.add_option("-c", "--config", dest="config", required=False,
    default=config.Dev)
manager.add_command("test", Test())
manager.add_command("create_db", CreateDB())
manager.add_command("drop_db", DropDB())
manager.add_command("seed_db", SeedDB())
manager.add_command("clean", Clean())
manager.add_command("assets", ManageAssets())


if __name__ == "__main__":
    manager.run()
Beispiel #42
0
# Set the path
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from flask.ext.script import Manager, Server, Command, Option
from quickhunt import create_app

manager = Manager(create_app)

manager.add_option('-e', '--env', dest='env', required=False, default='debug')

# Turn on debugger by default and reloader
manager.add_command("runserver", Server(
    use_reloader = True,
    port = int(os.environ.get('PORT', 5000)),
    host = '0.0.0.0')
)


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

Beispiel #43
0
from __future__ import (absolute_import, division, print_function,
                        with_statement, unicode_literals)

import os.path as p

from subprocess import call, check_call

from flask import current_app as app
from flask.ext.script import Server, Manager

from app import create_app, db

manager = Manager(create_app)
manager.add_option('-m',
                   '--cfgmode',
                   dest='config_mode',
                   default='Development')
manager.add_option('-f', '--cfgfile', dest='config_file', type=p.abspath)
manager.main = manager.run  # Needed to do `manage <command>` from the cli


@manager.option('-h', '--host', help='The server host', default=None)
@manager.option('-p', '--port', help='The server port', default=None)
@manager.option('-t',
                '--threaded',
                help='Run multiple threads',
                action='store_true')
def runserver(**kwargs):
    # Overriding the built-in `runserver` behavior
    """Runs the flask development server"""
Beispiel #44
0
        except AttributeError as e:
            print('Table does not exist: {}'.format(e))
            continue
        if restored:
            print('Importing {} table...'.format(restored[0].__table__.name))
        for item in restored:
            db.session.merge(item)

        db.session.commit()

    print('Done')


@manager.option('-d', '--destination', dest='destination', default=None, required=True, help='Output file')
def dump(destination):
    dump_models = []  # List of models you want to dump
    serialized = list()
    for model in dump_models:
        print('Dumping {}'.format(model))
        serialized.append(unicode(dumps(db.session.query(model).all()), errors='ignore'))
    with open(destination, 'w') as f:
        f.writelines(json.dumps(serialized))
    print('Done.')


manager.add_option('-c', '--config', dest="config", required=False,
    help="config file")

if __name__ == "__main__":
    manager.run()
Beispiel #45
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import sys

from flask.ext.script import Manager, Server, Shell
from admin_site import create_app
from ops.deploy.deploy import deploy

manager = Manager(create_app)
manager.add_option('-e', '--env', dest='env', required=False)
manager.add_option('-d',
                   '--deploy',
                   action='store_true',
                   dest='deploy',
                   required=False,
                   default=False)


def make_shell_context():
    from admin_site import config
    return dict(app=manager.app, config=config)


manager.add_command("shell", Shell(make_context=make_shell_context))

server = Server(host="0.0.0.0", port=5204)
manager.add_command("runserver", server)


@manager.option('-u',