示例#1
0
文件: admin.py 项目: kankje/blog
def install():
    if db.engine.dialect.has_table(db.engine.connect(), 'settings'):
        return redirect(url_for('regular.index'))

    g.settings = {
        'blog_name': 'Installation',
        'blog_description': ''
    }
    form = InstallForm()
    error = None

    if form.validate_on_submit():
        try:
            db.create_all()

            salt = crypt.generate_salt()
            db.session.add(Settings(
                username=form.username.data,
                password=crypt.hash_password(form.password.data, salt),
                salt=salt,
                blog_name=form.blog_name.data,
                blog_description=form.blog_description.data,
                blog_author=form.blog_author.data
            ))
            db.session.commit()

            return redirect(url_for('regular.index'))
        except SQLAlchemyError as exc:
            db.session.rollback()
            error = str(exc)

    return render_template('admin/install.jinja2', form=form, error=error)
示例#2
0
    def setUp(self):
        global data

        with open('names.json') as data_file:
            data = json.load(data_file)

        print("Using host: " + HOST)
        db.create_all()
示例#3
0
def setup_module(module):
    """ setup any state specific to the execution of the given module."""

    from app.models import db
    db.create_all()

    from app.corpus.models import db as corpus_db
    corpus_db.create_all()
示例#4
0
 def setUp(self):
     self.app = create_app()
     from app.server import login, show_all_posts
     self.app.add_url_rule('/', 'login', login)
     self.app.add_url_rule('/home', 'show_all_posts', show_all_posts)
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
     self.client = self.app.test_client(use_cookies=True)
 def setUp(self):
     self.app = Setup.create_app()
     app.config['TESTING'] = True
     app.secret_key = 'super secret key'
     app.config['PROFILE'] = True
     app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])
     with app.test_request_context():
         db.create_all()
         populate()
 def setUp(self):
     bucket_app = create_app('instance.config.TestingConfig')
     self.user = {'username': '******', 'password': '******'}
     self.app = bucket_app
     self.client = self.app.test_client
     with bucket_app.app_context():
         db.create_all()
         user = User(**self.user)
         user.save()
def createdb(testdata=True):
    """Initializes the database """
    app = create_app()
    with app.app_context():
        db.drop_all()
        db.create_all()
        if testdata:
            user = User(username="******", password="******")
            db.session.add(user)
            db.session.commit()
示例#8
0
def drop_and_create_db(verbose=False):
    """
    Drops database and creates a new one
    """
    if not verbose:
        db.engine.echo = False
    db.reflect()
    db.drop_all()
    db.create_all()
    return 0
示例#9
0
def db(app, request):
    """Session-wide test database."""

    def teardown():
        _db.drop_all()

    _db.app = app
    _db.create_all()

    request.addfinalizer(teardown)
    return _db
    def create_app():
        app.config.from_object('config.TestingConfig')
        app.secret_key = 'super secret key'
        app.logger.addHandler(logging.StreamHandler(sys.stdout))
        app.logger.setLevel(logging.ERROR)
        celery.conf.update(app.config)
        with app.test_request_context():
            db.create_all()
            populate()
            set_settings(secret='super secret key', app_name='Open Event', app_environment=Environment.TESTING)

        return app.test_client()
示例#11
0
def create_app(config_name):
    """
    App factory. Can be used to instantiate various environments.
    """
    _app = Flask(__name__)

    configure_service(_app, config_name)
    db.init_app(_app)

    with _app.app_context():
        db.create_all()
	
    return _app
示例#12
0
def testapp(request):
    from app.models import db

    app = create_app('app.config.TestConfig')
    client = app.test_client()

    db.app = app
    db.create_all()

    def teardown():
        db.session.remove()
        db.drop_all()

    request.addfinalizer(teardown)

    return client
示例#13
0
def initialize_db(credentials):
    with app.app_context():
        populate_data = True
        inspector = reflection.Inspector.from_engine(db.engine)
        table_name = 'events'
        table_names = inspector.get_table_names()
        if table_name not in table_names:
            try:
                db.create_all()
                stamp()
            except:
                populate_data = False
                print "Could not create tables. Either database does not exist or tables already created"
            if populate_data:
                credentials = credentials.split(":")
                DataManager.create_super_admin(credentials[0], credentials[1])
                populate()
示例#14
0
def create_app():
    app = Flask(__name__, static_folder=static_folder)

    try:
        app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['OPENSHIFT_MYSQL_DB_URL'] + os.environ['OPENSHIFT_APP_NAME']
    except KeyError:
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{0}'.format(
            os.path.abspath(os.path.join(app.root_path, '..', 'data-dev.sqlite')))

    app.config['THEME_PATHS'] = (os.path.join(os.environ.get('OPENSHIFT_DATA_DIR', app.root_path), 'themes'), )

    cfg_folder = os.environ.get('OPENSHIFT_DATA_DIR', app.root_path)

    if not os.path.exists(os.path.join(cfg_folder, 'config.yml')):
        make_config(cfg_folder)
        if 'OPENSHIFT_DATA_DIR' in os.environ:
            shutil.copytree(os.path.join(app.root_path, 'static'), os.path.join(cfg_folder, 'static'))
            shutil.copytree(os.path.join(app.root_path, 'themes'), os.path.join(cfg_folder, 'themes'))

    with open(os.path.join(cfg_folder, 'config.yml')) as f:
        app.config.update(yaml.load(f))

    # Database / Admin
    db.init_app(app)
    themes.init_themes(app, app_identifier='WikiWizard')
    login_manager.init_app(app)
    with app.app_context():
        try:
            User.query.all()
        except (OperationalError, ProgrammingError):
            db.create_all()
            install_data()
    # From Flask-Bootstrap
    app.jinja_env.globals['bootstrap_is_hidden_field'] = is_hidden_field_filter
    app.jinja_env.filters['css_sanitized'] = css_sanitizer
    app.jinja_env.add_extension(WikiInclude)

    # URL Rules / Blueprints
    from main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    # Admin view
    from admin import create_admin
    create_admin(app)

    return app
    def create_app():
        # app.config.from_object('config.TestingConfig')
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['DEBUG_TB_ENABLED'] = False
        app.config['CELERY_ALWAYS_EAGER'] = True
        app.config['CELERY_EAGER_PROPAGATES_EXCEPTIONS'] = True
        app.config['BROKER_BACKEND'] = 'memory'
        # app.config['CELERY_BROKER_URL'] = ''
        # app.config['CELERY_RESULT_BACKEND'] = ''
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(_basedir, 'test.db')
        app.secret_key = 'super secret key'
        celery.conf.update(app.config)
        with app.test_request_context():
            db.create_all()
            populate()

        return app.test_client()
示例#16
0
def testapp(request):
    app = create_app('app.settings.TestConfig', env='dev')
    client = app.test_client()

    db.app = app
    db.create_all()

    if getattr(request.module, "create_user", True):
        admin = User('admin', 'supersafepassword')
        db.session.add(admin)
        db.session.commit()

    def teardown():
        db.session.remove()
        db.drop_all()

    request.addfinalizer(teardown)

    return client
示例#17
0
def create_app(config_file):
    app = Flask(__name__)
    app.config.from_pyfile(config_file)

    from app.models import db
    db.app = app
    db.init_app(app)
    with app.app_context():
        db.create_all()

    if config_file == 'config_dev.py':
        from app.models import User
        admin_user = User("admin", "*****@*****.**", "Th1515NOT53cur3")
        admin_user.is_admin = True
        admin_user.zipcode = 80915
        admin_user.viewable = True
        db.session.add(admin_user)
        db.session.commit()

    app.register_blueprint(home)
    app.register_blueprint(auth)
    app.register_blueprint(market)
    app.register_blueprint(comm)
    app.register_blueprint(admin)
    app.debug = True

    from app.login_manager import lm
    lm.init_app(app)
    lm.login_view = 'auth.login'
    lm.login_message = u"You must be logged in to access that page."
    
    from app.email import mail
    mail.init_app(app)
    
    resize.init_app(app)

    from app.models import Item
    whooshalchemy.whoosh_index(app, Item)

    toolbar = DebugToolbarExtension(app)

    return app
示例#18
0
def app(request):
    # We add some config overrides specifically for testing. The password
    # hash is changed to plaintext to speed up user creation.
    config_override = {
        'SQLALCHEMY_DATABASE_URI': 'postgresql://*****:*****@localhost/onekptesting'
    }
    app = create_app(config_override)

    ctx = app.app_context()
    ctx.push()

    db.app = app
    db.create_all()

    def teardown():
        ctx.pop()
        db.drop_all()

    request.addfinalizer(teardown)

    return app
    def create_app():
        # app.config.from_object('config.TestingConfig')
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['DEBUG_TB_ENABLED'] = False
        app.config['CELERY_ALWAYS_EAGER'] = True
        app.config['CELERY_EAGER_PROPAGATES_EXCEPTIONS'] = True
        app.config['BROKER_BACKEND'] = 'memory'
        # app.config['CELERY_BROKER_URL'] = ''
        # app.config['CELERY_RESULT_BACKEND'] = ''
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(_basedir, 'test.db')
        app.secret_key = 'super secret key'
        app.logger.addHandler(logging.StreamHandler(sys.stdout))
        app.logger.setLevel(logging.ERROR)
        celery.conf.update(app.config)
        with app.test_request_context():
            db.create_all()
            populate()
            set_settings(secret='super secret key', app_name='Open Event')

        return app.test_client()
示例#20
0
def init_database():
    db.app = app
    db.init_app(app)
    db.create_all()

    # add users, if they doesn't exist
    if not db.session.query(Player).filter(Player.name == 'Daniel').all():
        db.session.add(Player(name='Daniel', email='*****@*****.**', twitter='volrath'))
    if not db.session.query(Player).filter(Player.name == 'Pedro').all():
        db.session.add(Player(name='Pedro', email='*****@*****.**', twitter='pedrojosep'))
    if not db.session.query(Player).filter(Player.name == 'Julio').all():
        db.session.add(Player(name='Julio', email='*****@*****.**', twitter='jccb'))
    if not db.session.query(Player).filter(Player.name == 'Kristoffer').all():
        db.session.add(Player(name='Kristoffer', email='*****@*****.**', twitter='kpantic'))
    if not db.session.query(Player).filter(Player.name == 'Alberto').all():
        db.session.add(Player(name='Alberto', email='*****@*****.**', twitter='alb3rto269'))
    if not db.session.query(Player).filter(Player.name == 'German').all():
        db.session.add(Player(name='German', email='*****@*****.**', twitter=''))

    # create.
    db.session.commit()
示例#21
0
def fullapp(request):
    app = create_app('app.settings.TestConfig', env='dev')
    client = app.test_client()

    db.app = app
    db.create_all()

    notebook = Notebook(name="Test Notebook", guid="5547a496-5f55-4b3c-b3da-4a457af78afc", active=True)
    tag1 = Tag(name="published", guid="8e552926-5bb5-45f3-93c4-0ee3670e33bf")
    tag2 = Tag(name="markdown", guid="81e5465e-4190-4719-bc70-ab19c2067289")
    tag3 = Tag(name="page", guid="cfeab7bb-daaf-4ccb-b410-3a2b2b46f0b0")
    # tag4 = Tag(name="sticky", guid="246ba18c-518d-44d6-9db9-0c219018812b")
    tag5 = Tag(name="test", guid="82be53a8-501f-4f69-b0c0-0bf00f530535")

    page1 = Note(title="Test Page", guid="581717a2-fdcc-4219-8922-252b89bd1434",
                 created=datetime.fromtimestamp(1447805140000/1000),
                 content='<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note><en-note></en-note>')
    page1.tags.append(tag1)
    page1.tags.append(tag2)
    page1.tags.append(tag3)

    note1 = Note(title="Test Note", guid="ef263e4c-ee26-4b5b-b746-e419f33646e1",
                 created=datetime.fromtimestamp(1447805140000/1000),
                 content='<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note><en-note></en-note>')
    note1.tags.append(tag1)
    note1.tags.append(tag2)
    note1.tags.append(tag5)

    notebook.notes.append(page1)
    notebook.notes.append(note1)
    db.session.add(notebook)
    db.session.commit()

    def teardown():
        db.session.remove()
        db.drop_all()

    request.addfinalizer(teardown)

    return client
示例#22
0
def initialize_db(credentials):
    with app.app_context():
        populate_data = True
        inspector = reflection.Inspector.from_engine(db.engine)
        table_name = 'events'
        table_names = inspector.get_table_names()
        print("[LOG] Existing tables:")
        print("[LOG] " + ','.join(table_names))
        if table_name not in table_names:
            print("[LOG] Table not found. Attempting creation")
            try:
                db.create_all()
                stamp()
            except Exception:
                populate_data = False
                print("[LOG] Could not create tables. Either database does not exist or tables already created")
            if populate_data:
                credentials = credentials.split(":")
                create_super_admin(credentials[0], credentials[1])
                populate()
        else:
            print("[LOG] Tables already exist. Skipping data population & creation.")
示例#23
0
def testapp(request):
    app = create_app("app.settings.TestConfig")
    client = app.test_client()

    db.app = app
    db.create_all()

    if getattr(request.module, "create_photo", True):
        photo = Photo(title="Title", filename="test.jpg", mimetype="image/jpg")
        db.session.add(photo)
        db.session.commit()

    def teardown():
        db.session.remove()
        db.drop_all()

        for f in os.listdir(os.path.join(os.path.abspath(os.path.dirname(__file__)), "images")):
            if f != "test.jpg":
                os.remove(os.path.join(os.path.abspath(os.path.dirname(__file__)), "images", f))


    request.addfinalizer(teardown)

    return client
示例#24
0
def createdb():
    from app.models import db
    db.create_all()
示例#25
0
 def setUp(self):
     db.create_all()
示例#26
0
def init_db():
    # 将模型映射成表,只用使用一次
    db.create_all()
    # db.drop_all()
    return '初始化数据库成功'
示例#27
0
文件: manager.py 项目: lpe234/bms
def create_all():
    """
    create all database tables.
    """
    db.create_all()
示例#28
0
文件: run.py 项目: zggcd/JAD
def createall():
    """ 创建数据库表 """
    db.create_all()
示例#29
0
 def setUp(self):
     with self.app.app_context():
         db.create_all()
         create_test_data()
示例#30
0
def create():
    db.create_all()
示例#31
0
文件: __init__.py 项目: jnsdrtlf/et
def create_app(root_path, minimal=False):
    app_name = 'minimal_app' if minimal else __name__
    app = Flask(app_name, root_path=root_path)

    config = os.environ.get('CONFIG', default='config/dev.cfg')
    secrets = os.environ.get('SECRETS', default='config/secret.cfg')
    app.config.from_pyfile(os.path.abspath(config))
    app.config.from_pyfile(os.path.abspath(secrets))
    app.secret_key = app.secret_key.encode()
    app.static_url_path = app.config.get('STATIC_FOLDER')
    app.static_folder = os.path.join(app.root_path, app.static_url_path)
    app.template_folder = os.path.join(app.root_path,
                                       app.config.get('TEMPLATE_FOLDER'))

    from app.models.event import Event
    from app.models.grade import Grade
    from app.models.lesson import Lesson
    from app.models.period import Period
    from app.models.relationships import UserGrade, UserLesson, UserSubject
    from app.models.report import Report
    from app.models.school import School
    from app.models.session import Session
    from app.models.subject import Subject
    from app.models.time import Time
    from app.models.user import User
    from app.models import db

    db.init_app(app)

    if not minimal:
        from app.blueprints.api import v1
        from app.blueprints.api.v1 import user as user_api
        from app.blueprints.api.v1 import lesson as lesson_api
        from app.blueprints.api.v1 import session as session_api
        from app.blueprints import auth
        from app.blueprints import index
        from app.blueprints import user as user
        from app.models.enums import Locale
        from app.models import ma
        from app.i18n import babel, moment
        import app.utils as utils
        from app.utils.tasks import tasks
        babel.init_app(app)
        moment.init_app(app)
        ma.init_app(app)
        db.create_all(app=app)

        @app.after_request
        def call_after_request_callbacks(response):
            for callback in getattr(g, 'after_request_callbacks', ()):
                callback(response)
            return response

        @app.before_request
        def auth_middleware():
            sid = request.cookies.get('sid',
                                      default='') or request.values.get('sid')
            session_result = Session.verify(sid)
            if session_result:
                g.session = session_result
                g.locale = g.session.user.locale.value
            else:
                g.session = None
                g.locale = utils.get_best_locale().value

            @utils.after_this_request
            def set_cookie(response):
                if g.session:
                    g.session.set_cookie(response)

        @app.before_request
        def config_middleware():
            try:
                g.school = db.session.query(School).filter(
                    School.id == 1).one()
            except:
                g.school = False
                endpoints = [
                    'static', 'auth.config', None, 'school_api1.school_post',
                    'school_api1.school_put'
                ]
                if request.endpoint not in endpoints:
                    app.logger.info('No school found. Redirect to config')
                    return redirect(url_for('auth.config', stage='school'))

        @babel.localeselector
        def get_locale():
            return g.locale

        # ------------
        # API routes
        # ------------
        app.register_blueprint(v1.bp, url_prefix='/api/v1')
        app.register_blueprint(user_api.bp, url_prefix='/api/v1/user')
        app.register_blueprint(session_api.bp, url_prefix='/api/v1/session')
        app.register_blueprint(lesson_api.bp, url_prefix='/api/v1/lesson')

        # ------------
        # Frontend
        # ------------
        app.register_blueprint(auth.bp)
        app.register_blueprint(user.bp, url_prefix='/user')
        app.register_blueprint(index.bp)

        tasks.create_events()

    return app, db
示例#32
0
def init_db(app):
    db.init_app(app)
    with app.app_context():
        db.create_all()
示例#33
0
def init_db():
    db.drop_all()
    db.create_all()
    populate_db()
示例#34
0
def create_db():
    db.drop_all()
    db.create_all()
示例#35
0
def reset_database():
    db.session.commit()
    db.drop_all()
    db.create_all()
    print('done')
示例#36
0
import glob

from datetime import datetime
from sqlalchemy import MetaData
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine



#local
#http://stackoverflow.com/questions/6506578/how-to-create-a-new-database-using-sqlalchemy
#engine = create_engine("mysql://*****:*****@localhost/metablog")
#if not database_exists(engine.url):
#    create_database(engine.url)

db.create_all()

with open('names.json') as data_file:
    data = json.load(data_file)

lorem = ["""Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.""", """Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?""", """At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."""]

IMAGES = [open(i).read() for i in glob.glob("testa_src/images/user*.jpg")]


def genRandUsers(number):
    for i in range(number):
        first = random.choice(data["first"])
        last = random.choice(data["last"])
        uid = str(int(hashlib.sha224( first + str(datetime.utcnow())).hexdigest(),16))[:6]
        print(uid)
示例#37
0
import sys
from app.models import db
_help = 'help      帮助\n' \
        'init      初始化数据库\n' \
        'migrate   同步数据库\n' \
        ''

if len(sys.argv) > 1:
    t = sys.argv[1]
    if t == 'init':
        db.create_all()
    if t == 'help':
        print(_help)
    if t == 'migrate':
        print('--------------')


else:
    print(_help)

示例#38
0
 def setUp(self):
     self.app = create_test_app()
     self.client = self.app.test_client()
     db.init_app(self.app)
     db.create_all()
示例#39
0
def initialize_db(credentials):
    with app.app_context():
        db.create_all()
        credentials = credentials.split(":")
        DataManager.create_super_admin(credentials[0], credentials[1])
        populate()
示例#40
0
 def create():
     "Creates database tables from sqlalchemy models"
     db.create_all()
     stamp()
    def tearDown(self):
        """Call after every test to remove the created table."""

        with self.app.app_context():
            db.drop_all()
            db.create_all()
示例#42
0
def create_table():
    db.create_all()
示例#43
0
def reset_db():
    print(type(db))
    db.drop_all()
    db.create_all()
    return jsonify({"message": "DB RESET OK"})
示例#44
0
 def setUp(self):
     db.drop_all()
     db.create_all()
示例#45
0
def drop_and_create_db():
    db.drop_all()
    db.create_all()
def database(app):
    _db.create_all()
    set_settings(app_name='Open Event', app_environment=Environment.TESTING)
    yield _db
    Setup.drop_db()
示例#47
0
def createdb():
    """ Creates a database with all of the tables defined in
        your SQLAlchemy models
    """

    db.create_all()
示例#48
0
 def setUp(self):
     """ Runs before each test """
     service.init_db()
     db.drop_all()  # clean up the last tests
     db.create_all()  # create new tables
     self.app = service.app.test_client()
示例#49
0
def setupTestEnvironment(test):
    app = createApiApp(TestConfig)
    test.app_context = app.app_context()
    test.app_context.push()
    db.create_all()
    return app
示例#50
0
文件: edit_db.py 项目: swindiggie/idb
def create_db():
    with app.app_context():
        db.init_app(app)

        db.create_all()

        created_anime = []
        created_characters = []
        created_actors = []
        created_manga = []

        existing_character = {}
        existing_actor = {}
        existing_manga = {}

        for anime_file_num in os.listdir(data_folder + jikan_anime):
            with open(data_folder + jikan_anime + anime_file_num) as anime_datafile:
                print("anime: " + anime_file_num)
                anime_json_data = json.load(anime_datafile)

                anime_title = anime_json_data['title']
                anime_aired = anime_json_data['aired']
                anime_score = anime_json_data['score'][0]
                anime_episodes = anime_json_data['episodes']
                anime_synopsis = anime_json_data['synopsis']

                anime_type = anime_json_data['type']
                if anime_type == None:
                    anime_type = 'Unknown'

                anime_pic = anime_json_data['image']
                anime_status = anime_json_data['status']
                anime_youtube = None
                try:
                    if anime_json_data['youtubeVideoId'] != '':
                        anime_youtube = anime_json_data['youtubeVideoId']

                except KeyError:
                    pass
                
                genre_list = []
                for genre in anime_json_data['genre']:
                    genre_list.append(genre[1])

                anime_genre = ', '.join(genre_list)

                anime_rating = anime_json_data['rating']
                
                final_anime = Anime(title=anime_title, aired=anime_aired, score=anime_score, num_episodes=anime_episodes, synopsis=anime_synopsis, media_type=anime_type, picture=anime_pic, status=anime_status, youtube_id=anime_youtube, rating=anime_rating, genre=anime_genre)
                created_anime.append(final_anime)

                # Character
                if 'character' in anime_json_data:
                    for character_list_object in anime_json_data['character']:
                        if character_list_object['role'] == 'Main':
                            anime_character_id = (character_list_object['url'].split('/'))[4]
                            if anime_character_id in existing_character:
                                final_anime.characters.add(created_characters[existing_character[anime_character_id]])
                                continue

                            if os.path.exists(data_folder + jikan_character + anime_character_id):
                                with open(data_folder + jikan_character + anime_character_id) as character_datafile:
                                    character_json_data = json.load(character_datafile)

                                    try:
                                        character_name = character_json_data['name']
                                    except KeyError:
                                        continue
                                    
                                    character_japanese_name = character_json_data['name-japanese']
                                    character_about = character_json_data['about']
                                    character_pic = character_json_data['image']
                                    if not character_pic:
                                        character_pic = None

                                    print("Creating character with MAL ID:" + anime_character_id)
                                    final_character = Character(name=character_name, japanese_name=character_japanese_name, about=character_about, picture=character_pic)
                                    created_characters.append(final_character)
                                    existing_character[anime_character_id] = len(created_characters) - 1

                                    final_anime.characters.add(final_character)

                                    # Voice actor
                                    if 'voice-actor' in character_list_object:
                                        for actor_list_object in character_list_object['voice-actor']:
                                            actor_id = (actor_list_object['url'].split('/'))[4]

                                            if actor_id in existing_actor:
                                                final_character.actors.add(created_actors[existing_actor[actor_id]])
                                                final_anime.actors.add(created_actors[existing_actor[actor_id]])
                                                continue

                                            actor_name = actor_list_object['name']

                                            if os.path.exists(data_folder + jikan_person + actor_id):
                                                print("actor id: " + actor_id)
                                                with open(data_folder + jikan_person + actor_id) as actor_datafile:
                                                    actor_json_data = json.load(actor_datafile)

                                                    actor_language = actor_json_data['language']
                                                    actor_given_name = None

                                                    try:
                                                        actor_given_name = actor_json_data['given-name']
                                                    except KeyError:
                                                        pass
                                                    
                                                    actor_birthday = actor_json_data['birthday']
                                                    actor_pic = None if actor_json_data['image'] == "" else actor_json_data['image']
                                                    actor_website = None if actor_json_data['website'] == "" else actor_json_data['website']
                                                    
                                                    final_actor = Actor(name=actor_name, language=actor_language, given_name=actor_given_name, birthday=actor_birthday, picture=actor_pic, website=actor_website)
                                                    created_actors.append(final_actor)
                                                    existing_actor[actor_id] = len(created_actors) - 1

                                                    final_character.actors.add(final_actor)
                                                    final_anime.actors.add(final_actor)

                # Manga
                if 'related' in anime_json_data:
                    related = anime_json_data['related']
                    if 'Adaptation' in anime_json_data['related']:
                        adaptation_obj = related['Adaptation']

                        manga_id_list = []
                        if isinstance(adaptation_obj[0], list):
                            for list_obj in related['Adaptation']:
                                tokens = list_obj[1].split('/')
                                manga_id_list.append(tokens[2])

                        else:
                            manga = related['Adaptation']
                            manga = manga[1].split('/')
                            manga_id_list.append(manga[2])
                    
                        for manga_id in manga_id_list:
                            if manga_id in existing_manga:
                                final_anime.mangas.add(created_manga[existing_manga[manga_id]])

                            elif os.path.exists(data_folder + jikan_manga + manga_id):
                                print("manga id: " + manga_id)
                                with open(data_folder + jikan_manga + manga_id) as manga_datafile:
                                    manga_json_data = json.load(manga_datafile)

                                    manga_title = None
                                    if manga_json_data['type'] == 'Novel':
                                        manga_title = manga_json_data['title'] + ' - (Novel)'
                                    else:
                                        manga_title = manga_json_data['title']

                                    manga_title_english = None
                                    try:
                                        manga_title_english = manga_json_data['title-english']
                                    except KeyError:
                                        pass

                                    manga_title_japanese = None
                                    try:
                                        manga_title_japanese = manga_json_data['japanese']
                                    except KeyError:
                                        pass

                                    list_authors = []
                                    for json_author in manga_json_data['author']:
                                        list_authors.append(json_author['name'])
                                    manga_author = ', '.join(list_authors)

                                    manga_published = manga_json_data['published']
                                    
                                    manga_score = None
                                    try:
                                        manga_score = manga_json_data['score'][0]
                                    except KeyError:
                                        pass
                                    

                                    manga_chapters = manga_json_data['chapters']
                                    manga_synopsis = manga_json_data['synopsis']
                                    manga_type = manga_json_data['type']
                                    manga_picture = manga_json_data['image']
                                    manga_status = manga_json_data['status']

                                    manga_genre_list = []
                                    for genre in manga_json_data['genre']:
                                        manga_genre_list.append(genre[1])

                                    manga_genre = ', '.join(manga_genre_list)

                                    final_manga = Manga(title=manga_title, title_english=manga_title_english, title_japanese=manga_title_japanese, author=manga_author, published=manga_published, score=manga_score, num_chapters=manga_chapters, synopsis=manga_synopsis, media_type=manga_type, picture=manga_picture, status=manga_status, genre=manga_genre)
                                    created_manga.append(final_manga)
                                    existing_manga[manga_id] = len(created_manga) - 1

                                    final_anime.mangas.add(final_manga)


                                    for manga_character in manga_json_data['character']:
                                        manga_character_id = (manga_character['url'].split('/'))[4]

                                        if manga_character_id in existing_character:
                                            final_manga.characters.add(created_characters[existing_character[manga_character_id]])
                                        else:
                                            if os.path.exists(data_folder + jikan_character + manga_character_id):
                                                with open(data_folder + jikan_character + manga_character_id) as manga_character_datafile:
                                                    manga_character_json_data = json.load(manga_character_datafile)

                                                    try:
                                                        manga_character_name = manga_character_json_data['name']
                                                    except KeyError:
                                                        continue
                                                    
                                                    manga_character_japanese_name = manga_character_json_data['name-japanese']
                                                    manga_character_about = manga_character_json_data['about']
                                                    manga_character_pic = manga_character_json_data['image']

                                                    print("Creating manga character: " + manga_character_id)
                                                    final_manga_character = Character(name=manga_character_name, japanese_name=manga_character_japanese_name, about=manga_character_about, picture=manga_character_pic)
                                                    created_characters.append(final_manga_character)
                                                    existing_character[manga_character_id] = len(created_characters) - 1

                                                    final_manga.characters.add(final_manga_character)


        for anime in created_anime:
            db.session.add(anime)

        for character in created_characters:
            db.session.add(character)

        for actor in created_actors:
            db.session.add(actor)

        for manga in created_manga:
            db.session.add(manga)

        

        db.session.commit()
        print("I HAVE COMITTED")
示例#51
0
from flask import Flask
from app.models import db

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

db.init_app(app)
db.create_all(app=app)

示例#52
0
def init_db():
    from app.models import db
    db.create_all(app=create_app())
示例#53
0
def init_db():
    db.init_app(Kanban_app)
    db.app = Kanban_app
    db.create_all() # create models in model.py
示例#54
0
def create_all():
    db.create_all()
    return '创建成功'
示例#55
0
def init_db(app):
    db.init_app(app)
    with app.app_context():
        db.create_all()
示例#56
0
def create_db():
    # 创建数据库中的表
    db.create_all()
    return '创建数据表'
示例#57
0
 def setUp(self):
     db.create_all()
示例#58
0
def resetdb():
    if os.path.exists("app/app.db"):
        os.remove("app/app.db")
    db.create_all()
示例#59
0
文件: user_views.py 项目: lpcqq/luo
def create_db():
    db.create_all()
    return '创建数据库成功'
示例#60
0
def create_db():
    db.create_all()
    return '创建完毕'