def sendEmail(PK, intervalID, intervalInSecs): with app.app_context(): queryObject = User.query.join( Settings, User.id == Settings.user_id).join( ChatMessages, Settings.user_id == ChatMessages.to_user).filter( and_(Settings.n_hour == intervalID, ChatMessages.id > PK)).all() maxPK = db.session.query(db.func.max(ChatMessages.id)).scalar() url = "http://optical.cs.ucdavis.edu" # url = "http://*****:*****@gmail.com', recipients=emailArray) msg.body = ("Hey Fort Nitta user,\n\n" + " You have new unread messages waiting!\n " + " Visit Fort Nitta now to check!\n " + "\n\nAll the best,\n" + "Fort Nitta Team,\n" + url) mail.send(msg) threading.Timer( intervalInSecs, lambda: sendEmail(maxPK, intervalID, intervalInSecs)).start()
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.")
def send_popo_correspond(dataList): """对应发送消息""" from backend import app import threading with app.app_context(): if not dataList: return sendPopoByUrl(dataList[0].get("to"), dataList[0].get("msg")) timer = threading.Timer(3, send_popo_correspond, [dataList[1:], ]) timer.start()
def rig_test_client(): with testing.postgresql.Postgresql() as postgresql: with app.app_context(): dburl = postgresql.url() engine = create_engine(dburl) Base.metadata.create_all(engine) db_session.bind = engine user_datastore = SQLAlchemySessionUserDatastore(db_session, User, Role) app.config['SQLALCHEMY_DATABASE_URI'] = dburl app.config['WTF_CSRF_ENABLED'] = False init_app_with_options(user_datastore) yield app.test_client(), engine
def send_popo_batch(toList, msg): """批量发送popo消息""" from backend import app import threading with app.app_context(): if not toList: return if type(toList) != list: sendPopoByUrl(toList, msg) else: sendPopoByUrl(toList[0], msg) timer = threading.Timer(3, send_popo_batch, [toList[1:], msg]) timer.start()
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
def create_new_db(): with app.app_context(): db.create_all() db.session.commit() print("Database created successfully.")
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''',
def insert_data(): # if check_message('Are you sure to insert data ? (Y/n)') == False: # return with app.app_context(): DBManager.insert_dummy_data()
def clear_db(): if check_message('Are you sure to clear database ? (Y/n)') == False: return with app.app_context(): DBManager.clear_db()
def init_db(): if check_message('Are you sure to init database ? (Y/n)') == False: return """Initialize database.""" with app.app_context(): DBManager.init_db()
def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs)
def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs)
def init(): with app.app_context(): db.create_all()
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()