示例#1
0
def recreate_db():  #第二课新增
    """
    Recreates a local database. You probably should not use this on
    production.
    """
    db.drop_all()
    db.create_all()
    db.session.commit()
def delete_db():
    if input(
            "WARNING THIS WILL ERASE THE LOG DATABASE. ARE YOU SURE YOU WANT TO PROCEED?(y/n)"
    ) == "y":
        with app.app_context():
            db.drop_all()
            db.session.commit()
            print("Database cleared successfully.")
示例#3
0
def app():
    app = create_app(TestConfig)

    with app.test_client() as client:
        # create demo db in memory
        with app.app_context():
            conn = db.engine.raw_connection()
            cursor = conn.cursor()
            cursor.executescript(default_data())

            yield client

            db.drop_all()
示例#4
0
def db(test_app: flask.Flask) -> flask_sqlalchemy.SQLAlchemy:
    from backend import db

    connected = False
    while not connected:
        try:
            db.drop_all()
            db.create_all()
        except (sqlalchemy.exc.OperationalError, psycopg2.OperationalError):
            time.sleep(1)
        else:
            connected = True
    yield db

    db.session.close()
示例#5
0
def db(request):
    if not real_app.config["SQLALCHEMY_DATABASE_URI"]:
        pytest.skip("Database not configured")  # pragma: nocover

    ctx = real_app.app_context()

    def fin():
        real_db.session.close_all()
        real_db.drop_all()
        # This is a bit of a hack, since we can't use `with`
        ctx.__exit__(None, None, None)

    ctx.__enter__()
    request.addfinalizer(fin)
    real_db.session.close_all()
    real_db.drop_all()
    real_db.create_all()
    return real_db
示例#6
0
文件: app.py 项目: Shyee-wsy/2do
def init_db(forge):
    """
    初始化数据库(包括生成初始数据)
    """
    db.drop_all()
    db.create_all()

    default_data = get_default_data()
    db.session.add_all(default_data)
    if forge is True:
        click.confirm(
            "This operation will generate the todo forge data, "
            "do you want to continue?",
            abort=True)
        forge_data = get_forge_data()
        db.session.add_all(forge_data)
    db.session.commit()

    click.echo("\nInitialized database success!")
示例#7
0
 def fin():
     real_db.session.close_all()
     real_db.drop_all()
     # This is a bit of a hack, since we can't use `with`
     ctx.__exit__(None, None, None)
示例#8
0
def dropdb():
    """Drops the db tables."""

    db.drop_all()
示例#9
0
from dotenv import load_dotenv
load_dotenv()
from werkzeug.security import generate_password_hash
from flask import jsonify

from backend import app, db
from backend.models import User, Skill
import json

with app.app_context():
  db.drop_all()
  db.create_all()
  jamesSkills = json.dumps({'Japanese': 1000, 'Javascript': 500, 'guitar': 30,
  'Python': 100, 'pool': 100, 'react': 100, 'redux': 100, 'learning': 200,

  })
  # Users
  james = User(username = '******', email = '*****@*****.**', hashed_password = generate_password_hash("password"), user_skills= jamesSkills, focus= 'Javascript',
  theme = 'galaxy')
  javier = User(username = '******', email = '*****@*****.**')
  dean = User(username = '******', email = '*****@*****.**')
  angela = User(username = '******', email = '*****@*****.**')
  soonmi = User(username = '******', email = '*****@*****.**')
  alissa = User(username = '******', email = '*****@*****.**')

  # Skills
  japanese = Skill(
    name = 'Japanese',
    skill_tip1= '''Learn the Alphabets in order of Hiragana, Katakana, Kanji.
    When learning kanji remember start with the jouyou kanji. Try to learn
    20-30 words a week after you have learned the first two alphabets''',
示例#10
0
 def run(self):
     db.drop_all()
     db.create_all()
示例#11
0
def drop():
    """Drops all of the tables from the database."""
    db.drop_all()
    print('Dropped all of the tables from the database.')
def cleanthemess():
    db.drop_all()
    for key in redis.keys():
        redis.delete(key)
    return render_template('error.html', Current_error='__All_deleted___')
示例#13
0
def drop_all():
    db.drop_all()
示例#14
0
def create_db():
    with app.app_context():
        app.logger.info('reflecting db')
        db.reflect()

        app.logger.info('dropping db')
        db.drop_all()

        app.logger.info('creating db')
        db.create_all()

        roles = [Role(name="user"), Role(name="superuser")]
        db.session.add_all(roles)

        user_datastore.create_user(
            first_name='Никита',
            last_name='Кулаков',
            email='*****@*****.**',
            password=encrypt_password('Kul7nick'),
            roles=roles,
        )
        user_datastore.create_user(
            first_name='Екатерина',
            last_name='Лебедева',
            email='*****@*****.**',
            password=encrypt_password('Lasunec123'),
            roles=roles[:1],
        )

        routes = [
            MetroRoute(color='rgb({0},{1},{2})'.format(random.randint(0, 255),
                                                       random.randint(0, 255),
                                                       random.randint(0, 255)),
                       name='Ветка #' + str(i)) for i in range(1, 11)
        ]

        regions = [
            Region(name='Округ #' + str(i),
                   abbr='ABBR',
                   description=generate_text()[:50]) for i in range(1, 11)
        ]

        districts = [
            District(name='Район #' + str(i),
                     region=regions[(i - 1) // 4],
                     description=generate_text()[:50]) for i in range(1, 41)
        ]

        stations = [
            MetroStation(name='Станция #' + str(i),
                         district=districts[i - 1],
                         routes=[
                             routes[(i - 1) % len(routes)],
                             routes[i % len(routes)]
                         ],
                         description=generate_text()[:50])
            for i in range(1, 41)
        ]

        app.logger.info('creating buildings')
        buildings = [
            Building(title='Title #' + i,
                     title_info='Some info in title #' + i,
                     year_build_start=int(datetime.now().year),
                     year_build_end=int(datetime.now().year),
                     leading_img_path='visotka.jpg',
                     latitude=random.uniform(55.614926, 55.860389),
                     longitude=random.uniform(37.416317, 37.772211),
                     images=[
                         BuildingImage(name='image #{}:{}'.format(1, i),
                                       path='shema.jpg'),
                         BuildingImage(name='image #{}:{}'.format(2, i),
                                       path='visota.jpg'),
                         BuildingImage(name='image #{}:{}'.format(3, i),
                                       path='visotka.jpg')
                     ],
                     text=text,
                     address='address #' + i,
                     station=stations[random.randint(0, 39)],
                     district=districts[random.randint(0, 39)],
                     number_facts=[
                         BuildingNumberFact(number=j * random.randint(1, 100),
                                            name='nfact #' + str(j))
                         for j in range(1, random.randint(2, 4))
                     ],
                     text_facts=[BuildingTextFact(text=generate_text())])
            for i in map(str, range(1, 11))
        ]

        architects = [
            Architect(name='Name#' + str(i),
                      surname='Surname#' + str(i),
                      patronymic='Patronymic#' + str(i),
                      born=random.choice([1825, 1927, None, 1953]),
                      died=random.choice([1825, 1927, None, 1953]),
                      alive=random.choice([False, False, False, True]),
                      place_of_birth='Place of birth #' + str(i),
                      quote=generate_text()[:100],
                      text=text,
                      img_path='shusev.jpg',
                      facts=[
                          ArchitectFact(name='name#' + str(i),
                                        text=generate_text()[:60])
                          for i in range(1, random.randint(2, 5))
                      ],
                      square_img='arch-square.png',
                      portrait_img='arch-portrait.png',
                      landscape_img='arch-landscape.png')
            for i in range(1, 20)
        ]
        for i, architect in enumerate(architects):
            if i < len(architects) - 1:
                architect.buildings = [
                    buildings[i % len(buildings)],
                    buildings[(i + 1) % len(buildings)]
                ]
            else:
                architect.buildings = [buildings[i % len(buildings)]]

        styles = [
            Style(name="Стиль #" + str(i),
                  date=random.choice([1800, 1810, 1825, 1840, 1860, 1875]),
                  philosophy='philosophy #' + str(i),
                  ideology='ideology #' + str(i),
                  text=text,
                  fact=generate_text(),
                  architects=[
                      architects[i - 1], architects[(i * 2) % len(architects)]
                  ],
                  buildings=[buildings[i - 1]],
                  building_img_path='klass-build.svg',
                  column_img_path='klass-col.svg',
                  door_handle_img_path='klass-door.svg',
                  description=generate_text()[:75]) for i in range(1, 11)
        ]
        for i, style in enumerate(styles):
            if i != 0:
                styles[i].previous = styles[i - 1]

        elements = [
            Element(name='Element#' + str(i),
                    date=random.choice([1800, 1810, 1825, 1840, 1860, 1875]),
                    text=text,
                    styles=[styles[i - 1], styles[i * 2 % len(styles)]],
                    places=[
                        ElementPlace(name='Element Place #1:' + str(i)),
                        ElementPlace(name='Element Place #2:' + str(i)),
                        ElementPlace(name='Element Place #3:' + str(i)),
                        ElementPlace(name='Element Place #4:' + str(i)),
                    ],
                    examples=[
                        ElementExample(img_path='usadba.jpg',
                                       building=buildings[i - 1]),
                        ElementExample(
                            img_path='usadba.jpg',
                            building=buildings[i * 2 % len(buildings)],
                        ),
                    ],
                    img_path='kartush.svg',
                    description=generate_text()[:60]) for i in range(1, 11)
        ]

        db.session.add_all(buildings)
        db.session.add_all(architects)
        db.session.add_all(routes)
        db.session.add_all(stations)
        db.session.add_all(districts)
        db.session.add_all(regions)
        db.session.add_all(styles)
        db.session.add_all(elements)

        db.session.commit()
示例#15
0
 def run(self):
     db.drop_all()
     db.create_all()
示例#16
0
 def run(self):
     db.drop_all()
示例#17
0
def create_db():
    db.drop_all()
    db.create_all()
    db.session.commit()
示例#18
0
def drop():
    """Drops all of the tables from the database."""
    db.drop_all()
    click.echo('Dropped all of the tables from the database.')
示例#19
0
def initdb(drop):
    if drop:
        db.drop_all()

    db.create_all()
    click.echo('Initialized database')
示例#20
0
def recreate():
    """Drops and recreates the tables in the database."""
    db.drop_all()
    db.create_all()
    click.echo('Recreated all of the tables in the database.')
示例#21
0
 def tearDown(self):
     db.session.remove()
     db.drop_all()
示例#22
0
 def run(self):
     db.drop_all()