def search_db(sender, data): simple.hide_item("Create Document from Template") session = Session() vars = session.query(Variable).order_by(Variable.name.asc()) with simple.window(f"Search in DB ({data.split('_')[0]})", **default_window()): core.add_text("All variables") for var in vars: core.add_input_text( f"{var.name}_name_search", label="", width=150, enabled=False, default_value=var.name, ) core.add_same_line(spacing=10) core.add_input_text( f"{var.name}_content_search", label="", width=300, enabled=False, default_value=var.content, ) core.add_same_line(spacing=10) core.add_button( f"{var.name}_update_button_search", label="Use this value", callback=use_value, callback_data=((data, var.content)), ) core.add_button( "button_db_close", label="Close Window", callback=close_popup, )
def addUser(username, refresh_token, playlist_id_short=None, playlist_id_medium=None, playlist_id_long=None): session = Session() id_exists = session.query(User.id).filter_by(username=username).scalar() # new user if id_exists == None: user = User(username=username, refresh_token=refresh_token, playlist_id_short=playlist_id_short, playlist_id_medium=playlist_id_medium, playlist_id_long=playlist_id_long) session.add(user) logging.info('New auto user: '******'Auto user updated: ' + user.username) # only update playlist IDs that are new if playlist_id_short != None: user.playlist_id_short = playlist_id_short if playlist_id_medium != None: user.playlist_id_medium = playlist_id_medium if playlist_id_long != None: user.playlist_id_long = playlist_id_long session.commit() session.close()
def is_trusted(tchatid): session = Session() q = session.query(TrustedChats).filter( TrustedChats.chat_id == str(tchatid)) session.close() if q.count(): return True return False
def timed_job(): session = Session() users = session.query(Users) for u in users: if datetime.datetime.now() >= u.time_remind: viber.send_messages(u.viber_id, [TextMessage(text="Пора учить слова", keyboard=KEYBOARD, tracking_data='tracking_data')]) session.close()
def test_track_playtime_supports_pauses(self): session = Session() session.add_event(Event('track_start', 50, 'A', '101')) session.add_event(Event('pause', 60, 'A', '101')) session.add_event(Event('play', 70, 'A', '101')) session.add_event(Event('track_end', 100, 'A', '101')) assert session.track_playtime == 40
def save_or_update_db(sender, data): session = Session() name = core.get_value(data[0]) content = core.get_value(data[1]) args = argparse.Namespace(name=name, content=content, tag=None) db_var = session.query(Variable).filter(Variable.name == name).first() if db_var: update_variable(args) else: add_variable(args)
def add_user(bot, update): root_from_set = config['TELEGRAM']['Root_users'] root_from_set = root_from_set.split(',') is_root = False for id in root_from_set: if str(id) == str(update.message.chat_id): is_root = True if not is_root: return False text = update.message.text text = text.replace('/addUser ', '') text = text.split(' ') adding_chat_it = text[0] try: adding_user_name = text[1] except IndexError: adding_user_name = '' session = Session() q = session.query(TrustedChats).filter( TrustedChats.chat_id == str(adding_chat_it)) if q.count(): bot.send_message(chat_id=update.message.chat_id, text="This user already in base.") bot.send_message(chat_id=update.message.chat_id, text="Bitch") else: myobject = TrustedChats(chat_id=str(adding_chat_it), name=adding_user_name) session.add(myobject) session.commit() bot.send_message(chat_id=update.message.chat_id, text="User was added.") session.close()
def test_start_time_comes_from_first_event(self): session = Session() session.add_event(Event('track_end', 100, 'A', '101')) session.add_event(Event('track_end', 50, 'A', '101')) session.add_event(Event('track_end', 150, 'A', '101')) assert session.start_time == 100
def test_ad_count_counts_number_of_ad_starts(self): session = Session() session.add_event(Event('ad_start', 50, 'A', '101')) session.add_event(Event('ad_start', 50, 'A', '101')) session.add_event(Event('ad_end', 50, 'A', '101')) session.add_event(Event('ad_start', 50, 'A', '101')) assert session.ad_count == 3
def test_track_playtime_supports_paused_heartbeated_unfinished_sessions( self): session = Session() session.add_event(Event('track_start', 50, 'A', '101')) session.add_event(Event('pause', 60, 'A', '101')) session.add_event(Event('track_heartbeat', 70, 'A', '101')) assert session.track_playtime == 10
def list(only_chat_ids): session = Session() q = session.query(TrustedChats).all() if only_chat_ids: res = [] for id in q: res.append(id.chat_id) click.echo(res) return True for id in q: if id.name is None: click.echo("Chat ID: {}".format(id.chat_id)) else: click.echo("Chat ID: {}, Name: {}".format(id.chat_id, id.name)) session.close()
def add_var_line(var, parent): session = Session() db_var = session.query(Variable).filter(Variable.name == var.name).first() default = "" if db_var: default = db_var.content core.add_input_text( f"{var.name}_name", label="", width=150, enabled=False, default_value=var.name, parent=parent, ) core.add_same_line(spacing=10, parent=parent) if db_var and db_var.content and len(db_var.content) > 80: height = 80 multiline = True else: height = 0 multiline = False core.add_input_text( f"{var.name}_input", label="", width=300, default_value=default, parent=parent, multiline=multiline, height=height, ) core.add_same_line(spacing=10, parent=parent) core.add_button( f"{var.name}_search_button", label="Search in DB", callback=search_db, callback_data=f"{var.name}_input", parent=parent, ) core.add_same_line(spacing=10, parent=parent) core.add_button( f"{var.name}_update_button", label="Save/Update", callback=save_or_update_db, callback_data=(f"{var.name}_name", f"{var.name}_input"), parent=parent, )
def add(id, name): session = Session() q = session.query(TrustedChats).filter(TrustedChats.chat_id == str(id)) if q.count(): click.secho(click.style('ChatId must be unique.', fg='red', blink=True), err=True) click.secho("Use \"list\" to see all trusted chat ids.") else: myobject = TrustedChats(chat_id=str(id), name=name) session.add(myobject) session.commit() click.echo('ChatId {} was added.'.format(id)) session.close()
def edit_db(): simple.hide_item("Create Document from Template") session = Session() vars = session.query(Variable).order_by(Variable.name.asc()) with simple.window("Edit Variable DB", **default_window()): core.add_text("All variables") for var in vars: with simple.group(f"{var.name}_group"): core.add_input_text( f"{var.name}_name_db", label="", width=150, enabled=False, default_value=var.name, ) core.add_same_line(spacing=10) core.add_input_text( f"{var.name}_content_db", label="", width=300, default_value=get_content(var.content), ) core.add_same_line(spacing=10) core.add_button( f"{var.name}_update_button_db", label="Update", callback=save_or_update_db, callback_data=(f"{var.name}_name_db", f"{var.name}_content_db"), ) core.add_same_line(spacing=10) core.add_button( f"{var.name}_delete_button_db", label="Delete", callback=remove_variable_gui, callback_data=argparse.Namespace(name=var.name), ) core.add_button( "close_button_db", label="Close Window", callback=close_popup, )
def test_track_playtime_counts_time_between_track_start_and_track_end( self): session = Session() session.add_event(Event('track_start', 50, 'A', '101')) session.add_event(Event('track_end', 100, 'A', '101')) assert session.track_playtime == 50
def test_duration_is_time_between_last_and_first_event(self): session = Session() session.add_event(Event('track_end', 50, 'A', '101')) session.add_event(Event('track_end', 150, 'A', '101')) session.add_event(Event('track_end', 100, 'A', '101')) assert session.duration == 50
#!/usr/bin/env python from main import Base, Session, User # 创建表结构和数据 Base.metadata.create_all() #中是我西iugai的的将阿黄飞鸿第四故事女工的 # 定义数据 bob = User(name='bob', birthday='1990-3-21', city='上海', money=370) tom = User(name='tom', birthday='1995-9-12', money=288) lucy = User(name='lucy', birthday='1998-5-14', city='北京') jam = User(name='jam', birthday='1994-3-9', city='深圳', money=86) alex = User(name='alex', birthday='1992-3-17', city='北京') eva = User(name='eva', birthday='1987-7-28', city='深圳', money=631) rob = User(name='rob', birthday='1974-2-5', city='上海', money=735) ella = User(name='ella', birthday='1999-5-26', city='北京') tony = User(name='tony', city='深圳', money=199) # 在数据库中添加数据 session = Session() # 创建会话 session.add_all([bob, tom, lucy, jam, alex, eva, rob, ella, tony]) session.commit()
from datetime import date from main import Session, engine, Base from actors import Actor from contact_details import ContactDetails from movie import Movie from stuntman import Stuntman # generate the schema Base.metadata.create_all(engine) # create a new session session = Session() # create movies bourne_identity = Movie("The Bourne Identity", date(2002, 10, 11)) furious_7 = Movie("Furious 7", date(2015, 4, 2)) pain_and_gain = Movie("Pain & Gain", date(2013, 8, 23)) # 5 - creates actors matt_damon = Actor("Matt Damon", date(1970, 10, 8)) dwayne_johnson = Actor("Dwayne Johnson", date(1972, 5, 2)) mark_wahlberg = Actor("Mark Wahlberg", date(1971, 6, 5)) # 6 - add actors to movies bourne_identity.actors = [matt_damon] furious_7.actors = [dwayne_johnson] pain_and_gain.actors = [dwayne_johnson, mark_wahlberg] # 7 - add contact details to actors matt_contact = ContactDetails("415 555 2671", "Burbank, CA", matt_damon)
def test_session_id_comes_from_first_event(self): session = Session() session.add_event(Event('track_end', 100, 'A', '101')) session.add_event(Event('track_end', 100, 'B', '101')) assert session.session_id == ('A', '101')
def test_track_playtime_works_without_track_end(self): session = Session() session.add_event(Event('track_start', 50, 'A', '101')) session.add_event(Event('track_heartbeat', 60, 'A', '101')) assert session.track_playtime == 10
def test_get_formatted_output_returns_in_correct_format(self): session = Session() session.add_event(Event('stream_start', 50, 'A', '101')) session.add_event(Event('ad_start', 60, 'A', '101')) session.add_event(Event('ad_end', 70, 'A', '101')) session.add_event(Event('track_start', 80, 'A', '101')) session.add_event(Event('track_heartbeat', 90, 'A', '101')) assert session.get_formatted_output() == { 'user_id': 'A', 'content_id': '101', 'session_start': 50, 'session_end': 90, 'total_time': 40, 'track_playtime': 10, 'event_count': 5, 'ad_count': 1 }
from main import User, Session, engine local_session = Session(bind=engine) #returns all objects # users=local_session.query(User).all()[:3] # for user in users: # print(user.username) #query for one object jona = local_session.query(User).filter(User.username == "jona").first() print(jona)
import unittest from main import Session from movie import Movie from actors import Actor session = Session() class SQLAlchemy_tests(unittest.TestCase): def test_connect(self): print(session.query(Movie).exists())
from main import Session,engine,User local_session=Session(bind=engine) user_to_delete=local_session.query(User).filter(User.username=="jonathan").first() local_session.delete(user_to_delete) local_session.commit()
from actors import Actor from main import Base, Session from contact_details import ContactDetails from movie import Movie from datetime import date session = Session() all_movies = session.query(Movie).all() print('\n### All movies') for movie in all_movies: print(f'{movie.title} was released on {movie.release_date}') print('') # get movies after 15-01-01 recent_movies = session.query(Movie).filter( Movie.release_date > date(2015, 1, 1)).all() print('\n### Recent movies') for movie in recent_movies: print(f'{movie.title} was released on {movie.release_date}') print('') # movies with the rock! rock_movies = session.query(Movie).join( Actor, Movie.actors).filter(Actor.name == 'Dwayne Johnson').all() print('\n### Rock movies') for movie in rock_movies: print(f'The Rock starred in {movie.title}')
def test_is_expired_is_false_59_seconds_after_last_event(self): session = Session() session.add_event(Event('ad_start', 50, 'A', '101')) assert not session.is_expired(50 + 59)
def updatePlaylists(): session = Session() # attempt to update each user's playlists for user in session.query(User): is_active = False # authorize the application with Spotify API payload = refreshToken(user.refresh_token) # if user account has been removed or authorization revoked, user is deleted if payload == None: session.delete(user) else: access_token = payload[0] playlist = user.playlist_id_short if playlist != None: # if the playlist has not been deleted if (dbClearPlaylist(access_token, playlist) != None): uri_list = dbGetTopTracksURI(access_token, 'short_term', 50) dbAddTracksPlaylist(access_token, playlist, uri_list) is_active = True else: user.playlist_id_short = None playlist = user.playlist_id_medium if playlist != None: if (dbClearPlaylist(access_token, playlist) != None): uri_list = dbGetTopTracksURI(access_token, 'medium_term', 50) dbAddTracksPlaylist(access_token, playlist, uri_list) is_active = True else: user.playlist_id_medium = None playlist = user.playlist_id_long if playlist != None: if (dbClearPlaylist(access_token, playlist) != None): uri_list = dbGetTopTracksURI(access_token, 'long_term', 50) dbAddTracksPlaylist(access_token, playlist, uri_list) is_active = True else: user.playlist_id_long = None # if no playlists could be updated, then remove user if not is_active: session.delete(user) session.commit() session.close() logging.info('Updated TopTracks Playlists')
from main import Session, engine, User local_session = Session(bind=engine) user_to_update = local_session.query(User).filter( User.username == 'jona').first() user_to_update.username = "******" user_to_update.email = "*****@*****.**" local_session.commit()
"email":"*****@*****.**" }, { "username":"******", "email":"*****@*****.**" }, { "username":"******", "email":"*****@*****.**" }, { "username":"******", "email":"*****@*****.**" }, ] local_session=Session(bind=engine) new_user=User(username="******",email="*****@*****.**") local_session.add(new_user) local_session.commit() # for u in users: # new_user=User(username=u["username"],email=u["email"]) # local_session.add(new_user) # local_session.commit()
def test_is_expired_is_true_60_seconds_after_last_event(self): session = Session() session.add_event(Event('ad_start', 50, 'A', '101')) assert session.is_expired(50 + 60)