Exemplo n.º 1
0
def main():
    app = init_app()
    manager = Manager(app)
    manager.add_command('seed', Seed())
    # manager.add_command('import', ImportVisitors())
    manager.run()
    return app
Exemplo n.º 2
0
 def test_run_with_default_command(self):
     manager = Manager(self.app)
     manager.add_command('simple', SimpleCommand())
     try:
         manager.run(default_command='simple')
     except SystemExit, e:
         assert e.code == 0
Exemplo n.º 3
0
def create_app(config_name):
    app = Flask(__name__)
    app.debug = True
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)

    db = SQLAlchemy(app)
    bootstrap = Bootstrap(app)
    moment = Moment(app)
    manager = Manager(app)
    mail = Mail(app)
    migrate = Migrate(app, db)
    manager.add_command('db', MigrateCommand)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from .api_1_0 import api as api_1_0_blueprint
    app.register_blueprint(api_1_0_blueprint, url_prefix='/api/v1.0')

    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        sslify = SSLify(app)

    return app
Exemplo n.º 4
0
class ServiceManager:

    def __init__(self, service):
        # create and attach a command manager for the service
        self.commandManager = Manager(service.app)
        self.service = service

        @self.commandManager.command
        def syncdb():
            """ Create the database entries. """
            # import the db module
            from nautilus.db import db
            # create all of the tables
            db.create_all()
            # notify the user
            print("Successfully created database entries.")

        @self.commandManager.command
        def runserver(host = '127.0.0.1', port = 8000, debug = False, secretKey = 'supersecret'):
            """ Start the service. """
            service.run(host = host, port = int(port), debug = debug, secretKey = secretKey)


    def run(self):
        """ run the command manager """
        try:
            self.commandManager.run()
        except KeyboardInterrupt:
            print()
            print("Cleaning up service...")
            self.service.stop()
        except Exception as err:
            print("Closing due to error: %s" % err)
            self.service.stop()
Exemplo n.º 5
0
def create_manager(app):
    manager = Manager(app)

    manager.add_command('db', db_manager)
    manager.add_command('user', user_manager)
    manager.add_command('work', work_manager)
    return manager
Exemplo n.º 6
0
    def test_run_catch_all(self):
        manager = Manager(self.app)
        manager.add_command('catch', CommandWithCatchAll())

        stdout, code = run('manage.py catch pos1 --foo pos2 --bar', lambda: manager.run())
        assert code == 0
        assert "['pos1', 'pos2', '--bar']" in stdout
Exemplo n.º 7
0
    def test_run_existing_bind_later(self):

        manager = Manager(self.app)

        stdout, code = run('manage.py simple', lambda: manager.run({'simple': SimpleCommand()}))
        assert code == 0
        assert 'OK' in stdout
Exemplo n.º 8
0
def run_cli():  # pragma: no cover
    app = create_base_app()
    register_blueprints(app)

    cli = Manager(app)
    cli.add_command("db", MigrateCommand)
    cli.run()
Exemplo n.º 9
0
def run():
    iatidq.db.create_all()
    iatidq.dqimporttests.hardcodedTests()
    manager = Manager(iatidataquality.app)
    server = Server(host='0.0.0.0')
    manager.add_command("runserver", server)
    manager.run()
Exemplo n.º 10
0
    def test_command_with_default_prompt(self, capsys):

        manager = Manager(self.app)

        @manager.command
        def hello():
            print(prompt(name='hello', default='romeo'))

        @Catcher
        def hello(msg):
            if re.search("hello", msg):
                return '\n'  # just hit enter

        with hello:
            code = run('manage.py hello', lambda: manager.run())
            out, err = capsys.readouterr()
            assert 'hello [romeo]: romeo' in out

        @Catcher
        def hello_juliette(msg):
            if re.search("hello", msg):
                return 'juliette'

        with hello_juliette:
            code = run('manage.py hello', lambda: manager.run())
            out, err = capsys.readouterr()
            assert 'hello [romeo]: juliette' in out
Exemplo n.º 11
0
    def test_run_existing_command(self, capsys):

        manager = Manager(self.app)
        manager.add_command('simple', SimpleCommand())
        code = run('manage.py simple', lambda: manager.run())
        out, err = capsys.readouterr()
        assert 'OK' in out
Exemplo n.º 12
0
def create_app():
    app = Flask(__name__)
    auto = Autodoc(app)
    cal = Calendar()
    event = Event()
    from open_event.views.views import app as routes

    app.register_blueprint(routes)
    migrate = Migrate(app, db)

    db.init_app(app)
    manager = Manager(app)
    manager.add_command("db", MigrateCommand)

    cors = CORS(app)
    app.secret_key = "super secret key"
    app.config.from_object("config.ProductionConfig")
    app.config["UPLOADS_FOLDER"] = os.path.realpath(".") + "/static/"
    app.config["FILE_SYSTEM_STORAGE_FILE_VIEW"] = "static"
    app.config["STATIC_URL"] = "/static/"
    app.config["STATIC_ROOT"] = "staticfiles"
    app.config["STATICFILES_DIRS"] = (os.path.join(BASE_DIR, "static"),)
    app.logger.addHandler(logging.StreamHandler(sys.stdout))
    app.logger.setLevel(logging.ERROR)

    admin_view = AdminView("Open Event")
    admin_view.init(app)
    admin_view.init_login(app)

    return app, manager, db
Exemplo n.º 13
0
    def test_submanager_usage_and_help_and_description(self, capsys):

        sub_manager = Manager(usage='sub_manager [--foo]',
                              help='shorter desc for submanager',
                              description='longer desc for submanager')
        sub_manager.add_command('simple', SimpleCommand())

        manager = Manager(self.app)
        manager.add_command('sub_manager', sub_manager)

        code = run('manage.py -h', lambda: manager.run())
        out, err = capsys.readouterr()
        assert code == 0
        assert 'sub_manager [--foo]' not in out
        assert 'shorter desc for submanager' in out
        assert 'longer desc for submanager' not in out

        code = run('manage.py sub_manager', lambda: manager.run())
        out, err = capsys.readouterr()
        assert code == 2
        assert 'too few arguments' in err

        code = run('manage.py sub_manager -h', lambda: manager.run())
        out, err = capsys.readouterr()
        assert code == 0
        assert 'sub_manager [--foo]' in out
        assert 'shorter desc for submanager' not in out
        assert 'longer desc for submanager' in out
        assert 'simple command' in out

        code = run('manage.py sub_manager simple -h', lambda: manager.run())
        out, err = capsys.readouterr()
        assert code == 0
        assert 'sub_manager [--foo] simple [-h]' in out
        assert 'simple command' in out
Exemplo n.º 14
0
def create_app():
    auto = Autodoc(app)
    cal = Calendar()
    event = Event()
    from open_event.views.views import app as routes
    app.register_blueprint(routes)
    migrate = Migrate(app, db)

    db.init_app(app)
    manager = Manager(app)
    manager.add_command('db', MigrateCommand)

    cors = CORS(app)
    app.secret_key = 'super secret key'
    app.config.from_object('config.ProductionConfig')
    # app.config.from_object('config.LocalSQLITEConfig')
    app.config['UPLOADS_FOLDER'] = os.path.realpath('.') + '/static/'
    app.config['FILE_SYSTEM_STORAGE_FILE_VIEW'] = 'static'
    app.config['STATIC_URL'] = '/static/'
    app.config['STATIC_ROOT'] = 'staticfiles'
    app.config['STATICFILES_DIRS'] = (os.path.join(BASE_DIR, 'static'),)
    app.logger.addHandler(logging.StreamHandler(sys.stdout))
    app.logger.setLevel(logging.INFO)
    # logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

    admin_view = AdminView("Open Event")
    admin_view.init(app)
    admin_view.init_login(app)

    return app, manager, db
Exemplo n.º 15
0
def migrate():
    migrate = Migrate(app, db)

    manager = Manager(app)
    manager.add_command('db', MigrateCommand)

    manager.run()
Exemplo n.º 16
0
def main():
    manager = Manager(create_app)

    @manager.command
    def show_routes():
        print current_app.url_map

    @manager.command
    def db_populate():
        user_admin = User(name='Administrator', username='******', password='******', email='*****@*****.**')
        db.session.add(user_admin)

        for i in range(1, 100):
            report = Report(user=user_admin, name='My Report {}'.format(i))
            db.session.add(report)

        db.session.commit()


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

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

    manager.run()
Exemplo n.º 17
0
    def test_without_default_commands(self):

        manager = Manager(self.app, with_default_commands=False)
        manager.set_defaults()

        assert 'runserver' not in manager._commands
        assert 'shell' not in manager._commands
Exemplo n.º 18
0
    def test_get_usage(self):

        manager = Manager(self.app)
        manager.add_command('simple', SimpleCommand())

        usage = manager.create_parser('manage.py').format_help()
        assert 'simple command' in usage
Exemplo n.º 19
0
    def test_with_default_commands(self):

        manager = Manager(self.app)
        manager.set_defaults()

        assert 'runserver' in manager._commands
        assert 'shell' in manager._commands
Exemplo n.º 20
0
    def test_command_decorator_with_additional_options(self, capsys):

        manager = Manager(self.app)

        @manager.option('-n', '--name', dest='name', help='Your name')
        def hello(name):
            print('hello ' + name)

        assert 'hello' in manager._commands

        code = run('manage.py hello --name=joe', lambda: manager.run())
        out, err = capsys.readouterr()
        assert 'hello joe' in out

        code = run('manage.py hello -h', lambda: manager.run())
        out, err = capsys.readouterr()
        assert 'Your name' in out

        @manager.option('-n', '--name', dest='name', help='Your name')
        @manager.option('-u', '--url', dest='url', help='Your URL')
        def hello_again(name, url=None):
            if url:
                print('hello ' + name + ' from ' + url)
            else:
                print('hello ' + name)

        assert 'hello_again' in manager._commands

        code = run('manage.py hello_again --name=joe', lambda: manager.run())
        out, err = capsys.readouterr()
        assert 'hello joe' in out

        code = run('manage.py hello_again --name=joe --url=reddit.com', lambda: manager.run())
        out, err = capsys.readouterr()
        assert 'hello joe from reddit.com' in out
def create_app(config):

    app = Flask(__name__)
    app.config.from_object(config)

    from remedyblueprint import remedy, url_for_other_page
    app.register_blueprint(remedy)

    from admin import admin
    admin.init_app(app)

    from auth.user_auth import auth, login_manager
    app.register_blueprint(auth)
    login_manager.init_app(app)

    # searching configurations
    app.jinja_env.trim_blocks = True
    # Register the paging helper method with Jinja2
    app.jinja_env.globals['url_for_other_page'] = url_for_other_page
    app.jinja_env.globals['logged_in'] = lambda : not current_user.is_anonymous()

    db.init_app(app)

    Migrate(app, db, directory=app.config['MIGRATIONS_DIR'])

    manager = Manager(app)
    manager.add_command('db', MigrateCommand)

    # turning API off for now
    # from api_manager import init_api_manager
    # api_manager = init_api_manager(app, db)
    # map(lambda m: api_manager.create_api(m), models)
    
    return app, manager
Exemplo n.º 22
0
    def test_command_decorator_with_boolean_options(self, capsys):

        manager = Manager(self.app)

        @manager.command
        def verify(verified=False):
            'Checks if verified'
            print('VERIFIED ? ' + 'YES' if verified else 'NO')

        assert 'verify' in manager._commands

        code = run('manage.py verify --verified', lambda: manager.run())
        out, err = capsys.readouterr()
        assert 'YES' in out

        code = run('manage.py verify -v', lambda: manager.run())
        out, err = capsys.readouterr()
        assert 'YES' in out

        code = run('manage.py verify', lambda: manager.run())
        out, err = capsys.readouterr()
        assert 'NO' in out

        code = run('manage.py verify -h', lambda: manager.run())
        out, err = capsys.readouterr()
        assert 'Checks if verified' in out
Exemplo n.º 23
0
    def test_run_with_default_command(self):
        manager = Manager(self.app)
        manager.add_command('simple', SimpleCommand())

        stdout, code = run('manage.py', lambda: manager.run(default_command='simple'))
        assert code == 0
        assert 'OK' in stdout
Exemplo n.º 24
0
    def test_command_decorator_with_options(self, capsys):

        manager = Manager(self.app)

        @manager.command
        def hello(name='fred'):
            'Prints your name'
            print('hello ' + name)

        assert 'hello' in manager._commands

        code = run('manage.py hello --name=joe', lambda: manager.run())
        out, err = capsys.readouterr()
        assert 'hello joe' in out

        code = run('manage.py hello -n joe', lambda: manager.run())
        out, err = capsys.readouterr()
        assert 'hello joe' in out

        code = run('manage.py hello -h', lambda: manager.run())
        out, err = capsys.readouterr()
        assert 'Prints your name' in out

        code = run('manage.py hello --help', lambda: manager.run())
        out, err = capsys.readouterr()
        assert 'Prints your name' in out
Exemplo n.º 25
0
    def test_run_not_existing(self):

        manager = Manager(self.app)

        stdout, code = run('manage.py simple', lambda: manager.run())
        assert code == 2
        assert 'OK' not in stdout
Exemplo n.º 26
0
    def test_add_named_command(self):

        manager = Manager(self.app)
        manager.add_command(NamedCommand())

        assert 'named' in manager._commands
        assert isinstance(manager._commands['named'], NamedCommand)
Exemplo n.º 27
0
    def test_command_decorator_with_additional_options(self):

        manager = Manager(self.app)

        @manager.option('-n', '--name', dest='name', help='Your name')
        def hello(name):
            print 'hello', name

        assert 'hello' in manager._commands

        stdout, code = run('manage.py hello --name=joe', lambda: manager.run())
        assert 'hello joe' in stdout

        stdout, code = run('manage.py hello -h', lambda: manager.run())
        assert 'Your name' in stdout

        @manager.option('-n', '--name', dest='name', help='Your name')
        @manager.option('-u', '--url', dest='url', help='Your URL')
        def hello_again(name, url=None):
            if url:
                print 'hello', name, 'from', url
            else:
                print 'hello', name

        assert 'hello_again' in manager._commands

        stdout, code = run('manage.py hello_again --name=joe', lambda: manager.run())
        assert 'hello joe' in stdout

        stdout, code = run('manage.py hello_again --name=joe --url=reddit.com', lambda: manager.run())
        assert 'hello joe from reddit.com' in stdout
Exemplo n.º 28
0
def create_app():
    from colorama import init
    init()
    from config import add_configs
    app = add_configs(Flask(__name__))

    from sqlalchemy_utils.functions import database_exists, create_database
    if not database_exists(app.config.get('SQLALCHEMY_DATABASE_URI')):
        create_database(app.config.get('SQLALCHEMY_DATABASE_URI'), encoding='utf8')

    with app.app_context():
        from models import db

        db.init_app(app)
        app.db = db

        from models.oauth2 import oauth2_provider
        oauth2_provider.init_app(app)

        # import models
        Migrate(app, db, directory='bin/migrations/')

        mgr = Manager(app)
        mgr.add_command('db', MigrateCommand)

    return mgr
Exemplo n.º 29
0
    def test_run_no_name(self):

        manager = Manager(self.app)
        sys.argv = ["manage.py"]
        try:
            manager.run()
        except SystemExit, e:
            assert e.code == 1
Exemplo n.º 30
0
 def test_run_catch_all(self):
     manager = Manager(self.app)
     manager.add_command("catch", CommandWithCatchAll())
     sys.argv = ["manage.py", "catch", "pos1", "--foo", "pos2", "--bar"]
     try:
         manager.run()
     except SystemExit, e:
         assert e.code == 0
Exemplo n.º 31
0
import os
from flask.ext.script import Manager, Shell, Server
from flask_migrate import Migrate, MigrateCommand
from app import app
from app.core.db import db

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


def _make_context():
    return {'app': app}


# Adding Shell Command
# python manage.py [arg]
manager.add_command('db', MigrateCommand)
manager.add_command('run', Server(host='0.0.0.0', port=9000))
manager.add_command('shell', Shell(make_context=_make_context))

if __name__ == '__main__':
    manager.run()
Exemplo n.º 32
0
from flask.ext.script import Server, Manager, Shell

from example import app, db

manager = Manager(app)
manager.add_command('runserver', Server())
manager.add_command('shell', Shell(make_context=lambda: {
    'app': app,
    'db': db
}))

if __name__ == '__main__':
    manager.run()
Exemplo n.º 33
0
from app import app
from app import db
from app import models
from flask.ext.script import Manager
from flask.ext.script import Shell
from flask.ext.script import Server

manager=Manager(app)

def make_shell():
	return dict(app=app,db=db,message=models.Message)

manager.add_command('shell',Shell(make_context=make_shell))
manager.add_command('runserver',Server(
	use_debugger=True,
	use_reloader=True,
	host='localhost',
	port=5000
))

if __name__=='__main__':
	manager.run()
Exemplo n.º 34
0
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

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

manager = Manager(app)

# Turn on debugger by default and reloader
manager.add_command("runserver", Server())

if __name__ == "__main__":
    manager.run()
Exemplo n.º 35
0
#coding=UTF-8
from __future__ import absolute_import

from flask.ext.script import Manager, Server
from flask.ext.migrate import MigrateCommand

from cidadeiluminada import create_app
from cidadeiluminada.manage import manager as cidadeiluminada_manager

app = create_app()

manager = Manager(app)
manager.add_command('ci', cidadeiluminada_manager)
manager.add_command('db', MigrateCommand)
manager.add_command('runserver', Server())


@manager.command
def instance_path():
    from flask import current_app
    return current_app.instance_path


if __name__ == '__main__':
    manager.run()
Exemplo n.º 36
0
#!/usr/bin/env python

from flask.ext.script import Manager, Command
from flask.ext.migrate import MigrateCommand

from app import create_app
from tasks import run_celery
from tests.command import PytestCommand

manager = Manager(create_app)
manager.add_option('-c', '--config', dest='config_file', required=False)
manager.add_command('db', MigrateCommand)
manager.add_command('test', PytestCommand)
manager.add_command('runcelery', Command(run_celery))

if __name__ == '__main__':
    manager.run()
Exemplo n.º 37
0
import os
import glob
import subprocess
import urllib.parse
import multiprocessing

from flask import url_for
from flask.ext.script import Server
from flask.ext.script import Manager
from sqlalchemy import text as sqla_text

from webservices.rest import app, db
from webservices.config import SQL_CONFIG
from webservices.common.util import get_full_path

manager = Manager(app)

# The Flask app server should only be used for local testing, so we default to
# using debug mode and auto-reload. To disable debug mode locally, pass the
# --no-debug flag to `runserver`.
manager.add_command('runserver', Server(use_debugger=True, use_reloader=True))


def execute_sql_file(path):
    # This helper is typically used within a multiprocessing pool; create a new database
    # engine for each job.
    db.engine.dispose()
    print(('Running {}'.format(path)))
    with open(path) as fp:
        cmd = '\n'.join(
            [line for line in fp.readlines() if not line.startswith('--')])
Exemplo n.º 38
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)
Exemplo n.º 39
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()
Exemplo n.º 40
0
from flask.ext.script import Manager, Server
from pyweb import app

manager = Manager(app)

# 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()
Exemplo n.º 41
0
from flask import Flask, render_template, request, redirect, url_for, abort
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager
import datetime
import cloudinary.uploader

app = Flask(__name__)
app.config.from_object('punchstarter.default_settings')

db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)

from punchstarter.models import *


@app.route('/')
def hello():
    projects = db.session.query(Project).order_by(
        Project.time_created.desc()).limit(10)

    return render_template('index.html', projects=projects)


@app.route('/projects/create/', methods=['GET', 'POST'])
def create():
    if request.method == "GET":
        return render_template('create.html')
Exemplo n.º 42
0
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.assets import ManageAssets
from livereload import Server

from gather import create_app
from gather.extensions import db

app = create_app()
migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command("db", MigrateCommand)
manager.add_command("assets", ManageAssets())


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


@manager.command
def clear_cache():
    from gather.extensions import cache
    with app.app_context():
        cache.clear()


@manager.command
def livereload():
    db.create_all()
Exemplo n.º 43
0
Fabrice,Le Fessant,[email protected]
Mathieu,Lecarme,[email protected]
Jonathan,MERCIER,[email protected]
Bruno,Michel,[email protected]
Gael,Pasgrimaud,[email protected]
Julien,Pauli,[email protected]
Rodolphe,Quiédeville,[email protected]
Philippe,Robin,[email protected]
Frank,Rousseau,[email protected]
Romuald,Rozan,[email protected]
Michael,Scherer,[email protected]
Pierre,Schweitzer,[email protected]
Basile,Starynkevitch,[email protected]
Christophe,Villeneuve,[email protected]"""

manager = Manager(create_app)


@manager.shell
def make_shell_context():
    """
  Updates shell. (XXX: not sure what this does).
  """
    return dict(app=app, db=db)


@manager.command
def dump_routes():
    """
  Dump all the routes declared by the application.
  """
Exemplo n.º 44
0
# coding:utf-8
# !/usr/bin/env python

import os
from app import create_app, db
from app.models import User, Role
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand

# 先创建程序。如果已定义环境变量 LOTUS_CONFIG ,则读取配置名;否则默认配置。
app = create_app(os.getenv('LOTUS_CONFIG') or 'default')

# 初始化 Flask-Script、Flask-Migrate 和为 Python shell 定义的上下文
manager = Manager(app)
migrate = Migrate(app, db)


# fixme
def make_shell_context():
    return dict(app=app, db=db, User=User, Role=Role)


manager.add_command('shell', Shell(make_context=make_shell_context()))
manager.add_command('db', MigrateCommand)
print manager.command


# 启动单元测试命令 fixme
@manager.command
def test():
    '''run the unit tests '''
Exemplo n.º 45
0
import os

from flask.ext.script import Manager, Server

from narcissus.app import create_app
from narcissus.exts import db


app_root = os.path.dirname(os.path.abspath(__name__))

application = create_app('narcissus', os.path.join(app_root, 'development.conf'))
server = Server()
manager = Manager(application)
manager.add_command('runserver', server)


@manager.option('-c', dest='config', help='Config file',
                default='development.conf')
@manager.option('-d', dest='destroy', help='Destroy database', default=False)
def create_db(config, destroy):
    config_file = os.path.join(app_root, config)
    application.config.from_pyfile(config_file)
    with application.test_request_context():
        if destroy:
            db.drop_all()
        from narcissus.master.model import Tag
        from narcissus.album.model import Album, Image, Thumb
        db.create_all()
    print 'Created Database!'

Exemplo n.º 46
0
import subprocess

from flask.ext.script import Manager, Server

from . import app
from .freezer import freezer


manager = Manager(app, with_default_commands=False)

manager.add_command('run', Server(host="0.0.0.0"))


@manager.command
def freeze(serve=False):
    """Freezes the static version of the website."""
    if serve:
        freezer.run(debug=True)
    else:
        urls = freezer.freeze()
        print 'Built %i files.' % len(urls)


@manager.command
def up(destination):
    print '### Freezing'
    freeze()
    print '### Uploading to', destination
    subprocess.call(['rsync', '-Pah', '--del', freezer.root + '/', destination])

Exemplo n.º 47
0
import os

from flask.ext.script import Manager, Server
from flask.ext.script.commands import ShowUrls
from flask.ext.migrate import Migrate, MigrateCommand

from webapp import create_app
from webapp.models import db, User, Post, Tag, Comment

# default to dev config
env = os.environ.get('WEBAPP_ENV', 'dev')
app = create_app('webapp.config.%sConfig' % env.capitalize())

migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command("server", Server())
manager.add_command("show-urls", ShowUrls())
manager.add_command('db', MigrateCommand)


@manager.shell
def make_shell_context():
    return dict(app=app, db=db, User=User, Post=Post, Tag=Tag, Comment=Comment)


if __name__ == "__main__":
    manager.run()
Exemplo n.º 48
0
from flask.ext.script import Manager
from flask import Flask
import sqlite3
from flask import request, render_template, jsonify, make_response, send_file
import numpy as np
import json
import time
k = 2

app = Flask(__name__)
manager = Manager(app)


def get_db():
    db = sqlite3.connect('autoscaler_monitor.db')
    db.row_factory = sqlite3.Row
    return db


def query_db(query, args=(), one=False):
    db = get_db()
    cur = db.execute(query, args)
    db.commit()
    rv = cur.fetchall()
    db.close()
    return (rv[0] if rv else None) if one else rv


def get_log_db():
    db = sqlite3.connect('log.db')
    db.row_factory = sqlite3.Row
Exemplo n.º 49
0
from pmg import app
from pmg.models.soundcloud_track import SoundcloudTrack
from flask.ext.script import Server, Manager
from flask.ext.migrate import MigrateCommand

app.debug = True

manager = Manager(app)
manager.add_command('runserver', Server(port=5000, threaded=True))
manager.add_command('db', MigrateCommand)


@manager.command
def sync_soundcloud():
    SoundcloudTrack.sync()

if __name__ == '__main__':
    manager.run()
Exemplo n.º 50
0
import os
import datetime

from simplecoin import create_manage_app, db, currencies, powerpools, redis_conn
from simplecoin.scheduler import SchedulerCommand
from simplecoin.models import (Transaction, UserSettings, Credit, ShareSlice,
                               DeviceSlice, Block, CreditExchange)

from urlparse import urlparse
from flask import current_app, _request_ctx_stack
from flask.ext.migrate import stamp
from flask.ext.script import Manager, Shell, Server
from flask.ext.migrate import MigrateCommand


manager = Manager(create_manage_app)


@manager.option('-e', '--emit', help='prints the SQL that is executed',
                action="store_true")
def init_db(emit=False):
    """ Resets entire database to empty state """
    if emit:
        import logging
        logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

    res = raw_input("You shouldn't probably ever do this in production! Are you"
                    " really, really sure you want to reset the DB {}? [y/n] "
                    .format(db.engine))
    if res != "y":
        return
Exemplo n.º 51
0
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from config import SQLALCHEMY_DATABASE_URI
from run import application
from app.basemodels import db

migrate = Migrate(application, db)

manager = Manager(application)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()
Exemplo n.º 52
0
# -*- coding:utf-8 -*-
from flask.ext.script import Manager, Server
from app import app
from app import models

manager = Manager(app)


@manager.command
def save_todo():
    todo = models.Todo(content="My first todo")
    todo.save()


manager.add_command("runserver",
                    Server(host='127.0.0.1', port=5000, use_debugger=True))

if __name__ == "__main__":
    manager.run()
Exemplo n.º 53
0
# -*- coding: UTF-8 -*-
"""
Meieraha 2: Flask-Script manager script

See: http://flask-script.readthedocs.org/

Copyright 2015, Konstantin Tretyakov
License: MIT
"""
import logging, os, pkg_resources
from flask.ext.script import Manager
from meieraha2.app import create_app
from meieraha2.model import db, Dataset, MeieRahaVisualization, ConfigParameter

app = create_app()
manager = Manager(app)


@manager.shell
def shell_context():
    from meieraha2 import model
    return dict(app=app, model=model, db=model.db)


@manager.command
def runserver(log_config=None):
    'Launch a debug server.'
    if log_config is not None:
        logging.config.fileConfig(log_config)
    else:
        logging.basicConfig(level=logging.DEBUG)
Exemplo n.º 54
0
import os
import sys
from flask import current_app
from flask.ext.script import Manager,prompt,prompt_pass,\
        prompt_bool,prompt_choices
from flask.ext.script import Server
from werkzeug import generate_password_hash, check_password_hash

from motiky import configs
from motiky.configs import db
from motiky import create_app

from motiky.logic.models import CmsUser

app = create_app(configs.ProductionConfig)
manager = Manager(app)


@manager.command
def create_all():
    if prompt_bool("Are you sure? You will init your database"):
        db.create_all()


@manager.command
def drop_all():
    if prompt_bool("Are you sure? You will lose all your data!"):
        db.drop_all()


@manager.option('-u', '--username', dest='username', required=True)
Exemplo n.º 55
0
import os

from flask.ext.script import Manager, Server
from flask.ext.script.commands import ShowUrls, Clean
from flask.ext.migrate import Migrate, MigrateCommand

from app import create_app
from app.models import db

# default to dev config because no one should use this in
# production anyway
env = os.environ.get('APP_ENV', 'dev')
app = create_app('app.settings.%sConfig' % env.capitalize())

migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command("server", Server())
manager.add_command("show-urls", ShowUrls())
manager.add_command("clean", Clean())
manager.add_command("db", MigrateCommand)


@manager.command
def createdb():
    """ Creates a database with all of the tables defined in
        your SQLAlchemy models
    """

    db.create_all()

Exemplo n.º 56
0

class CreateDBCommand(Command):
    'Create DB and tables'

    def run(self, alembic_ini=None):
        if flask.current_app.config['SQLALCHEMY_DATABASE_URI'].startswith(
                'sqlite'):
            # strip sqlite:///
            datadir_name = os.path.dirname(
                flask.current_app.config['SQLALCHEMY_DATABASE_URI']
                [len('sqlite:///'):])
            if not os.path.exists(datadir_name):
                os.makedirs(datadir_name)
        db.create_all()


class DropDBCommand(Command):
    'Drop DB tables'

    def run(self):
        db.drop_all()


manager = Manager(app)
manager.add_command('create_db', CreateDBCommand())
manager.add_command('drop_db', DropDBCommand())

if __name__ == '__main__':
    manager.run()
Exemplo n.º 57
0
#local settings should be ignored by git
try:
    from local_settings import LocalConfig
except ImportError:
    LocalConfig = None


if os.environ.get("ENFERNO_ENV") == 'prod':
    app = create_app(ProdConfig)
elif LocalConfig :
    app = create_app(LocalConfig)
else:
    app = create_app(DevConfig)

manager = Manager(app)


def _make_context():
    """Return context dict for a shell session so you can access
    app  default.
    """
    return {'app': app}


manager.add_command('server', Server())
manager.add_command('shell', Shell(make_context=_make_context))

manager.add_command('create_user', CreateUserCommand())
manager.add_command('add_role', AddRoleCommand())
manager.add_command('remove_role', RemoveRoleCommand())
Exemplo n.º 58
0
""" use 'python manage.py run' command to run up application in development environment"""

import os
from flask.ext.script import Manager
from photophile import app
from photophile.database import session, User, Category, Base

manager = Manager(app)

@manager.command
def run():
    port = int(os.environ.get('PORT', 8080))
    app.run(host='0.0.0.0', port=port)

if __name__ == "__main__":
    manager.run()
    
    
    
   
Exemplo n.º 59
0
# -*- coding: utf-8 -*-
import subprocess
from flask.ext.script import Manager, Server
from appl import create_app

from appl.configs.development import DevelopmentConfig

app = create_app(DevelopmentConfig)
manager = Manager(app)

# ** The Flask-Script will override app.config['DEBUG']
_USE_DEBUGGER = app.debug

# Run local server
manager.add_command(
    "runserver", Server(host='localhost',
                        port=5000,
                        use_debugger=_USE_DEBUGGER))


@manager.command
def init():
    p = subprocess.call(['alembic', 'init', 'alembic'])


@manager.option('-t', '--tag', dest='tag', default='upgrade')
def db_rev(tag):
    p = subprocess.call(['alembic', 'revision', '--autogenerate', '-m', tag])


@manager.option('-r', '--revision', dest='rev', default='head')
Exemplo n.º 60
0
from flask.ext.script import Server, Manager, prompt_bool
# from myapp import app
from apps import app

manager = Manager(app)
manager.add_command("runserver", Server('0.0.0.0', port=5001))
app.run(host='0.0.0.0', port=5001, debug=True)

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