示例#1
0
def parser_artist(artist_id):
    create_app()
    process = Process.get_or_create(id=artist_id)
    if process.is_success:
        return

    print 'Starting fetch artist: {}'.format(artist_id)
    start = time.time()
    process = Process.get_or_create(id=artist_id)

    tree = get_tree(ARTIST_URL.format(artist_id))

    artist = Artist.objects.filter(id=artist_id)
    if not artist:
        artist_name = tree.xpath('//h2[@id="artist-name"]/text()')[0]
        picture = tree.xpath(
            '//div[contains(@class, "n-artist")]//img/@src')[0]
        artist = Artist(id=artist_id, name=artist_name, picture=picture)
        artist.save()
    else:
        artist = artist[0]
    song_items = tree.xpath('//div[@id="artist-top50"]//ul/li/a/@href')
    songs = []
    for item in song_items:
        song_id = item.split('=')[1]
        song = parser_song(song_id, artist)
        if song is not None:
            songs.append(song)
    artist.songs = songs
    artist.save()
    process.make_succeed()
    print 'Finished fetch artist: {} Cost: {}'.format(
        artist_id, time.time() - start)
def test_create_app():
    try:
        create_app()
    except SystemExit:
        # Clean git repository doesn't have `local_config.py`, so it is fine
        # if we get SystemExit error.
        pass
def run(
        context,
        host='127.0.0.1',
        port=5000,
        development=True,
        install_dependencies=True,
        upgrade_db=True
    ):
    """
    Run DDOTS RESTful API Server.
    """
    if install_dependencies:
        context.invoke_execute(context, 'app.dependencies.install')
    if upgrade_db:
        context.invoke_execute(context, 'app.db.upgrade')
        if development:
            context.invoke_execute(
                context,
                'app.db.init_development_data',
                upgrade_db=False,
                skip_on_failure=True
            )

    from app import create_app
    create_app(
        flask_config='development' if development else 'production'
    ).run(
        host=host,
        port=port
    )
def test_create_app_passing_FLASK_CONFIG_env(monkeypatch, flask_config_name):
    monkeypatch.setenv('FLASK_CONFIG', flask_config_name)
    if flask_config_name == 'production':
        from config import ProductionConfig
        monkeypatch.setattr(ProductionConfig, 'SQLALCHEMY_DATABASE_URI', 'sqlite://')
        monkeypatch.setattr(ProductionConfig, 'SECRET_KEY', 'secret')
    create_app()
示例#5
0
文件: base.py 项目: Howon/eventum
 def setUpClass(self):
     """ Sets up a test database before each set of tests """
     create_app(
         MONGODB_SETTINGS={'DB': 'testing'},
         TESTING=True,
         CSRF_ENABLED=False,
         WTF_CSRF_ENABLED=False
     )
     from app import app
     self.app = app
示例#6
0
    def test_create_app(self):
        self.test_app = create_app("testing")
        self.test_app_context = self.test_app.app_context()
        self.test_app_context.push()
        self.test_client = self.test_app.test_client()
        self.test_app_context.pop()

        self.dev_app = create_app("development")
        self.dev_app_context = self.dev_app.app_context()
        self.dev_app_context.push()
        self.dev_client = self.dev_app.test_client()
        self.dev_app_context.pop()
示例#7
0
 def decorated_function(*args, **kwargs):
     """
     エラーをログファイルに記録する
     """
     try:
         r = f(*args, **kwargs)
         return r
     except Exception as e:
         from app import create_app
         create_app().logger.critical(datetime.datetime.now())
         create_app().logger.critical(traceback.format_exc())
         raise e
 def setUp(self):
     app = create_app('testing')
     self.app = app
     self.ctx = app.app_context()
     self.ctx.push()
     self.client = app.test_client()
     db.create_all()
 def stamp(context, directory='migrations', revision='head', sql=False, tag=None):
     """'stamp' the revision table with the given revision; don't run any
     migrations"""
     from app import create_app
     with create_app().app_context():
         config = _get_config(directory)
         command.stamp(config, revision, sql=sql, tag=tag)
示例#10
0
 def setUp(self):
     self.app = create_app('testing')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
     Role.insert_roles()
     self.client = self.app.test_client()
示例#11
0
    def setUp(self):
        """
            Initialize the test cases.
        """
        self.app = create_app(TestConfiguration)
        self.client = self.app.test_client()
        self.app_context = self.app.app_context()
        self.app_context.push()
        self.request_context = self.app.test_request_context('/')
        self.request_context.push()
        db.create_all()

        # Add a few test models.
        role_1 = Role(name='A')
        role_2 = Role(name='B')
        role_3 = Role(name='C')
        role_4 = Role(name='D')
        role_5 = Role(name='E')
        role_6 = Role(name='F')
        role_7 = Role(name='G')
        db.session.add(role_1)
        db.session.add(role_2)
        db.session.add(role_3)
        db.session.add(role_4)
        db.session.add(role_5)
        db.session.add(role_6)
        db.session.add(role_7)
        db.session.commit()
示例#12
0
	def setUpClass(cls):
		#start Firefox
		try:
			cls.client = webdriver.Firefox()
		except:
			pass

		if cls.client:
			#create the application
			cls.app = create_app('testing')
			cls.app_context = cls.app.app_context()
			cls.app_context.push()

			#suppress logging to keep unitteset output clean
			import logging
			logger = logging.getLogger('werkzeug')
			logger.setLevel("ERROR")

			#create database with fake user and post
			db.create_all()

			u = User(username='******', password='******', role=1)
			db.session.add(u)

			p = Post(title='test_post', body='test_post_body', user_id=u.id)
			db.session.add(p)
			db.session.commit()

			#start the Flask server in a thread
        	threading.Thread(target=cls.app.run).start()
示例#13
0
    def setUpClass(cls):
        try:
            cls.client = webdriver.Firefox()
        except:
            pass

        if cls.client:
            cls.app = create_app('testing')
            cls.app_context = cls.app_context()
            cls.app_context.push()

            import logging
            logger = logging.getLogger('werkzeug')
            logger.setLevel("ERROR")

            db.create_all()
            Role.insert_roles()
            User.generate_fake(10)
            Post.generate_fake(10)

            admin_role = Role.query.filter_by(permissions=0xff).first()
            admin = User(email='*****@*****.**',
                         username='******', password='******',
                         role=admin_role, confirmed=True)
            db.session.add(admin)
            db.session.commit()

            threading.Thread(target=cls.app.run).start()
            time.sleep(1)
def teardown():
    app = create_app('test')
    with app.app_context():
        db.session.remove()
        db.drop_all()
        db.engine.execute("drop table alembic_version")
        db.get_engine(app).dispose()
示例#15
0
    def setUp(self):
        """
            Initialize the test cases.
        """
        self.app = create_app(TestConfiguration)
        self.app_context = self.app.app_context()
        self.app_context.push()
        self.request_context = self.app.test_request_context('/')
        self.request_context.push()
        db.create_all()

        # Add a few test models.
        self.model_1 = TestModel()
        self.model_2 = TestModel()
        self.model_3 = TestModel()
        self.model_4 = TestModel()
        self.model_5 = TestModel()
        self.model_6 = TestModel()
        self.model_7 = TestModel()
        db.session.add(self.model_1)
        db.session.add(self.model_2)
        db.session.add(self.model_3)
        db.session.add(self.model_4)
        db.session.add(self.model_5)
        db.session.add(self.model_6)
        db.session.add(self.model_7)
        db.session.commit()
示例#16
0
 def setUp(self):
     self.app = create_app(AuthTestConfig)
     self.app_context = self.app.test_request_context()
     self.app_context.push()
     db.app = self.app
     db.create_all()
     self.client = self.app.test_client(use_cookies=True)
    def setUp(self):
        # Use an in memory database
        settings.EQ_SERVER_SIDE_STORAGE_TYPE = "DATABASE"
        settings.EQ_SERVER_SIDE_STORAGE_DATABASE_URL = "sqlite://"

        self.application = create_app('development')
        self.client = self.application.test_client()
示例#18
0
文件: base.py 项目: imhuwq/imhuwq
    def setUpClass(cls):
        try:
            cls.client = webdriver.Chrome(executable_path=chrome_driver)
        except:
            pass

        if cls.client:
            # 创建 app
            cls.app = create_app('test')
            cls.app_context = cls.app.app_context()
            cls.app_context.push()

            # 建立数据库
            db.create_all()
            setting = Settings(
                site_admin_email='*****@*****.**',
                site_initiated=True,
            )
            db.session.add(setting)
            db.session.commit()

            user = User(
                name='test_user',
                password='******',
                email='*****@*****.**'
            )
            db.session.add(user)
            db.session.commit()

            cls.host = 'http://localhost:5000'

            import logging
            logger = logging.getLogger('werkzeug')
            logger.setLevel("ERROR")
            threading.Thread(target=cls.app.run).start()
示例#19
0
    def setUpClass(cls):
        # 启动Firefox
        try:
            cls.client = webdriver.Firefox()
        except:
            pass

        # 如果无法启动浏览器,则跳过这些测试
        if cls.client:
            # 创建程序
            cls.app = create_app('testing')
            cls.app_context = cls.app.app_context()
            cls.app_context.push()

            # 禁止日志,保持输出简洁
            import logging
            logger = logging.getLogger('werkzeug')
            logger.setLevel("ERROR")

            # 创建数据库
            db.create_all()
            Role.insert_role()

            # 添加管理员
            admin_role = Role.query.filter_by(permission=0xff).first()
            admin = User(email='*****@*****.**',
                         username='******', pasword='cat',
                         role=admin_role, confirmed=True)
            db.session.add(admin)
            db.session.commit()

            # 在一个线程中启动Flask服务器
            threading.Thread(target=cls.app.run).start()
 def setUpClass(cls):
     try:
         cls.client = webdriver.Firefox()
     except:
         pass
     if cls.client:
         # create app
         cls.app = create_app('testing')
         cls.app_context = cls.app.app_context()
         cls.app_context.push()
         # create log
         import logging
         logger = logging.getLogger('werkzeug')
         logger.setLevel(logging.ERROR)
         # create database
         db.create_all()
         Role.init_roles()
         User.generate_fake(count=10)
         Post.generate_fake(count=10)
         # add admin
         admin_role = Role.query.filter_by(permissions=0xff).first()
         admin = User(email='*****@*****.**', username='******',
                      password='******', role=admin_role, confirmed=True)
         db.session.add(admin)
         db.session.commit()
         # run server in child thread
         Thread(target=cls.app.run).start()
示例#21
0
def enter(context, install_dependencies=True, upgrade_db=True):
    """
    Enter into IPython notebook shell with an initialized app.
    """
    if install_dependencies:
        context.invoke_execute(context, 'app.dependencies.install')
    if upgrade_db:
        context.invoke_execute(context, 'app.db.upgrade')
 
    import pprint
    import logging

    from werkzeug import script
    import flask

    import app
    flask_app = app.create_app()

    def shell_context():
        context = dict(pprint=pprint.pprint)
        context.update(vars(flask))
        context.update(vars(app))
        return context

    with flask_app.app_context():
        script.make_shell(shell_context, use_ipython=True)()
示例#22
0
 def setUp(self):
               self.app = create_app('testing')
               self.app_context = self.app.app_context()
               self.app_context.push()
               db.create_all()
               Role.insert_roles()
               self.client = self.app.test_client(use_cookies=True) #测试客户端对象 (启用cookie像浏览器一样可能接收和发半发送cookie)
示例#23
0
 def setUp(self):
     self.app = create_app("testing")
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
     Role.insert_roles()
     self.client = self.app.test_client(use_cookies=True)
示例#24
0
    def setUp(self):
        self.app = create_app('testing')

        self.app_context = self.app.app_context()
        self.app_context.push()

        db.create_all()
示例#25
0
	def setUpClass(cls):
		#launch Firefox
		try:
			cls.client = webdriver.Chrome()
		except:
			pass

		if cls.client:
			cls.app = create_app('testing')
			cls.app_context = cls.app.app_context()
			cls.app_context.push()

			import logging
			logger = logging.getLogger('werkzeug')
			logger.setLevel('ERROR')

			# create database, and fill it up with some faked data
			db.create_all()
			Role.insert_roles()
			User.generate_fake(10)
			Post.generate_fake(10)

			# add administrater
			admin_role = Role.query.filter_by(permissions=0xff).first()
			admin = User(email='*****@*****.**',
						 username='******', password='******',
						 role=admin_role, confirmed=True)
			db.session.add(admin)
			db.session.commit()

			# launch Flask server in a thread
			threading.Thread(target=cls.app.run).start()

			# give the server a second to ensure it is up
			time.sleep(1)
def search_results(query):
    app = create_app('test')
    test_client = app.test_client()
    setup_authorization(app)

    response = test_client.get('/index-to-create/services/search?%s' % query)
    return json.loads(response.get_data())
示例#27
0
 def create_app(self):
     '''Create the wsgi application'''
     app_ = app.create_app()
     db.session = mock.Mock()
     one = db.session.query.return_value.filter.return_value.one
     one.return_value = Exception()
     return app_
    def create_app(self):
        """
        Create the wsgi application for flask

        :return: application instance
        """
        return app.create_app(config_type='TEST')
示例#29
0
    def setUp(self):
        self.app = create_app('testing')

        self.app_context = self.app.app_context()
        self.app_context.push()

        self.test_client = self.app.test_client()
 def setUp(self):
     self.app = create_app('testing')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
     self.client = self.app.test_client()
     self.url = api.url_for(RegisterResource)
示例#31
0
"""Database migration and upgrade manager."""

from flask_migrate import Migrate
from flask_migrate import MigrateCommand
from flask_script import Manager

from app import config
from app import create_app
from app import db

app = create_app(config.set_config())
app.app_context().push()

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

manager.add_command("db", MigrateCommand)

if __name__ == "__main__":
    manager.run()
示例#32
0
 def setUp(self):
     self.app = create_app(TestConfig)
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
示例#33
0
import os
from app import create_app

app = create_app('config')

if __name__ == '__main__':
    app.run(host=app.config['HOST'],
            port=app.config['PORT'],
            debug=app.config['DEBUG'])
示例#35
0
"""
server.py: Run Flask server with Deep Learning model.
"""

__author__      = "alvertogit"
__copyright__   = "Copyright 2018-2020"


import os

from app import create_app

app = create_app(os.environ.get("FLASK_ENV"))

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)
示例#36
0
#!/usr/bin/env python
# before use SET PYTHONPATH=<project_path>
# TODO: https://flask.palletsprojects.com/en/1.1.x/cli/#custom-scripts
import sys
from app.views.renders import render_cut_filepath
from render_worker import tasks
from flask import url_for
from app import create_app
from app.models import Render

app = create_app(debug=True)

render_id = sys.argv[1]

render = Render.query.filter(Render.id == render_id).one()
print("Queueing this render: ", render)

with app.app_context():
    demo_url = url_for('static',
                       filename=render_cut_filepath(render.gtv_match_id,
                                                    render.map_number,
                                                    render.client_num,
                                                    render.start, render.end))

print("Cut demo url:", demo_url)
# exit()

tasks.render.send(render.id, demo_url, render.start, render.end)
示例#37
0
import eventlet
eventlet.monkey_patch()
# from app import create_app, socketio
#
# app = create_app(debug=True)
#
# if __name__ == '__main__':
#     socketio.run(app)

from app import create_app, socketio

app = create_app(debug=False)

if __name__ == '__main__':
    socketio.run(app, host="127.0.0.1", port="3002")
示例#38
0
from os import getenv
from app import create_app
from app.models import Area, Comment, Concept, Country, Document, DocumentType, Index, Region, \
    Role, State, Travel, User, Workflow, db

app = create_app(getenv('FLASK_CONFIG') or 'default')


@app.shell_context_processor
def make_shell_context():
    return dict(app=app, Area=Area, Comment=Comment, Concept=Concept, Country=Country, \
                Document=Document, DocumentType=DocumentType, Index=Index, Region=Region, \
                Role=Role, State=State, Travel=Travel, User=User, Workflow=Workflow, db=db)


@app.cli.command()
def init():
    insert(Area)
    insert(Concept)
    insert(Country)
    insert(DocumentType)
    insert(Role)
    insert(User)
    insert(State)
    insert(Travel)
    insert(Document)


def insert(model):
    print(f'Inserting table {model.__tablename__} ...')
    model.insert()
示例#39
0
from app import create_app, db
from flask_script import Manager,Server
from app.models import Role ,PostCategory, Comment, BlogPost,Subscriber,Admin
from  flask_migrate import Migrate, MigrateCommand

 
app = create_app('development')  


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

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

@manager.shell
def make_shell_context():
    return dict(app = app,db = db,Admin = Admin, BlogPost = BlogPost, Role = Role, Comment = Comment,Subscriber= Subscriber,PostCategory=PostCategory ) 

if __name__ == '__main__':
    manager.run()
示例#40
0
 def setUp(self):
     self.app = create_app(config="testing")
     self.client = self.app.test_client()
     self.app_context = self.app.app_context()
示例#41
0
# coding: utf-8

import os
from app import create_app, db
from app.models import User, Role
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand

app = create_app(os.getenv('CHENGSITE_ENV') or 'DevConfig')

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)

if __name__ == '__main__':
    manager.run()
示例#42
0
# _*_ coding: utf-8 _*_
"""
  Created by Alimazing on 2018/5/12.
"""
from werkzeug.exceptions import HTTPException
from flask_script import Manager, Command, Server

from app import create_app
from app.libs.error import APIException
from app.libs.error_code import ServerError

__author__ = 'Alimazing'

app = create_app()


@app.errorhandler(Exception)
def framework_error(e):
    if isinstance(e, APIException):
        return e
    elif isinstance(e, HTTPException):
        code = e.code
        msg = e.description
        error_code = 1007
        return APIException(code, error_code, msg)
    else:
        if not app.config['DEBUG']:
            return ServerError()
        else:
            raise e
示例#43
0
文件: manage.py 项目: ASaiun/ui_demo
# -*- coding: utf-8 -*-
from flask import request
from app import create_app
from flask_script import Manager

app = create_app('debug')
print app.config


def before_request():
    app.jinja_env.cache = {}


app.before_request(before_request)

manager = Manager(app)


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


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

# from flask import Flask
# app = Flask(__name__)

# @app.route('/')
示例#44
0
import os

from kubeflow.kubeflow.crud_backend import config, logging
import app

log = logging.getLogger(__name__)

APP_NAME = os.environ.get("APP_NAME", "Tensorboard Web App")
BACKEND_MODE = os.environ.get("BACKEND_MODE", "prod")  # 'prod' or 'dev'

# Load the Dev config based on BACKEND_MODE env var
if BACKEND_MODE == "dev":
    cfg = config.DevConfig
else:
    cfg = config.Config

_app = app.create_app(name=APP_NAME, config_class=cfg)

if __name__ == "__main__":
    _app.run()
示例#45
0
文件: run.py 项目: shri73/blog_api
import os
from app import create_app

if __name__ == '__main__':
    # Get flask env 'development' from env
    env_name = os.getenv("FLASK_ENV")
    app = create_app(env_name)
    app.run()
示例#46
0
 def setUp(self):
     self.app = create_app('testing')
     self.app_context = self.app.app_context()
     self.app_context.push()
示例#47
0
 def setUp(self):
     self.app = create_app('testing')
     self.app_context = self.app.app_context()
     self.app_context.push()
     self.client = self.app.test_client(use_cookies=True)
示例#48
0
#!/usr/bin/env python

from app import create_app, db
from app.models import User, Role, Permission
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand

app = create_app('default')
manager = Manager(app)
migrate = Migrate(app, db)


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


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

if __name__ == '__main__':
    manager.run()
示例#49
0
#start position
import os
from app import create_app, db
from app.models import User, Role
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand

app = create_app(os.environ.get('FLASK_CONFIG') 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)


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


if __name__ == '__main__':
    manager.run()
示例#50
0
import os
from app import create_app, db
from app.models import User, Role
from flask_migrate import Migrate

app = create_app(os.getenv('FLASKY_CONFIG') or 'default')
migrate = Migrate(app, db)


@app.shell_context_processor
def make_shell_context():
    return dict(db=db, User=User, Role=Role)


@app.cli.command()
def test():
    """Run the unit tests."""
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
示例#51
0
from app import create_app

application = create_app()
示例#52
0
 def create_app(self):
     return create_app(self)
示例#53
0
import os
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import create_app, db

config_name = os.environ.get('APP_SETTINGS')
app = create_app(config_name)
manager = Manager(app)

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

# add db command

if __name__ == "__main__":
    manager.run()
示例#54
0
import os

from flask import jsonify

from config import config
from app import create_app

flask_env = os.getenv('FLASK_ENV', 'production')
app = create_app(config=config[flask_env])


@app.route('/')
def status():
    return jsonify({
        'status': 'success',
        'message': 'up and running'
    })


if __name__ == "__main__":
    app.run()
示例#55
0
 def setUp(self):
     self.app = create_app("testing")
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
示例#56
0
from app import create_app, db
from flask_script import Manager, Server
from flask_migrate import Migrate, MigrateCommand
from app.models import User, Role

app = create_app("development")

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

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

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

if __name__ == "__main__":
    manager.run()
 def setUp(self):
     self.app = app.create_app()
     self.app.testing = True
     self.app = self.app.test_client(self)
示例#58
0
 def create_app(self):
     return biu.create_app('testing')
示例#59
0
 def setUp(self):
     self.app = TestClient(create_app("testing"))
示例#60
0
import os
from flask_script import Manager  # class for handling a set of commands
from flask_migrate import Migrate, MigrateCommand
from app import db, create_app
from app import models
from app.models import Pizza

app = create_app(config_name=os.environ.get('APP_SETTINGS'))
migrate = Migrate(app, db)
manager = Manager(app)


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


manager.add_command('db', MigrateCommand)

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