コード例 #1
0
def init_manager(application, port, extra_directories=()):

    manager = Manager(application)

    extra_files = list(get_extra_files(extra_directories))

    application.logger.info("Watching {} extra files".format(len(extra_files)))

    manager.add_command(
        "runserver",
        Server(port=port, extra_files=extra_files)
    )

    @manager.command
    def runprodserver():
        from waitress import serve
        serve(application, port=port)

    @manager.command
    def list_routes():
        """List URLs of all application routes."""
        for rule in sorted(manager.app.url_map.iter_rules(), key=lambda r: r.rule):
            print("{:10} {}".format(", ".join(rule.methods - set(['OPTIONS', 'HEAD'])), rule.rule))

    return manager
コード例 #2
0
ファイル: manage.py プロジェクト: kwin-wang/flask-learn
def init_manage(config_name):
    app = create_app(config_name or 'default')
    manager = Manager(app)
    migrate = Migrate(app, db)

    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)

    return manager
コード例 #3
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    Bootstrap(app)
    db = SQLAlchemy(app)
    migrate = Migrate(app, db)
    manager = Manager(app)
    manager.add_command('db', MigrateCommand)
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'login'
    return app, db, migrate, manager, login_manager
コード例 #4
0
ファイル: __init__.py プロジェクト: klen/flask-pw
    def manager(self):
        """Integrate a Flask-Script."""
        from flask_script import Manager, Command

        manager = Manager(usage="Migrate database.")
        manager.add_command('create', Command(self.cmd_create))
        manager.add_command('migrate', Command(self.cmd_migrate))
        manager.add_command('rollback', Command(self.cmd_rollback))
        manager.add_command('list', Command(self.cmd_list))
        manager.add_command('merge', Command(self.cmd_merge))

        return manager
コード例 #5
0
    def test_call_auto_env(self):
        """Regression test: Passing the environment to the ManageAssets command
        is optional, it can be auto-detected."""
        mgmt = Manager(self.app)
        mgmt.add_command('assets', ManageAssets())

        try:
            # Used to raise an error due to the env not being properly set.
            sys.argv = ['./manage.py', 'assets', 'build']
            mgmt.run()
        except SystemExit:
            # Always raised, regardless of success or failure of command
            pass
コード例 #6
0
ファイル: manager.py プロジェクト: mmalter/widukind-api
def main(create_app_func=None):
    
    if not create_app_func:
        from widukind_api.wsgi import create_app
        create_app_func = create_app
    
    class ServerWithGevent(Server):
        help = description = 'Runs the Flask development server with WSGI SocketIO Server'
    
        def __call__(self, app, host, port, use_debugger, use_reloader,
                   threaded, processes, passthrough_errors):

            if use_debugger:
                app = DebuggedApplication(app, evalex=True)
    
            server = WSGIServer((host, port), app)
            try:
                print('Listening on http://%s:%s' % (host, port))
                server.serve_forever()
            except KeyboardInterrupt:
                pass
    
    env_config = config_from_env('WIDUKIND_API_SETTINGS', 'widukind_api.settings.Prod')
    
    manager = Manager(create_app_func, 
                      with_default_commands=False)
    
    #TODO: option de config app pour désactiver run counter
    
    manager.add_option('-c', '--config',
                       dest="config",
                       default=env_config)

    manager.add_command("shell", Shell())

    if HAS_GEVENT:
        manager.add_command("server", ServerWithGevent(
                        host = '0.0.0.0',
                        port=8081)
        )
    else:
        manager.add_command("server", Server(
                        host = '0.0.0.0',
                        port=8081)
        )

    manager.add_command("config", ShowConfigCommand())
    manager.add_command("urls", ShowUrlsCommand())
    
    manager.run()
コード例 #7
0
ファイル: test_ext.py プロジェクト: chawk/flask-sitemap
    def test_pagination(self):
        self.app.config['SERVER_NAME'] = 'www.example.com'
        self.app.config['SITEMAP_INCLUDE_RULES_WITHOUT_PARAMS'] = True
        self.app.config['SITEMAP_MAX_URL_COUNT'] = 10
        sitemap = Sitemap(app=self.app)
        now = datetime.now().isoformat()

        @self.app.route('/')
        def index():
            pass

        @self.app.route('/first')
        def first():
            pass

        @self.app.route('/second')
        def second():
            pass

        @self.app.route('/<username>')
        def user(username):
            pass

        @sitemap.register_generator
        def user():
            for number in range(20):
                yield 'user', {'username': '******'.format(number)}

        directory = mkdtemp()
        manager = Manager(self.app)
        manager.add_command('sitemap', script.Sitemap())

        try:
            manager.handle('manage.py', ['sitemap', '-o', directory])

            with self.app.test_client() as c:
                data = c.get('/sitemap.xml').data
                data1 = c.get('/sitemap1.xml').data

                assert b('sitemapindex') in data
                assert len(data1) > 0

                with open(os.path.join(directory, 'sitemap.xml'), 'r') as f:
                    assert b(f.read()) == data

                with open(os.path.join(directory, 'sitemap1.xml'), 'r') as f:
                    assert b(f.read()) == data1
        finally:
            shutil.rmtree(directory)
コード例 #8
0
ファイル: test_noi1.py プロジェクト: GovLab/noi2
class EmailSendingTests(ViewTestCase):
    BASE_APP_CONFIG = ViewTestCase.BASE_APP_CONFIG.copy()

    BASE_APP_CONFIG.update(
        MAIL_USERNAME='******',
        NOI_DEPLOY='noi.org',
        SECURITY_EMAIL_SENDER='*****@*****.**',
        MAIL_SUPPRESS_SEND=True,
    )

    def setUp(self):
        super(EmailSendingTests, self).setUp()
        self.manager = Manager(self.app)
        self.manager.add_command('noi1', noi1.Noi1Command)
        self.mail = self.app.extensions.get('mail')

        noi1.set_users_from_json([SAMPLE_USER])
        self.user = noi1.add_user_to_db(SAMPLE_USER, password='******')
        db.session.commit()

        assert self.user.noi1_migration_info.email_sent_at is None

    def run_command(self, *args):
        self.manager.handle('', ['noi1'] + list(args))

    def test_send_all_migration_instructions_works(self):
        with self.mail.record_messages() as outbox:
            self.run_command('send_all_migration_instructions')
            self.assertEqual(len(outbox), 1)

        with self.mail.record_messages() as outbox:
            self.run_command('send_all_migration_instructions')
            self.assertEqual(len(outbox), 0)

    def test_send_migration_instructions_works(self):
        with self.mail.record_messages() as outbox:
            self.run_command('send_migration_instructions',
                             '*****@*****.**')
            self.assertEqual(len(outbox), 1)
            msg = outbox[0]
            self.assertEqual(msg.sender, '*****@*****.**')
            self.assertEqual(msg.recipients, ['*****@*****.**'])
            assert 'https://noi.org' in msg.body

            delta = (datetime.datetime.now() -
                     self.user.noi1_migration_info.email_sent_at)

            assert delta.total_seconds() < 60
コード例 #9
0
    def test_parse_templates(self):
        """Test the --parse-templates option.
        """
        # Create a file in the app's templates directory
        self.app.template_folder = self.path('templates')
        self.create_files({
            'templates/template.html': """
            {% assets "in", output="output" %}
                {{ ASSET_URL }}
            {% endassets %}
            """,
            'in': "foo"
        })

        # Run the build command with --parse-templates, which should pick
        # up the bundle we defined in above template.
        mgmt = Manager(self.app)
        mgmt.add_command('assets', ManageAssets(log=stdout_log))
        mgmt.handle('test', ['assets', '--parse-templates', 'build'])

        assert self.exists('output')
コード例 #10
0
    def test_call(self):
        # Setup the webassets.script with a mock main() function,
        # so we can check whether our call via Flask-Script actually
        # goes through.
        test_inst = self
        class DummyArgparseImplementation(GenericArgparseImplementation):
            def run_with_argv(self, argv):
                test_inst.last_script_call = argv
                return 0

        mgmt = Manager(self.app)
        mgmt.add_command('assets',
                ManageAssets(self.env, impl=DummyArgparseImplementation))

        try:
            # -h is a great test as that is something Flask-Script might
            # want to claim for itself.
            sys.argv = ['./manage.py', 'assets', '-h']
            mgmt.run()
        except SystemExit:
            # Always raised, regardless of success or failure of command
            pass
        assert self.last_script_call == ['-h']
コード例 #11
0
ファイル: manage.py プロジェクト: aavenel/ihatemoney
def main():
    app = create_app()
    Migrate(app, db)

    manager = Manager(app)
    manager.add_command('db', MigrateCommand)
    manager.add_command('generate_password_hash', GeneratePasswordHash)
    manager.add_command('generate-config', ConfigTemplate)
    manager.run()
コード例 #12
0
ファイル: manage.py プロジェクト: Glandos/ihatemoney
def main():
    QUIET_COMMANDS = ('generate_password_hash', 'generate-config')

    backup_stderr = sys.stderr
    # Hack to divert stderr for commands generating content to stdout
    # to avoid confusing the user
    if len(sys.argv) > 1 and sys.argv[1] in QUIET_COMMANDS:
        sys.stderr = open(os.devnull, 'w')

    app = create_app()
    Migrate(app, db)

    # Restore stderr (among other: to be able to display help)
    sys.stderr = backup_stderr

    manager = Manager(app)
    manager.add_command('db', MigrateCommand)
    manager.add_command('generate_password_hash', GeneratePasswordHash)
    manager.add_command('generate-config', GenerateConfig)
    manager.add_command('delete-project', DeleteProject)
    manager.run()
コード例 #13
0
ファイル: app.py プロジェクト: py-yyc/SocketioDemo
def create_app(configuration_file):
    """
    Create the app.

    :param configuration_file: Path of the configuration file to use for deployment settings
    :return: New application to use
    """
    # Setup the Flask app instance and configuration
    app = Flask(__name__)
    app.config.from_object(settings)  # Setup default settings
    app.config.from_pyfile(configuration_file, silent=True)  # Override with user settings -- and silence failures

    # Setup a little bit of console logging
    if app.config['DEBUG']:
        app.logger.setLevel(DEBUG)
    else:
        app.logger.setLevel(INFO)
        app.logger.addHandler(StreamHandler())

    manager = Manager(app)

    # Initialize the Socket.io Stream and bind it to the app instance (Only one stream per app at this time)
    async_mode = 'threading' if app.config['DEBUG'] else 'gevent'
    create_stream(app, resource='/api/v1/stream', async_mode=async_mode)

    # Add all Flask-Script manager commands
    manager.add_command('runserver', RunCommand)
    manager.add_command('clean', Clean)
    manager.add_command('urls', ShowUrls)

    # Create simple to use function on the app for starting commands
    # noinspection PyUnusedLocal
    def _cli(self):
        manager.run()
    # noinspection PyUnresolvedReferences
    app.cli = _cli.__get__(app, app.__class__)

    # Load all blueprints
    app.register_blueprint(api_blueprint, url_prefix='/api/v1')
    app.register_blueprint(ui_blueprint, url_prefix='')

    return app
コード例 #14
0
ファイル: cli.py プロジェクト: drivet/yawt
def create_manager(app=None):
    """Create the command line manager"""
    app_supplied = True
    if not app:
        app = create_app()
        app_supplied = False
    manager = Manager(app)

    server = Server(use_debugger=True, use_reloader=True)
    server.description = 'runs the yawt local server.'
    manager.add_command('runserver', server)
    manager.add_command('newsite', NewSite())
    manager.add_command('walk', Walk())

    if app_supplied:
        _handle_cli_init(manager)
    else:
        with app.test_request_context():
            _handle_cli_init(manager)

    return manager
コード例 #15
0
# -*- coding: utf-8 -*-
# Установка путей
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from flask_script import Manager, Server
from tumblelog import app
project = Manager(app)
project.add_command(
    "runserver", Server(use_debugger=True, use_reloader=True, host='0.0.0.0'))
if __name__ == "__main__":
    project.run()

コード例 #16
0
ファイル: run.py プロジェクト: lebroncc/flask_test
# coding=utf-8
import os
from flask_script import Manager, Command

from flask_test import create_app

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)


# flask_script自定义命令两种方式
# 使用add_command自定义 python run.py hello1
class Hello(Command):
    def run(self):
        print('hello world')


manager.add_command('hello1', Hello())


# 使用装饰器@manager.command自定义 python run.py hello2
@manager.command
def hello2():
    print("server is running")


if __name__ == '__main__':
    manager.run()
コード例 #17
0
ファイル: main.py プロジェクト: TuringFantasy/simple_dedupe
    """
    users = get_db_users()
    return jsonify(users), 200


@app.route('/user/<id_value>', methods=['GET'])
def get_user(id_value):
    """
    Return a given user by ID
    
    Params
    ---------
    id_value (int) : ID of user

    Returns
    ---------
    {
        "id": <id>
        "name": <name of user>
    }

    """
    users = get_db_users()
    correct_user = next(
        (item for item in users if str(item['id']) == id_value))
    return jsonify(correct_user), 200


if __name__ == '__main__':
    manager.add_command("runserver", GunicornServer())
    manager.run()
コード例 #18
0
ファイル: manage.py プロジェクト: trevorjamesmartin/drim_gam
from os import getenv as os_getenv
from os import path as os_path
from sys import path as sys_path

sys_path.append(os_path.abspath(os_path.join(os_path.dirname(__file__), '..')))


from flask_script import Manager, Server
from application import create_app


from common import SERVER_PORT, SERVER_IP


app = create_app()
manager = Manager(app)


manager.add_command("runserver", Server(
    use_debugger=True,
    use_reloader=True,
    host=os_getenv('IP', SERVER_IP),
    port=int(os_getenv('PORT', SERVER_PORT)))
)


if __name__ == "__main__":
    manager.run()
コード例 #19
0
ファイル: manage.py プロジェクト: Troywxx/Savras
from flask_script import Manager, Server
from flask_migrate import Migrate, MigrateCommand

from main import app, db, Task

migrate = Migrate(app, db)

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


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


if __name__ == '__main__':
    manager.run()
コード例 #20
0
from flask import Flask
from flask_script import Manager, Server

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

class CustomServer(Server):
    def __call__(self, app, *args, **kwargs):
        return Server.__call__(self, app, *args, **kwargs)

manager.add_command (
    "runserver",
    CustomServer(host = "0.0.0.0", use_reloader = False)
)

from ecg.database.ui import views
    SQLALCHEMY_ECHO = True


app.config.from_object(Config)

# 创建数据库SQLAlchemy工具对象: flask_sqlalchemy
db = SQLAlchemy(app)

# 创建数据库迁移工具对象: flask_migrate
# 第一个参数: Flask的实例, 第二个参数: SQLAlchemy数据库实例
migrate = Migrate(app, db)

# 创建脚本启动命令管理类对象: flask_script
manager = Manager(app)
# 向manager对象中添加数据库的操作命令
manager.add_command(
    'db', MigrateCommand)  # 此处db与数据库SQLAlchemy工具对象db不是一个意思,这个db只是操作命令的一个名字


# 定义数据库模型类
class User(db.Model):
    '''用户表'''
    __tablename__ = 'tbl_users'  # 定义数据库的表名,默认是以模型类名作为表名
    id = db.Column(db.Integer, primary_key=True)  # 整型的主键,默认会设置为自增主键
    name = db.Column(db.String(64), unique=True, index=True)
    email = db.Column(db.String(128), unique=True)
    password = db.Column(db.String(128))
    role_id = db.Column(db.Integer, db.ForeignKey('tbl_roles.id'))  # 表名的某个字段

    def __repr__(self):
        '''定义之后,可以先显示对象的时候更直观'''
        return 'User object: name = %s' % self.name
コード例 #22
0
]

BASE_DIR = os.path.abspath(os.path.dirname( __file__))  #guarda la ruta del directorio de mi aplicacion// donde estoy ubic

app = Flask(__name__)
app.url_map.strict_slashes = False
app.config['DEBUG'] = True
app.config['ENV'] = 'development'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(BASE_DIR, 'dev.db') #cual va ser la base de datos que voi a utilizar
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # EVITA QUE MI BASE DE DATOS GUARDE CAMBIOS INNECESARIOS CADA VEZ QUE HAGO UNA MODIFICACION A NIVEL DE TABLAS

db.init_app(app)
migrate = Migrate(app, db)#genera los comandos para crear la migracion.

manager = Manager(app)
manager.add_command('db', MigrateCommand)#ejecuta mis migraciones por consola
CORS(app) #evite que tenga problemas con el navegador,para que pueda utilizarse en manera de desarollo

@app.route("/todos", methods=["GET"])
def helloworld():
    if request.method =="GET":
        todos = Todo.get.all_todos()
        return jsonify(todos)

@app.route("/todos", methods=["POST"])
def addTodo():
    if request.method =="POST":
        todo.id = request.json.get("id")
        todo.label= request.json.get("label")
        todo.done = request.json.get("done")
コード例 #23
0
ファイル: manage.py プロジェクト: asamalik/cdic
        logging.getLogger("app.logic.build_logic").setLevel(logging.INFO)

        r = Runner(app)

        r.add_periodic_task("Reschedule build task", ctx_wrapper(reschedule_stall_builds), 200)
        r.add_periodic_task("Schedule dh status update task",
                            ctx_wrapper(schedule_dh_status_updates), 600)
        r.add_periodic_task("Reschedule failed dockerhub creation task",
                            ctx_wrapper(reschedule_dockerhub_creation), 600)

        all_async_tasks = [
            run_build_task,
            create_dockerhub_task,
            update_dockerhub_build_status_task,
        ]

        for task in all_async_tasks:
            r.add_on_demand_task(task)

        r.start()


manager.add_command("create_sqlite_file", CreateSqliteFileCommand())
manager.add_command("create_db", CreateDBCommand())
manager.add_command("drop_db", DropDBCommand())

manager.add_command("run_async_tasks", RunAsyncTasks())

if __name__ == '__main__':
    manager.run()
コード例 #24
0
ファイル: manager.py プロジェクト: axfFlask/axfFlask
from flask_migrate import MigrateCommand
from flask_script import Manager

from App import create_app

app = create_app("develop")

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

if __name__ == '__main__':
    manager.run()
コード例 #25
0
#!/usr/bin/env python
from flask_migrate import Migrate, MigrateCommand
from flask_script import Server, Manager

from api.app import create_app, db
from api.commands import GenerateApiSpecCommand

app = create_app(config_object='api.conf.DevelopmentConfig')
manager = Manager(app)

migrate = Migrate(app, db)

manager.add_command("runserver", Server())
manager.add_command('db', MigrateCommand)
manager.add_command('generate_swagger', GenerateApiSpecCommand)

if __name__ == "__main__":
    manager.run()
コード例 #26
0
        request_log = RequestLog()
        request_log.request_id = g.request_id
        request_log.ip = g.ip
        request_log.url = g.url
        request_log.time = g.time
        request_log.submitter = g.username
        request_log.status_num = res.status_code
        g.log_d['username'] = g.username
        g.log_d['status_code'] = res.status_code
        # current_app.logger.info(g.log_d)
        db.session.add(request_log)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
    return res


# @app.teardown_appcontext
# def shutdown_session(exception=None):
#     db.session.remove()
#     if exception and db.session.is_active:
#         db.session.rollback()

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

if __name__ == '__main__':
    manager.run()
コード例 #27
0
ファイル: manage_pc.py プロジェクト: zzfhncn/ApiTestManage
# gevent的猴子魔法
monkey.patch_all()

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)


def make_shell_context():
    return dict(
        app=app,
        db=db,
        User=User,
        ApiCase=ApiMsg,
    )


manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
manager.add_command('runserver',
                    Server(host='127.0.0.1',
                           port='8080'))  # host设置为本地地址后,局域网内的其他机子都可以访问

# manager.add_command('runserver', WSGIServer(('192.168.13.253', '8080'), app))

if __name__ == '__main__':
    # app.run(host='127.0.0.1', port=8080, debug=False)
    manager.run(default_command='runserver')
    # manager.run(default_command='shell')
コード例 #28
0
ファイル: manage.py プロジェクト: GDSRS/ideal-pancake
from flask_script import Manager, Server
from flask_migrate import Migrate, MigrateCommand
from application import create_app, get_db
from application.models import *

app = create_app(os.getenv('FLASK_CONFIG', 'default'))
db = get_db()
migrate = Migrate(app, db)
manager = Manager(app)


@manager.shell
def make_shell_context():
    return dict(app=app,
                db=db,
                User=User,
                Adm=Administrator,
                Con=Consumer,
                Bkt=Basket,
                Bkti=BasketItem,
                Ord=Order,
                Vegn=VegetableName,
                Veg=Vegetable,
                Ori=OrderItem)


manager.add_command('run', Server())
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()
コード例 #29
0
ファイル: manage.py プロジェクト: xjf8096/FlaskORM
from flask import Flask
from flask_script import Manager, Server
from flask_migrate import MigrateCommand

from app import create_app

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

manager.add_command('start', Server(host='127.0.0.1', port=9000))
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()
コード例 #30
0
ファイル: manage.py プロジェクト: opyate/gnashboard

def _make_context():
    """Return context dict for a shell session so you can access
    app, db and the Foo model by default.
    """
    return {
        'app': app,
        'db': db,
        'Foo': Foo,
        'Basket': Basket,
        'Page': Page,
        'KV': KV
    }


@manager.command
def test():
    """Run the tests."""
    import pytest
    exit_code = pytest.main([TEST_PATH, '--verbose'])
    return exit_code


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

if __name__ == '__main__':
    manager.run()
コード例 #31
0
ファイル: manage.py プロジェクト: vividhsv/cookiecutter-flask
else:
    app = create_app(DevConfig)

HERE = os.path.abspath(os.path.dirname(__file__))
TEST_PATH = os.path.join(HERE, 'tests')

manager = Manager(app)


def _make_context():
    """Return context dict for a shell session so you can access
    app, db, and the User model by default.
    """
    return {'app': app, 'db': db, 'User': User}


@manager.command
def test():
    """Run the tests."""
    import pytest
    exit_code = pytest.main([TEST_PATH, '--verbose'])
    return exit_code


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

if __name__ == '__main__':
    manager.run()
コード例 #32
0
ファイル: __init__.py プロジェクト: Teyras/JBToDo
import os
from flask import Flask, jsonify
from flask_script import Manager, Server
from flask_migrate import Migrate, MigrateCommand
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from .db import get_uri

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = get_uri()
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SECRET_KEY'] = '1234'

manager = Manager(app)

port = os.getenv('PORT', '5000')
manager.add_command('runserver', Server(host='0.0.0.0', port=int(port)))

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

Bootstrap(app)

from JBToDo.navigation import nav
nav.init_app(app)

import JBToDo.model
import JBToDo.views
コード例 #33
0
ファイル: manage.py プロジェクト: shroom24/sirius
from sirius.web import webapp
from sirius.fake import commands as fake_commands
from sirius.emulate import commands as emulate_commands
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand

app = webapp.create_app(os.getenv('FLASK_CONFIG', 'default'))
manager = Manager(app)
migrate = Migrate(app, webapp.db)


def make_shell_context():
    return dict(app=app, db=webapp.db)


manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
manager.add_command('fake', fake_commands.fake_manager)
manager.add_command('emulate', emulate_commands.manager)


@manager.command
def deploy():
    """Run deployment tasks."""
    from flask_migrate import upgrade

    # migrate database to latest revision
    upgrade()


if __name__ == '__main__':
コード例 #34
0
ファイル: i18n.py プロジェクト: MichelCordeiro/indico
        command.finalize_options()
        command.run()

    return _wrapper


cmd_list = ['init_catalog', 'extract_messages', 'update_catalog']
cmd_list += [cmd + '_js' for cmd in cmd_list]
cmd_list.append('compile_catalog')


for cmd_name in cmd_list:
    cmd_class = getattr(frontend, re.sub(r'_js$', '', cmd_name))

    command = Command(wrap_distutils_command(cmd_class))

    for opt, short_opt, description in cmd_class.user_options:

        long_opt_name = opt.rstrip('=')
        var_name = long_opt_name.replace('-', '_')
        opts = ['--' + long_opt_name]

        if short_opt:
            opts.append('-' + short_opt)

        command.add_option(Option(*opts, dest=var_name,
                                  action=(None if opt.endswith('=') else 'store_true'), help=description,
                                  default=DEFAULT_OPTIONS.get(cmd_name, {}).get(var_name)))

    IndicoI18nManager.add_command(cmd_name, command)
コード例 #35
0
from flask_script import Manager, Server
from app import create_app
from extensions.sql_alchemy import sqldb

import dbmodels.data_center.location as loc

manager = Manager(lambda config_filename, config_options: create_app(config_filename, config_options))
manager.add_option('-cf', '--configuration-file', dest='config_filename', default=None)
manager.add_option('-co', '--configuration-options', dest='config_options', default=None)

server = Server(port=5000, use_debugger=True, use_reloader=True)
manager.add_command("runserver", server)


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


@manager.command
def clear_db():
    sqldb.drop_all()


@manager.command
def init_db():
    sqldb.drop_all()
    sqldb.create_all()


@manager.command
コード例 #36
0
ファイル: manage.py プロジェクト: devops-life/flask-todo
#!/usr/bin/env python
# encoding: utf-8


"""
@author: chenzhangpeng
@contact: [email protected]
@site: http://www.qinqinbaby.com
@file: manage.py.py
@time: 16/6/8 下午2:26
"""

from flask_script import Manager,Server
from app import app
from app.models import Todo

manager = Manager(app)
manager.add_command("runserver",Server(host='0.0.0.0',port=5000))

# 测试mongodb连接
# @manager.command
# def save_todo():
#     todo = Todo(content="哈哈哈哈")
#     todo.save()

if __name__ == '__main__':
    manager.run()
コード例 #37
0
ファイル: manage.py プロジェクト: vonkarmen/fromzero_flask
import os
import sys

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from flask_script import Manager, Server
from flask_migrate import MigrateCommand
from flask_blog import app

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

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

if __name__ == '__main__':
    manager.run()
コード例 #38
0
ファイル: manage.py プロジェクト: xaratt/assetmanager
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from flask_script import Manager, Server
from assetmanager import create_app, loaddata


app = create_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",
    port = 8888)
)
manager.add_command("import", loaddata.RSS())

if __name__ == "__main__":
    manager.run()
コード例 #39
0
ファイル: test.py プロジェクト: Honfeil/pythonWeb
from flask_bootstrap import Bootstrap
from flask_script import Manager, Server
from flask_moment import Moment
from datetime import datetime
from Form import NameForm
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
# 跨站点请求伪造保护
app.config['SECRET_KEY'] = 'hard to guess string'
bootstrap = Bootstrap(app)
# 使用bootstrap
app.config['BOOTSTRAP_SERVE_LOCAL'] = True
# 使用管理(代码可在控制台运行)
manager = Manager(app)
manager.add_command("runserver",
                    Server(host="localhost", port=8888, use_debugger=True))
# 使用时间插件(便利而强大的时间功能)
moment = Moment(app)
# 设置数据库
basedir = os.path.abspath(os.path.dirname(__file__))
app.config[
    'SQLAlchemy_DATABASE_URI'] = 'mysql:\\\\' + 'root:root@localhost:3306/test'
app.config['SQLALchemy_COMMIT_ON_TEARDOWN'] = True
db = SQLAlchemy(app)

# mysql的url格式
# mysql://username:password@hostname/database


@app.route('/', methods=['get', 'post'])
def index():
コード例 #40
0
ファイル: manage.py プロジェクト: willingc/doc_dash
    def run(self, fix_imports):
        """Run command."""
        skip = ['requirements']
        root_files = glob('*.py')
        root_directories = [name for name in next(os.walk('.'))[1] if not name.startswith('.')]
        files_and_directories = [arg for arg in root_files + root_directories if arg not in skip]

        def execute_tool(description, *args):
            """Execute a checking tool with its arguments."""
            command_line = list(args) + files_and_directories
            print('{}: {}'.format(description, ' '.join(command_line)))
            rv = call(command_line)
            if rv is not 0:
                exit(rv)

        if fix_imports:
            execute_tool('Fixing import order', 'isort', '-rc')
        execute_tool('Checking code style', 'flake8')


manager.add_command('server', Server())
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('db', MigrateCommand)
manager.add_command('urls', ShowUrls())
manager.add_command('clean', Clean())
manager.add_command('lint', Lint())

if __name__ == '__main__':
    manager.run()
コード例 #41
0
# THIS FILE CREATES THE FLASK APP AND START SERVER

import os
from flask_script import Manager, Server
from flask_ci import CICommand

from application import create_app
import settings
import config

debug = config.DEBUG
host = os.getenv('IP', '0.0.0.0')
port = int(os.getenv('PORT', 8080))

app = create_app(debug)
manager = Manager(app)

manager.add_command("ci", CICommand(settings))
manager.add_command(
    "runserver",
    Server(use_debugger=debug, use_reloader=debug, host=host, port=port))

if __name__ == "__main__":
    manager.run()
コード例 #42
0

"""Define flask app creation in different environments."""
if os.getenv('TRAVIS'):
    app = create_app(os.environ.get('travis'))
elif sys.argv[0] == 'nosetests':
    app = create_app('testing')
else:
    app = create_app('default')

api = Api(app)

migrate = Migrate(app, db)

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

login_manager = LoginManager()
login_manager.init_app(app)


@login_manager.request_loader
def load_user(request):
    """Check authorization header and authenticate user for request.

    Authenticate user with provided token where the login_required
    decorator is used
    """
    token = request.headers.get('token')
    if token:
        s = Serializer(os.environ.get('SECRET_KEY'))
コード例 #43
0
app = create_app(os.getenv('FLASK_CONFIG') or 'default')

# 使用命令行选项来控制启动参数
manager = Manager(app)


def make_shell_context():
    """
    回调函数,在shell命令中自动执行某些操作(注册程序,数据库实例以及模型)
    :return:
    """
    return dict(app=app)


# 注册一个make_shell_context回调函数
manager.add_command("shell", Shell(make_context=make_shell_context))

app = Flask(__name__)

if __name__ == '__main__':
    # define some working threads
    threads = []

    # get jenkins build failure data
    t_build_failure = threading.Thread(target=get_jenkins_build_failure_data)
    threads.append(t_build_failure)

    t_testlink_info = threading.Thread(target=get_test_link_case_info)
    threads.append(t_testlink_info)

    t_zentao_info = threading.Thread(target=get_zentao_bug_info)
コード例 #44
0
ファイル: manage.py プロジェクト: wangshoujunnew/xiaoniu_cron
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
# ========================= 引入其他url模块
# 注册蓝图
app.register_blueprint(blueprint=helloworld1, url_prefix="/test_cron")
# =========================== end

manager = Manager(app)

migrate = Migrate(app, db)


def make_shell_context():
    return dict(app=app, JobLog=JobLog, CronInfos=CronInfos)


manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
manager.add_command(
    "runserver",
    Server("10.2.3.100", port=10080, threaded=True, use_debugger=False))
# manager 启动服务
# manager.add_command("runserver", Server("localhost", port=8080))


@manager.command
def test():
    """
    使用场景:创建一些敏感数据(如后台管理员),批量添加测试数据等等
    终端中操作指令 : python 文件名 方法名
    :return:
    """
コード例 #45
0
ファイル: manage.py プロジェクト: g4b1nagy/flask-boilerplate
#!/usr/bin/env python

from flask_assets import ManageAssets
from flask_script import Manager

from app import app, assets, db
from app.models import User


manager = Manager(app)
manager.add_command('assets', ManageAssets(assets))


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


@manager.command
def db_seed():
    user = User(
        first_name='Gabi',
        last_name='Nagy',
        email='*****@*****.**',
        picture_url='http://helpfulsheep.com/assets/helpful-sheep.png',
        social_id='facebook_12345',
        social_profile_url='http://helpfulsheep.com/',
    )
    db.session.add(user)
    db.session.commit()
コード例 #46
0
ファイル: manage.py プロジェクト: HassibIbrahim/PitchOnes
from app import create_app, db
from flask_script import Manager, Server
from app.models import User, Comment, Post
from flask_migrate import Migrate, MigrateCommand

# Creating app instance
app = create_app('development')

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


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


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


if __name__ == '__main__':
    manager.run()
コード例 #47
0
ファイル: manage.py プロジェクト: immanetize/copr
            CoprWhoosheer.insert_copr(writer, copr)
        writer.commit(optimize=True)


class GenerateRepoPackagesCommand(Command):
    """
    go through all coprs and create configuration rpm packages
    for them, if they don't already have it
    """

    def run(self):
        generate_repo_packages.main()


manager = Manager(app)
manager.add_command("test", TestCommand())
manager.add_command("create_sqlite_file", CreateSqliteFileCommand())
manager.add_command("create_db", CreateDBCommand())
manager.add_command("drop_db", DropDBCommand())
manager.add_command("create_chroot", CreateChrootCommand())
manager.add_command("alter_chroot", AlterChrootCommand())
manager.add_command("display_chroots", DisplayChrootsCommand())
manager.add_command("drop_chroot", DropChrootCommand())
manager.add_command("alter_user", AlterUserCommand())
manager.add_command("add_debug_user", AddDebugUserCommand())
manager.add_command("fail_build", FailBuildCommand())
manager.add_command("update_indexes", UpdateIndexesCommand())
manager.add_command("generate_repo_packages", GenerateRepoPackagesCommand())
manager.add_command("rawhide_to_release", RawhideToReleaseCommand())

if __name__ == "__main__":
コード例 #48
0
from flask_script import Manager, Shell, Server
from termcolor import colored

from app import app

manager = Manager(app)


def make_shell_context():
    return dict(app=app)


manager.add_command('runserver', Server())
manager.add_command('shell', Shell(make_context=make_shell_context))

if __name__ == '__main__':
    # manager.run(debug=True)
    manager.run()
コード例 #49
0
ファイル: manage.py プロジェクト: kernt/elasticsearch-HQ
        db.drop_all(app=app)


class PyTest(Command):
    """
    Runs all unittests. You MUST make sure that all clusters configured are running for the tests to pass!
    """

    def run(self):
        tests_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'tests')
        import pytest
        exit_code = pytest.main([tests_path, '--verbose'])
        return exit_code


manager.add_command("runserver", Server())
manager.add_command('clean-db', CleanDB)
manager.add_command('run-tests', PyTest)

"""
This draws on https://github.com/miguelgrinberg/Flask-Migrate

 To upgrade DB:
 1. python manage.py db migrate (GENERATE the migration scripts)
 2. python manage.py db upgrade (PERFORMS the update ddl)
"""
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()
コード例 #50
0
ファイル: manage.py プロジェクト: TakeMeHigher/flask_script
    """
    批量导入
    :param name:
    :param url:
    :return:
    """
    import xlrd
    from xlrd.book import Book
    from xlrd.sheet import Sheet
    from xlrd.sheet import Cell
    workbook = xlrd.open_workbook(path)
    sheet_names = workbook.sheet_names()
    # sheet = workbook.sheet_by_name('工作表1')
    sheet = workbook.sheet_by_index(0)

    # 循环Excel文件的所有行
    for row in sheet.get_rows():
        # print(row)
        # 循环一行的所有列
        for col in row:
            # 获取一个单元格中的值
            print(col.value, end=';')
        print('')


# 自定义命令
manager.add_command("runserver", Server())

if __name__ == "__main__":
    manager.run()
コード例 #51
0
ファイル: manage.py プロジェクト: taogeT/livetv_mining
def test(coverage=False):
    """Run the unit tests."""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    testresult = TextTestRunner(verbosity=2).run(TestLoader().discover('tests'))
    if cov:
        cov.stop()
        cov.save()
        print('Coverage Summary:')
        cov.report()
        covdir = app.config.get('COVERAGE_DIRECTORY', '')
        if covdir:
            covdir = os.path.join(covdir, datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S'))
            if not os.path.exists(covdir):
                os.makedirs(covdir)
            cov.html_report(directory=covdir)
            print('Coverage HTML version: file://{}/index.html'.format(covdir))
        cov.erase()
    if len(testresult.failures) + len(testresult.errors) > 0:
        sys.exit(1)


manager.add_command('shell', Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
manager.add_command('rungevent', GeventServer)


if __name__ == '__main__':
    manager.run()
コード例 #52
0
ファイル: manage.py プロジェクト: lsn1183/web_project
from flask_migrate import Migrate, MigrateCommand

from config import config
from app.db import db

app = Flask(__name__)
app.config.from_object(config['default'])
# cache.init_app(app)
db.app = app
db.init_app(app)
# from app.db import *
# import app.db
# db.create_all(app=app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)

# from app.db.doc import *
# from app.db.doc_tag_cat import *
# from app.db.doc_tags import *
# from app.db.ds_attach import *
# from app.db.ds_doc import *
# from app.db.ds_doc_checklist_item import *
# from app.db.ds_doc_if import *
# from app.db.ds_doc_template import *
# from app.db.ds_drbfm import *
# from app.db.ds_failure import *
# from app.db.ds_model_tag_rel import *
# from app.db.ds_rel_specification import *
# from app.db.ds_resource import *
# from app.db.ds_scene import *
コード例 #53
0
        for line in open('.env'):
            var = line.strip().split('=', 1)
            if len(var) == 2:
                os.environ[var[0]] = var[1]

import_env()
app = create_app(app_config)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
app.config['ZIMBRA_URL']='https://192.168.22.110:7071/service/admin/soap'
app.config['ZIMBRA_ADMIN']='*****@*****.**'
app.config['ZIMBRA_ADMIN_PASSWORD']='******'

manager = Manager(app)
test_manager = Manager(usage='Performs test related operations')

manager.add_command('db', db_manager)
manager.add_command('test', test_manager)
manager.add_command("routes", ShowUrls())

@manager.shell
def make_context_shell():
    """
    Usage: ./manage.py shell
    Starts a python shell with with app, db and models loaded
    """
    # Loads all the models which inherit from Base
    models_map = {name: cls for name, cls in models.__dict__.items() if isinstance(cls, type(Base))}
    return dict(app=app, db=db, **models_map)

@db_manager.option('--url', dest='url', type=parse_sqlalchemy_url,
                   default=app.config['SQLALCHEMY_DATABASE_URI'],
コード例 #54
0
#     tests = unittest.TestLoader().discover('tests')
#     unittest.TextTestRunner(versbosity=2).run(tests)
#
#
# if __name__ == '__main__':
#     manager.run()

#!/usr/bin/env python3.6
from app import create_app
from flask_script import Manager, Server

# Creating app instance
app = create_app('development')

manager = Manager(app)
manager.add_command('server', Server)


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


if __name__ == '__main__':
    manager.run()
コード例 #55
0
ファイル: manage.py プロジェクト: Jaza/flask-s3-save-example
sys.path.append(path.abspath(path.join(path.dirname(__file__), '..')))

from flask_script import Manager, Server
from flask_script.commands import InvalidCommand
from flask_migrate import MigrateCommand


def create_app(quiet=False):
    from project import app

    return app


manager = Manager(create_app)

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

manager.add_command('db', MigrateCommand)


from accounts.commands import *


if __name__ == "__main__":
    manager.run()
コード例 #56
0
app = Flask(__name__)
app.debug = True
app.use_reloader = True
app.static_folder = 'static'
app.config['SECRET_KEY'] = 'hardtoguessstring'
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get(
    'DATABASE_URL') or "postgresql://localhost/FRGAsi364final"
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['HEROKU_ON'] = os.environ.get('HEROKU')

# App addition setups
manager = Manager(app)
db = SQLAlchemy(app)  # For database use
migrate = Migrate(app, db)  # For database use/updating
manager.add_command('db', MigrateCommand)

# Login configurations setup
login_manager = LoginManager()
login_manager.session_protection = 'strong'  # might make the password stronger, not sure yet
login_manager.login_view = 'login'
login_manager.init_app(app)  # set up login manager


## Set up Shell context so it's easy to use the shell to debug
# Define function
def make_shell_context():
    return dict(app=app, db=db, User=User)


# Add function use to manager
コード例 #57
0
ファイル: manage.py プロジェクト: OmeGak/indico
def main():
    app = make_app(set_path=True)
    migrate.init_app(app, db, os.path.join(app.root_path, '..', 'migrations'))
    manager = Manager(app, with_default_commands=False)

    manager.add_command('shell', IndicoShell())
    manager.add_command('admin', IndicoAdminManager)
    manager.add_command('db', DatabaseManager)
    manager.add_command('plugindb', PluginDatabaseManager)
    manager.add_command('runserver', IndicoDevServer())
    manager.add_command('i18n', IndicoI18nManager)
    manager.add_command('celery', IndicoCeleryCommand)
    signals.plugin.cli.send(manager)

    try:
        manager.run()
    except KeyboardInterrupt:
        print
        sys.exit(1)
コード例 #58
0
article1 = Article.query.first()

sheet1 = Sheet.query.first()
sheet1.policy + ' on ' + sheet1.target
sheet1.contributor.append(yann)
db.session.commit()

# Flask migrate part
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand

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

manager.add_command('db', MigrateCommand)

if __name__ == 'main':
    manager.run()

article0 = Article.query.first()
article_db = Article.query.get_or_404(article1.id)
authors = [{'firstname': author.name, 'surname':author.surname, 'email':author.email} for author in article_db.author]

author = article_db.author[0]

zip(["firstname","surname","email"], author1)

{print(zip(["firstname","surname","email"], author)) for author in article_db.author}

article1 = Article.query.filter_by(title = 'Test du 6 janvier').first()

for author in article1.author:
コード例 #59
0
ファイル: Flasko.py プロジェクト: lambdaplus/flasko
class LoginForm(Form):
    email = StringField('Email', validators=[DataRequired(),
                                             Length(1, 64),
                                             Email()])
    #username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField('Keep me logged in')
    submit = SubmitField('Log In')


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)


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        user = User(email=form.email.data,
                    username=form.username.data,
                    password=form.password.data)
コード例 #60
0
ファイル: manager.py プロジェクト: vividhsv/MarathonMR
    app = create_app(ProdConfig)
else:
    app = create_app(DevConfig)

HERE = os.path.abspath(os.path.dirname(__file__))
TEST_PATH = os.path.join(HERE, 'tests')

manager = Manager(app)


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


@manager.command
def test():
    import pytest
    exit_code = pytest.main([TEST_PATH, '--verbose'])
    return exit_code


manager.add_command('server', Server(port=1234))
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('urls', ShowUrls())

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

# To run coverage
# py.test --cov=MarathonMR tests/