def get_images(): session = Session() image_type = request.args.get('type') images = session.query(DisplayImage).filter_by(type=image_type).all() res = json.dumps(images, cls=AlchemyEncoder, encoding='utf-8') session.close() return res
def setup_data(): delete_db(engine) session = Session() AppModelBase.metadata.create_all(engine) acs = [ ArtifactCoordinatesModel(lat=40.09389490340147, lon=-85.62538134792705), ArtifactCoordinatesModel(lat=40.09585039419487, lon=-85.62004021718168), ArtifactCoordinatesModel(lat=40.09451269825916, lon=-85.62251577299321) ] aims = [ ArtifactImageModel('/static/whiteoak.jpg', 'The white oak tree'), ArtifactImageModel('/static/entrance.jpg', 'The visitor center'), ArtifactImageModel('/static/greatmound.jpg', 'The great mound!') ] artifacts = [ ArtifactModel(name="White Oak", description="The white oak tree"), ArtifactModel(name="Visitor Center", description="The visitor center."), ArtifactModel(name="Great Mound", description="The great mound.") ] for loc in acs: session.add(loc) for a in aims: session.add(a) for idx, artifact in enumerate(artifacts): artifact.addCoordinates(acs[idx]) artifact.addImage(aims[idx]) session.commit() session.close()
def tie_breaker(rank): p1 = rank[0] p2 = rank[1] p1_wins = 0 p2_wins = 0 if p1['pts'] == p2['pts']: session = Session() games = session.query(Game) \ .filter( or_( and_(Game.p1_id == p1['id'], Game.p2_id == p2['id']), and_(Game.p1_id == p2['id'], Game.p2_id == p1['id']) ) ) \ .order_by(Game.id.asc()) \ .all() for game in games: if game.p1_id == p1['id']: if game.p1_wins > game.p2_wins: p1_wins += 1 else: p2_wins += 1 else: if game.p1_wins > game.p2_wins: p2_wins += 1 else: p1_wins += 1 if p2_wins > p1_wins: rank[0] = p2 rank[1] = p1 return rank
def return_existing_kode(kode): session = Session() check_if_present = session.query(Company_List).\ filter(Company_List.company_code == kode).\ scalar() session.close() return check_if_present
def update(cls, old: str, new: str) -> Base: instance = cls.current() if not instance.assert_password(old): raise Exception('Password not matched') instance.set_safe_password(new) Session.commit() return instance
def view_player(id): session = Session() player = session.query(Player).filter(Player.id == id).one() players = session.query(Player).all() decks = session.query(Deck).all() pmap = {} for d in players: pmap[d.id] = d dmap = {} for d in decks: dmap[d.id] = d rank_manager = RankingManager() ranking = rank_manager.get_ranking() rank_data = ranking.get_player_ranking(id) table = rank_manager.ranking_table([rank_data], True) games_data, decks_data = get_player_info(id) titles = rank_manager.get_titles(id) return render_template('players/view_player.html', player=player, players=pmap, decks=dmap, ranking_table=table, games_data=games_data, decks_data=decks_data, titles=titles)
def detail_user_profile(userid): session = Session() try: prof = get_detail_user_profile(session, userid) if not prof: return "User with userid %s does not exist." % userid if request.method == 'POST' and request.content_type == 'application/json': data = { 'userid': prof.userid, 'username': prof.username, 'firstname': prof.firstname, 'lastname': prof.lastname, 'image': prof.image, 'gender': prof.gender, 'age': prof.age, 'profile_created_on': prof.created } return jsonify(data) else: return render_template('detail_user_profile.html', profile=prof, img_link=url_for('.profile_image', userid=prof.userid)) except Exception as ex: session.rollback() raise ex
def add_user(self, username, email=None, fname=None, lname=None, password=None): """ Add a user to the DB""" s = Session() try: u = User(username=username, email=email, fname=fname, lname=lname, password=password, strava_id=self.athlete.id) s.add(u) s.commit() return int(u.id) except SQLAlchemyError as err: s.rollback() print('Error: \n', err) raise s.close() return
def send_player_ranking(ranking_data, block_name, titles): session = Session() players = session.query(Player).all() team = {} for player in players: name = player.name if player.nickname is not None: name = player.nickname team[player.id] = {'name': name} admin = request.args.get('admin', '') == 'True' rank_manager = RankingManager() table = rank_manager.ranking_table(ranking_data, True) for id in team: player = team[id] player['link'] = '/players/profile/%s' % id return render_template('players/index.html', admin=admin, rank_table=table, teams=team, block_name=block_name, titles=titles)
def insert_actor(iActorUUID, iShortName, iCommonName, iCountry, iVictimology, iTOI, iSS, iSince, iMOO, iCaps, iLastUpdate, iDescription): session = Session() try: dbInsert = md.ActorMeta() dbInsert.uuid = iActorUUID dbInsert.shortname = iShortName dbInsert.commonname = iCommonName dbInsert.country = iCountry dbInsert.victimology = iVictimology dbInsert.cfrtypeofincident = iTOI dbInsert.cfrstatesponsor = iSS dbInsert.since = iSince dbInsert.modeofoperation = iMOO dbInsert.capabilities = iCaps dbInsert.last_update = iLastUpdate dbInsert.description = iDescription session.merge(dbInsert) session.commit() except Exception as error: session.rollback() print("f(x) insert_actor: DATABASE ERROR: {}".format(error)) sys.exit(error) finally: session.close() #DEBUG SEQ if gv._DEBUG: print("f(x) insert_actor: {} DATA ADDED TO ACTORS TABLE".format( iShortName))
def create(cls, data: dict) -> Optional[Base]: # try: instance = cls.model(**data) Session.add(instance) Session.commit() return instance
def handleSnippetLike(snippet_id, user): session = Session() #increment snippet likes snippet_to_update = session.query(Snippet).filter_by( id=snippet_id).first() snippet_to_update.likes = snippet_to_update.likes + 1 session.add(snippet_to_update) #print("Updated likes for", snippet_to_update) #associate user that liked snippet with the snippet's attributes #print('id:', user.id) #print("about to print temp snippet") tempSnippetTags = snippet_to_update.tags[:] #print(tempSnippetTags, '\n') user_to_update = session.query(User).filter_by(id=user.id).first() #print(user_to_update) #print('before', user_to_update.tags, '\n') for stag in tempSnippetTags: for utag in user_to_update.tags: if stag == utag: tempSnippetTags.remove(stag) break user_to_update.tags.extend(tempSnippetTags) #print('after', user_to_update.tags, '\n') session.add(user_to_update) #commit changes session.commit()
def change_password(request): session = Session() user = session.query(User).get(request.session['user_id']) if user == None: return HTTPFound(location='/admin/dashboard') return dict(status='ok', view_path=c_view_paths['admin'], user=user)
def destroy(cls, id: int) -> Optional[Base]: try: instance = cls.model.query.filter_by(id=id).one() Session.delete(instance) Session.commit() return instance except: return None
def show(request): session = Session() post_id = request.matchdict['id'] post = session.query(Post).get(post_id) if post == None: return HTTPFound(location='/admin/dashboard') return dict(status='ok', view_path=c_view_paths['admin'], post=post)
def session(): Base.metadata.bind = engine Base.metadata.create_all() connection = engine.connect() transaction = connection.begin() session = Session(bind=connection) yield session session.close() Base.metadata.drop_all(bind=engine) connection.close()
class TestShop(unittest.TestCase): def setUp(self): self.session = Session().session def tearDown(self): self.session.close() def test_select(self): shop = self.session.query(Shop.name).filter(Shop.id == 1).first() self.assertEqual(shop.name, "ラビットハウス")
def search_artifact_name(data): session=Session() searchString=data['searchString'] if(searchString==""): emit('retrieved_search_results',[]) else: searchResults=ArtifactModel.getPartials(session,searchString) searchResults = [ item.getDict() for item in searchResults ] emit('retrieved_search_results',searchResults) session.close()
def timed_job(): session = Session() users = session.query(User) for u in users: if datetime.datetime.utcnow() >= u.time_reminder: viber.send_messages(u.viber_id, [ TextMessage(text="Время повторить слова", keyboard=WAIT_KEYBOARD, tracking_data='tracking_data') ])
def index_view(): session = Session() tournament = session.query(Tournament).filter(Tournament.status == 'active').first() if tournament is None: return render_template('main.html') from .tournaments import render_tournament return render_tournament(tournament=tournament)
def add_streams(self, user_id, s_id): """ Add Strava data streams for a given user_id and activity_id """ # get the strava streams for that activity stream = self.get_streams(s_id) # convert the streams to a DF if stream is not None: s = Session() df = self.stream_to_DF(stream) # add `user_id` to the DF df['user_id'] = user_id # add `activity_id` to the DF df['activity_id'] = s.query( Activity.id).filter_by(strava_id=s_id.astype(str)).one()[0] try: df.to_sql(self.streams_TBL, engine, if_exists='append', index=False) s.commit() except: s.rollback() print('Error: `add_streams` cannot write event to DB. \n') raise s.close() else: print('Error: Stream is empty for User {0}, Activity {1}'.format( user_id, s_id)) return
def __init__(self, username, type=None, freq=None, fields=None): s = Session() user_id = s.query(User.id).filter(User.username == username).one()[0] type = 'Run' if type is None else type q = "SELECT * FROM {0} WHERE user_id={1} AND type='{2}'".format( 'activities', user_id, 'Run') df = pd.read_sql_query(q, engine) df.set_index('start_date', inplace=True) # change index to specified frequency. DEFAULT: 'M' freq = 'M' if freq is None else freq df.index = df.index.to_period(freq) # stats fields to summarize if fields is None: fields = [ 'distance', 'moving_time', 'average_speed', 'average_heartrate', 'max_heartrate', 'average_cadence', 'max_cadence', 'suffer_score', 'total_elevation_gain' ] # rearrange the columns in this order df = df.reindex(columns=fields) # drop the rest of the columns cols_to_drop = [cols for cols in df.columns if cols not in fields] df.drop(cols_to_drop, axis=1, inplace=True) # perform the aggregations df = df.groupby(df.index).agg(['count', 'sum', 'mean', 'max']) # keep only one version of `count` df.insert(0, 'count', df['distance', 'count']) df.drop('count', axis=1, level=1, inplace=True) # drop MultiIndex -- dropping individual cols is too confusing df.columns = [ ('_'.join([c1, c2])) for c1, c2 in \ zip(df.columns.get_level_values(level=0), df.columns.get_level_values(level=1)) ] # remove some agg columns that don't make sense. e.g., `sum` of `average_cadence` df.drop( [ 'average_cadence_sum', 'average_heartrate_sum', 'max_heartrate_sum', 'average_speed_sum', #'max_speed_sum', 'suffer_score_sum', 'total_elevation_gain_mean' ], axis=1, inplace=True) self.summary_df = df.sort_index(ascending=False)
def query_avarage(what, arn=None, finnish_state=None, application=None): session = Session() query = session.query(func.avg(getattr(Execution, what)).label('average')) if arn is not None: query = query.filter(Execution.function == arn) if finnish_state is not None: query = query.filter(Execution.finnish_state == finnish_state) if application is not None: query = query.filter(Execution.application == application) return query.first()[0]
def index(request): if request.session['user_id'] == None: return HTTPFound(location='/admin') session = Session() latest_posts = session.query(Post).order_by(desc( Post.created_at)).limit(5).all() return dict(status='ok', view_path=c_view_paths['admin'], latest_posts=latest_posts)
def profile_image(userid): session = Session() try: prof = get_detail_user_profile(session, userid) fp = os.path.join(app.config['UPLOAD_FOLDER'], prof.userid + '_' + prof.image) return send_file(fp, mimetype='image/png') except Exception as ex: session.rollback() raise ex
def index_view(): session = Session() tournaments = session.query(Tournament).order_by( Tournament.id.desc()).all() players = session.query(Player).order_by(Player.name.asc()).all() admin = request.args.get('admin', '') == 'True' return render_template('tournaments/index.html', admin=admin, tournaments=tournaments, players=players)
def create_insert_object_from_model(model, artifactObject): session = Session() session.add(artifactObject) session.commit() artifactID = artifactObject.id artifact = session.query(model).get(artifactObject.id) arttifactID1 = artifact.id session.close() assert arttifactID1 == artifactID
def __init__(self) -> None: super().__init__() session = Session() session.flush() years = session.query(Tournament.year).distinct().all() years = [x[0] for x in years] years.append(None) for year in years: self.rankings[year] = Ranking(year)
def delete_video(self, file): shutil.rmtree(f"hls/{file.file_id}") session = Session() session.delete(file) session.commit() Session.remove()
def get_parent_child_data(iValue="", iUUID=""): ret_list = "" session = Session() try: if gv._DEBUG: print("f(x) get_parent_child_data: PULLING UUID:VALUE: [{}]:[{}]". format(iUUID, iValue)) if iValue == "all": # query = "select uuid from mp_parent_child_by_uuid" ret_list = session.query(md.ParentChildByUuid). \ with_entities(md.ParentChildByUuid.uuid). \ all() return md.ParentChildByUuidSchema(many=True).dump(ret_list) elif iValue == "actor" or iValue == "family" or iValue == "path" or iValue == "malware": # query = "select uuid from mp_parent_child_by_uuid where mytype = ? order by path asc" # value = (iValue.upper(),) ret_list = session.query(md.ParentChildByUuid). \ with_entities(md.ParentChildByUuid.uuid). \ filter(md.ParentChildByUuid.mytype == iValue.upper()). \ order_by(md.ParentChildByUuid.path). \ all() return md.ParentChildByUuidSchema(many=True).dump(ret_list) elif iValue == "" and iUUID != "": # query = "select * from mp_parent_child_by_uuid where uuid = ?" # value = (iUUID,) # ret_val = cursor.fetchone() ret_list = ret_list = session.query(md.ParentChildByUuid). \ filter(md.ParentChildByUuid.uuid == iUUID). \ first() return md.ParentChildByUuidSchema(many=False).dump(ret_list) elif iValue != "" and iUUID == "": # query = "select * from mp_parent_child_by_uuid where name = ?" # ret_val = cursor.fetchone() ret_list = session.query(md.ParentChildByUuid). \ filter(md.ParentChildByUuid.name == iValue). \ first() return md.ParentChildByUuidSchema(many=False).dump(ret_list) elif iValue != "" and iUUID != "": # query = "select * from mp_parent_child_by_uuid where name = ? or uuid = ?" # value = (iValue, iUUID) # ret_val = cursor.fetchone() ret_list = session.query(md.ParentChildByUuid). \ filter(sa.or_(md.ParentChildByUuid.name == iValue, md.ParentChildByUuid.uuid == iUUID)). \ first() return md.ParentChildByUuidSchema(many=False).dump(ret_list) else: return {} except Exception as error: print("f(x) get_parent_child_data: DATABASE ERROR: {}".format(error)) sys.exit(error) finally: session.close()
def import_data(file_path, creator_id, task_handle): update_status(task_handle, 'Parsing iCal file') file = open(file_path, 'rb') calendar = Calendar.from_ical(file.read()) update_status(task_handle, 'Processing event') event = Event() if 'X-WR-CALNAME' in calendar: event.name = get_valid_event_name(calendar.decoded('X-WR-CALNAME')) if not event.name and 'X-WR-CALDESC' in calendar: event.name = get_valid_event_name(calendar.decoded('X-WR-CALDESC')) for session in calendar.walk('vevent'): if not event.name: event.name = get_valid_event_name(session.decoded('UID')) start_time = session.decoded('dtstart') end_time = session.decoded('dtend') if not event.start_time or start_time < event.start_time: event.start_time = start_time if not event.end_time or end_time > event.end_time: event.end_time = end_time if not event.name: event.name = 'Un-named Event' # Event name set if 'X-WR-TIMEZONE' in calendar: event.timezone = calendar.decoded('X-WR-TIMEZONE') event.has_session_speakers = True event.state = 'Published' event.privacy = 'public' db.session.add(event) update_status(task_handle, 'Adding sessions') for session_block in calendar.walk('vevent'): track_id = None if 'CATEGORIES' in session_block: categories = session_block['CATEGORIES'] string_to_hash = categories if not hasattr(categories, '__iter__') else categories[0] seed = int('100'.join(list(str(ord(character)) for character in string_to_hash))) random.seed(seed) color = "#%06x" % random.randint(0, 0xFFFFFF) track, _ = get_or_create(Track, event_id=event.id, name=string_to_hash, color=color) track_id = track.id microlocation, _ = get_or_create(Microlocation, event_id=event.id, name=session_block.decoded('location')) session = Session() session.track_id = track_id session.microlocation_id = microlocation.id session.title = session_block.decoded('summary') session.short_abstract = session_block.decoded('description') session.start_time = session_block.decoded('dtstart') session.end_time = session_block.decoded('dtend') session.signup_url = session_block.decoded('url') session.event_id = event.id session.state = 'accepted' session.speakers = [] save_to_db(session, 'Session Updated') attendees = [] if 'attendee' in session_block: attendees_dirty = session_block['attendee'] if hasattr(attendees_dirty, '__iter__'): for attendee in attendees_dirty: attendees.append((attendee.params['CN'], attendee)) else: attendees.append((attendees_dirty.params['CN'], attendees_dirty)) for attendee in attendees: speaker = Speaker(name=attendee[0], event_id=event.id, email=attendee[1].replace('MAILTO:', ''), country='Earth', organisation='') db.session.add(speaker) session.speakers.append(speaker) db.session.commit() update_status(task_handle, 'Added session "' + session.title + '"') update_status(task_handle, 'Saving data') save_to_db(event) update_status(task_handle, 'Finalizing') own_event(event=event, user_id=creator_id) return event