def merge_list(): named_streams = [] for stream in request.args: stream_name = request.args[stream] if not db.get(stream_name): return {"Error": "Stream {} Doesn't Exist".format(stream_name)} named_streams.append(stream_name) unique_name = ''.join(sorted(named_streams)) merge_doc = db.get('merge') if unique_name in merge_doc: try: current_idx = merge_doc[unique_name]['idx'] m_list = merge_doc[unique_name]['list'] last_stream = None if current_idx > 0: last_stream = m_list[current_idx - 1] m_list = merge_doc[unique_name]['list'] merge_doc[unique_name]['idx'] += 1 db.save(merge_doc) return {"last": last_stream, "current": m_list[current_idx]} except: merge_doc[unique_name]['idx'] = 0 db.save(merge_doc) return {"Warning": "End of Merged List Reached Starting Over"} else: sorted_master = [] for name in named_streams: stream_list = db.get(name)['list'] sorted_master.extend(stream_list) new_sorted_master = sorted(sorted_master) merge_doc[unique_name] = {"list": new_sorted_master, "idx": 1} db.save(merge_doc) return {"last": None, "current": new_sorted_master[0]}
def init_wechat_sdk(): """ 初始化微信sdk :return: WechatBasic """ access_token = db.get("wechat:access_token") jsapi_ticket = db.get("wechat:jsapi_ticket") token_expires_at = db.get("wechat:access_token_expires_at") ticket_expires_at = db.get("wechat:jsapi_ticket_expires_at") if all((access_token, jsapi_ticket, token_expires_at, ticket_expires_at)): wechat = WechatBasic(appid=app.config['APP_ID'], appsecret=app.config['APP_SECRET'], token=app.config['TOKEN'], access_token=access_token, access_token_expires_at=int(token_expires_at), jsapi_ticket=jsapi_ticket, jsapi_ticket_expires_at=int(ticket_expires_at)) else: wechat = WechatBasic(appid=app.config['APP_ID'], appsecret=app.config['APP_SECRET'], token=app.config['TOKEN']) access_token = wechat.get_access_token() db.set("wechat:access_token", access_token['access_token'], 7000) db.set("wechat:access_token_expires_at", access_token['access_token_expires_at'], 7000) jsapi_ticket = wechat.get_jsapi_ticket() db.set("wechat:jsapi_ticket", jsapi_ticket['jsapi_ticket'], 7000) db.set("wechat:jsapi_ticket_expires_at", jsapi_ticket['jsapi_ticket_expires_at'], 7000) return wechat
def scoring(): gameweeks = sorted(db.get('gameweeks'), key=lambda gw: gw['week']) for gw in gameweeks: gw['deadline'] = decode_iso_datetime(gw['deadline']) gw['conclusion'] = decode_iso_datetime(gw['conclusion']) clubs = sorted(db.get('clubs'), key=lambda club: club['name']) teams = sorted(db.get('users'), key=lambda user: user['name']) return render_template('scoring.html', activepage="scoring", gameweeks=gameweeks, clubs=clubs, teams=teams)
def waiver_claims(): cgw = current_gameweek() wgw = waiver_gameweek() print 'cgw %s' % cgw['week'] print 'wgw %s' % wgw['week'] view = request.args.get('view', 'own') if current_user.get_id() is None: view = 'league' current_claims = sorted([ claim for claim in db.get( 'claims', dict(user=current_user.get_id(), week=wgw['week'])) ], key=lambda claim: claim['priority']) if cgw['week'] == wgw['week']: week = int(request.args.get('week', cgw['week'] - 1)) else: week = int(request.args.get('week', cgw['week'])) claimquery = dict(week=week) tradequery = dict(week=week) if view == 'league': claimquery.update(status='success') else: # view == 'own' or somehow still omitted at this point claimquery.update(user=current_user.get_id()) prev_claims = sorted(db.get('claims', claimquery), key=lambda claim: (claim.get('order', 100), claim['priority'])) trades = db.get('trades', tradequery) if view != 'league': trades = [ trade for trade in trades if current_user.get_id() in (trade['first']['userid'], trade['second']['userid']) ] return render_template('waivers.html', activepage='waivers', current_claims=current_claims, prev_claims=prev_claims, trades=trades, current_claim_count=len(current_claims), week_pagination=week_pagination(week), waiver_deadline=wgw['waiver'], view=view)
def update_facebook_comments(url, entity_uuid): access_token = get(User, email='*****@*****.**').code graph = facebook.GraphAPI(access_token) post_response = graph.get_object('me/posts') comments = [] counter = 0 while post_response.get('paging', {}).get('next') is not None: for post in post_response['data']: if url in post.get('message', ''): comment_response = graph.request('{}/comments'.format( post.get('id'))) comments = comments + comment_response.get('data') while comment_response.get('paging', {}).get('next') is not None: after = comment_response.get('paging', {}).get('cursors', {}).get('after') comment_response = graph.request( '{}/comments'.format(post.get('id')), {'after': after}) comments = comments + comment_response.get('data') link = "https://www.facebook.com/photo.php?fbid={}".format( post.get('id').split('_')[0]) comments = [ process_fb_comment(comment, link, graph) for comment in comments ] for comment in comments: Comment.add_or_update(comment.get('id'), entity_uuid, comment) return comments if counter > 10: return [] post_response = requests.get( post_response.get('paging', {}).get('next')).json()
def scorefixture(weekno, fixtureno): gw = db.get('gameweeks', dict(week=weekno)) if len(gw) == 0: flash("Gameweek %s not found" % weekno) return redirect(url_for('scoring')) else: gw = gw[0] if gw['scored']: flash("Scoring for gameweek %s is not open. Please re-open scoring for this week first." % weekno) return redirect(url_for('scoring')) else: try: fixture = gw['fixtures'][fixtureno - 1] except IndexError: flash("Fixture %s not found in the week %s." % (fixtureno, weekno)) return redirect(url_for('scoring')) if request.method == 'POST': players = get_fixture_players(fixture) homegoals = goals_from_scorefixture_form(request.form, 'home', players) awaygoals = goals_from_scorefixture_form(request.form, 'away', players) fixture.update(homelineup=lineup_from_scorefixture_form(request.form, 'home', players), awaylineup=lineup_from_scorefixture_form(request.form, 'away', players), homegoals=homegoals, homescore=len(homegoals), awaygoals=awaygoals, awayscore=len(awaygoals)) db.save(gw) return render_template('scorefixture.html', activepage="scoring", gameweek=gw, fixture=fixture, weekno=weekno, fixtureno=fixtureno)
def viewscore(weekno, fixtureno): gw = db.get('gameweeks', dict(week=weekno)) if len(gw) == 0: abort(404) else: gw = gw[0] if not gw.get('scored', False): abort(404) else: try: fixture = gw.get('schedule', [])[fixtureno - 1] except IndexError: abort(404) homelineup = sorted(gw.get('lineups', dict()).get(fixture.get('home', ''), []), key=sort_player) awaylineup = sorted(gw.get('lineups', dict()).get(fixture.get('away', ''), []), key=sort_player) return render_template('fixture.html', activepage='schedule', gameweek=gw, fixture=fixture, homelineup=homelineup, awaylineup=awaylineup)
def trade(team1, team2): team1, team2 = db.get_by_id(team1), db.get_by_id(team2) if (not team1) or (not team2): abort(404) if request.method == 'POST': cgw = current_gameweek() players = dict([(unicode(player['_id']), player) for player in db.get('players')]) firstplayer = [players.get(player) for player in request.form.getlist('firstplayer')] secondplayer = [players.get(player) for player in request.form.getlist('secondplayer')] for player in firstplayer: player['team'] = team2['name'] for player in secondplayer: player['team'] = team1['name'] trade = dict( week=cgw['week'], firstplayer=firstplayer, secondplayer=secondplayer, first=team1, second=team2) db.save_all(firstplayer + secondplayer) db.save(trade, 'trades') return redirect(url_for('scoring')) else: return render_template('trade.html', activepage="scoring", team1=team1, team2=team2)
def get_verified_user(email, password): user = get(User, email=email) if user: verified = authenticate_password(password, user.password_hash.encode('utf-8')) if verified: return user return None
def edit_advisory(advisory_id): advisory = db.get(Advisory, id=advisory_id) if not advisory: return not_found() form = AdvisoryEditForm(advisory.id) if not form.is_submitted(): form.workaround.data = advisory.workaround form.impact.data = advisory.impact form.reference.data = advisory.reference if not advisory.reference and Publication.published == advisory.publication: form.reference.data = advisory_fetch_reference_url_from_mailman( advisory) if not form.validate_on_submit(): if advisory.reference: flash(WARNING_ADVISORY_ALREADY_PUBLISHED, 'warning') return render_template('form/advisory.html', title='Edit {}'.format(advisory.id), Advisory=Advisory, form=form) advisory.impact = form.impact.data or None advisory.workaround = form.workaround.data or None if advisory.reference != form.reference.data: advisory.content = form.advisory_content advisory_extend_model_from_advisory_text(advisory) advisory.reference = form.reference.data or None db.session.commit() flash('Edited {}'.format(advisory.id)) return redirect('/{}'.format(advisory.id))
def update_waiver_order(): try: priorities = [int(prio) for prio in request.form.get('priorities', '').split(',')] except ValueError: priorities = [] wgw = waiver_gameweek() if datetime.now() >= wgw['waiver']: flash("The deadline for waivers this week has passed. You can no longer edit your claims.") else: current_claims = sorted(db.get('claims', dict(user=current_user.get_id(), week=wgw['week'])), key=lambda claim: claim['priority']) deleted_claims = [] for (n, claim) in enumerate(current_claims): try: claim['priority'] = priorities.index(n + 1) except ValueError: deleted_claims.append(claim) db.save_all([claim for claim in current_claims if claim not in deleted_claims]) for claim in deleted_claims: db.delete(claim) return redirect(url_for('waiver_claims'))
def get_teams(reverse=False): rv = sorted(db.get('users'), key=lambda user: (-user.get('points', 0), -user.get('score', 0), -user.get('tiebreak', 0), user.get('draftorder', 0))) if reverse: rv = reversed(rv) return list(rv)
def get_whois_ip(ip): """docstring for get_whois_ip""" res = db.get(REDIS_KEY_IP % ip) if res: return res else: return get_real_whois_ip(ip)
def load_user(userid): try: dbuser = db.get('users', {'userid': userid})[0] except IndexError: return None return User(dbuser)
def to_dict(self): # get images images = AsanaImage.get_asana_images(self.uuid) # get attributes attributes = AsanaAttribute.get_asana_attributes(self.uuid) print self.created_at data = {'uuid': self.uuid, 'name': self.name, 'created_ago': relative_time(self.created_at), 'created_at': format_date(self.created_at, format='%B %d, %Y'), 'image_url': get(AsanaImage, asana_uuid=self.uuid, primary_image=True).image_url, 'images': images, 'description': get(AsanaAttribute, asana_uuid=self.uuid, name='description').value, 'attributes': attributes } return data
def get_player(name): try: return db.get( 'players', {'searchname': _contains(unidecode(unicode(name.lower())))})[0] except IndexError: return None
def team(userid): user = load_user(userid) if not user: abort(404) players = get_lineup(user.get_name()) cgw = current_gameweek() claims = db.get('claims', {'user': userid}) if cgw['waiver'] < datetime.now(): recent_changes = sorted([ claim for claim in claims if (claim['week'] == cgw['week'] and claim['status'] == 'success') ], key=lambda claim: claim['priority']) else: recent_changes = sorted([ claim for claim in claims if (claim['week'] == (cgw['week'] - 1) and claim['status'] == 'success') ], key=lambda claim: claim['priority']) return render_template('team.html', players=players, activepage='team', user=user, next_opponents=next_opponents(), recent_changes=recent_changes)
def update_waiver_order(): try: priorities = [ int(prio) for prio in request.form.get('priorities', '').split(',') ] except ValueError: priorities = [] wgw = waiver_gameweek() if datetime.now() >= wgw['waiver']: flash( "The deadline for waivers this week has passed. You can no longer edit your claims." ) else: current_claims = sorted(db.get( 'claims', dict(user=current_user.get_id(), week=wgw['week'])), key=lambda claim: claim['priority']) deleted_claims = [] for (n, claim) in enumerate(current_claims): try: claim['priority'] = priorities.index(n + 1) except ValueError: deleted_claims.append(claim) db.save_all( [claim for claim in current_claims if claim not in deleted_claims]) for claim in deleted_claims: db.delete(claim) return redirect(url_for('waiver_claims'))
def get_wechat_access_token(): """获取 access_token""" access_token = db.get("wechat:access_token") if access_token: return access_token else: app.logger.warning(u"获取 access_token 缓存失败") return None
def reaction_detail(slug): entry = db.get('reaction', dict(slug=slug)) if not entry: abort(404) else: return render_template('reactiondetail.html', activepage='reaction', entry=entry[0])
def json_club_players(clubid): query = request.args.get('q', '').lower() club = db.get_by_id(clubid) players = sorted(db.get('players', {'club': club['name'], 'searchname': lambda sn: (query in sn)}), key=sort_player) return jsonify({'players': [dict(id=player['_id'], text='%s %s' % (player['position'], player['name'])) for player in players]})
def json_team_players(teamid): query = request.args.get('q', '') team = db.get_by_id(teamid) players = sorted(db.get('players', {'team': team['name'], 'searchname': lambda sn: (query in sn)}), key=sort_player) return jsonify({'players': [dict(id=player['_id'], text='%s %s' % (player['position'], player['name'])) for player in players]})
def schedule(): gameweeks = db.get('gameweeks') cgw = current_gameweek() gw = int(request.args.get('week', cgw['week'])) pagin = pagination(gw, len(gameweeks)) gameweek = gameweeks[gw - 1] return render_template('schedule.html', activepage="schedule", gameweek=gameweek, pagination=pagin)
def update_next_fixtures(): clubs = dict([(c['_id'], c) for c in db.get('clubs')]) fixtures = current_gameweek()['fixtures'] for fixture in fixtures: clubs[fixture['home']['_id']]['nextopponent'] = '%s (H)' % fixture['away']['name'] clubs[fixture['away']['_id']]['nextopponent'] = '%s (A)' % fixture['home']['name'] db.save_all(clubs.values())
def run_inceptionV3(): """ Run the pre-trained base Inception V3 model and send image to queue Listening user submitted images and stack them in a Redis queue """ data = {"success": False} # load model name model_name = request.form.get('model_name') # load and pre-processing image img = request.files['image'] img = image.load_img(img, target_size = (299, 299)) x = np.expand_dims(image.img_to_array(img), axis=0) x = preprocess_input(x) x = x.copy(order="C") # encode x = API_helpers.base64_encode_image(x) # create a image id this_id = str(uuid.uuid4()) d = {"id": this_id, "image": x, "model_name": model_name} # push to the redis queue db.rpush(INCEPTIONV3_IMAGE_QUEUE, json.dumps(d)) while True: # check if the response has been returned output = db.get(this_id) if output is not None: output = output.decode('utf-8') data["prediction"] = json.loads(output) db.delete(this_id) break else: # print "* Waiting for the Inference Server..." time.sleep(CLIENT_SLEEP) data['success'] = True return jsonify({ "data": data }), 200
def complete_gameweeks(): changedweeks = [] for gw in db.get('gameweeks'): conclusion = datetime.strptime(gw['conclusion'], '%Y-%m-%dT%H:%M:%S') if (not gw.get('completed', False)) and conclusion < datetime.now(): gw['completed'] = True changedweeks.append(gw) if changedweeks: db.save_all(changedweeks) update_next_fixtures()
def get_whois_domain(domain): """docstring for get_whois_domain""" res = db.get(REDIS_KEY_DOMAIN % domain.registered_domain) if res: thread = threading.Thread(target=get_real_whois_domain, args=[domain]) thread.daemon = True tasks.put(thread) return res else: return get_real_whois_domain(domain)
def get(cls, ip): if not db.sismember("ips", ip): raise NotFound("IP address %s not registered" % ip) db_values = db.get("ip:%s" % ip) if not db_values: raise NotFound("IP address %s not registered" % ip) ip_info = json.loads(db_values) return cls(ip=ip, created=ip_info["created"])
def create_user(email, password_hash): role = 0 if get(User, email=email): raise Exception('A User with that email has already been created.') user = User(uuid=str(uuid4()), email=email, role=role, password_hash=password_hash, email_verification_token=str(uuid4())) save(user)
def record_lineups(): cgw = current_gameweek() if (cgw['deadline'] < datetime.now()) and (not cgw['conclusion'] < datetime.now()): lineups = db.get('players', dict(startingxi='1')) teams = set(p['team'] for p in lineups) cgw['lineups'] = dict() for team in teams: cgw['lineups'][team] = [player for player in lineups if player['team'] == team] db.save(cgw)
def players(): query = unidecode(unicode(request.args.get('q', '').lower())) pos = request.args.get('p', '').upper() if pos not in ('G', 'D', 'M', 'F', ''): pos = '' sorttype = request.args.get('s', 'score').lower() if sorttype not in ('score', 'form'): sorttype = 'score' filt = request.args.get('f', 'all') if filt not in ('all', 'free'): filt = 'all' def search(playername): return (query == '') or (query in playername) def status(team): return (filt == 'all') or (team == '') sort = dict(score=sort_player_score, form=sort_player_form)[sorttype] players = sorted(db.get( 'players', { 'position': lambda x: pos in x, 'searchname': search, 'club': lambda x: x != '', 'team': status }), key=sort) pages = int(ceil(len(players) / 15.0)) page = int(request.args.get('pg', 1)) pagin = pagination(page, pages) players = players[((page - 1) * 15):(page * 15)] gw_now = current_gameweek() for player in players: player['waiver'] = waiver_status(player, gw_now['week'], gw_now['deadline'], gw_now['waiver'], next_gameweek()['waiver']) return render_template('players.html', activepage="players", pagination=pagin, players=players, query=query, pos=pos, sorttype=sorttype, filt=filt)
def dcf_valuation(*args, **kwargs): if not args[0]: return [], [], [], dash.no_update try: df_dict = args[0] live_analysis_mode = args[-2] snapshot_uuid = args[-1] ticker = list(df_dict.keys())[0] dcf_store_dict_json = db.get(ticker + '-' + snapshot_uuid) dcf_store_dict = json.loads( dcf_store_dict_json) if dcf_store_dict_json else None safe_get_dcf = dcf_store_dict.get(ticker).get( 'dcf_df_dict') if dcf_store_dict else None if 1 in live_analysis_mode or not safe_get_dcf: dcf_df, dcf_output_dict = get_dcf_df(*args) else: dcf_df = pd.DataFrame.from_dict(safe_get_dcf) dcf_output_dict = dcf_store_dict[ticker]['dcf_output_dict'] # Capture all inputs to dcf-store.data ctx = dash.callback_context dcf_store_dict = ctx.inputs.pop('fin-store.data') for k, v in ctx.inputs.items(): dcf_store_dict[ticker][k] = v dcf_store_dict[ticker]['dcf_df_dict'] = dcf_df.to_dict('records') dcf_store_dict[ticker]['dcf_output_dict'] = dcf_output_dict dcf_output_df = pd.DataFrame({ 'Price': [dcf_output_dict['last_price']], 'Value': ['{:.2f}'.format(dcf_output_dict['estimated_value_per_share'])], 'Price as % of Value': [ '{:.2f}'.format(100 * dcf_output_dict['last_price'] / dcf_output_dict['estimated_value_per_share']) ], 'PV Total': [get_string_from_number(dcf_output_dict['PV_sum'])], 'PV Terminal Value': [get_string_from_number(dcf_output_dict['PV_terminal_value'])], }) return dcf_store_dict, make_table('dcf-df', dcf_df), dbc.Table.from_dataframe( dcf_output_df, striped=True, bordered=True, hover=True), dash.no_update except TypeError as e: logger.exception(e) return [], [], replace_str_element_w_dash_component( traceback.format_exc()), handler_data_message( 'See Error Message(s) in DCF outputs:', '') except Exception as e: logger.exception(e) raise PreventUpdate
def json_all_players(): query = request.args.get('q', '') players = sorted(db.get('players', {'searchname': lambda sn: (query in sn)}), key=sort_player) return jsonify({ 'players': [ dict(id=player['_id'], text='%s %s' % (player['position'], player['name'])) for player in players ] })
def scoreweek(weekno): gw = db.get('gameweeks', dict(week=weekno)) if len(gw) == 0: flash("Gameweek %s not found" % weekno) return redirect(url_for('scoring')) else: gw = gw[0] if gw['scored']: flash("Scoring for gameweek %s is not open. Please re-open scoring for this week first." % weekno) return redirect(url_for('scoring')) else: return render_template('scoreweek.html', activepage="scoring", gameweek=gw)
def begin_trade(): teamnames = (request.form.get('team1', ''), request.form.get('team2', '')) if len([teamname for teamname in set(teamnames) if teamname != '']) != 2: flash("Did not find two unique team names to begin the trade - please try again") return redirect(url_for('scoring')) else: teams = db.get('users', dict(name=lambda name: name in teamnames)) if len(teams) != 2: flash("Could not find two users matching the usernames provided - please try again") return redirect(url_for('scoring')) else: return redirect(url_for('trade', team1=teams[0]['_id'], team2=teams[1]['_id']))
def add_waiver_claim(user, username, week, add, drop, status=''): claims = db.get('claims', dict(user=user, week=week)) existing = [(c['add']['_id'], c['drop']['_id']) for c in claims] if not ((add['_id'], drop['_id']) in existing): try: priority = max(claim['priority'] for claim in claims) + 1 except ValueError: priority = 1 document = dict(user=user, username=username, week=week, priority=priority, add=add, drop=drop, status=status) db.save(document, collection='claims')
def update_player_scores(): players = dict([(p['_id'], p) for p in db.get('players')]) gameweeks = db.get('gameweeks', dict(scored=True)) recent = sorted(gw['week'] for gw in gameweeks)[-4:] for player in players.values(): player.pop('totalscore', None) player['form'] = [0] * len(recent) for gw in gameweeks: for result in gw.get('fixtures', []): for player in (result.get('homelineup', []) + result.get('awaylineup', [])): dbplayer = players.get(player.get('_id', '')) if dbplayer: dbplayer.update(totalscore=(dbplayer.get('totalscore', 0) + player.get('score', 0))) try: dbplayer['form'][recent.index(gw['week'])] = player.get('score', 0) except ValueError: pass db.save_all(players.values())
def current_gameweek(): weeks = sorted(db.get('gameweeks'), key=lambda gw: gw['week']) incomplete_weeks = [week for week in weeks if week['completed'] == False] if len(incomplete_weeks) == 0: rv = weeks[-1] for datetype in ('deadline', 'waiver', 'conclusion'): rv[datetype] = decode_iso_datetime(rv[datetype]) + timedelta(weeks=1) else: rv = incomplete_weeks[0] for datetype in ('deadline', 'waiver', 'conclusion'): rv[datetype] = decode_iso_datetime(rv[datetype]) return rv
def __init__(self, token=''): """Always create network""" with shelve.open('lastfm') as db: session_key = db.get('session_key') self.network = LastFMNetwork(api_key=self.API_KEY, api_secret=self.API_SECRET, session_key=session_key, token=token) if token: app.logger.info('saving session key: {}'.format( self.network.session_key)) db['session_key'] = self.network.session_key
def waiver_claims(): cgw = current_gameweek() wgw = waiver_gameweek() print 'cgw %s' % cgw['week'] print 'wgw %s' % wgw['week'] view = request.args.get('view', 'own') if current_user.get_id() is None: view = 'league' current_claims = sorted([claim for claim in db.get('claims', dict(user=current_user.get_id(), week=wgw['week']))], key=lambda claim: claim['priority']) if cgw['week'] == wgw['week']: week = int(request.args.get('week', cgw['week'] - 1)) else: week = int(request.args.get('week', cgw['week'])) claimquery = dict(week=week) tradequery = dict(week=week) if view == 'league': claimquery.update(status='success') else: # view == 'own' or somehow still omitted at this point claimquery.update(user=current_user.get_id()) prev_claims = sorted(db.get('claims', claimquery), key=lambda claim: (claim.get('order', 100), claim['priority'])) trades = db.get('trades', tradequery) if view != 'league': trades = [trade for trade in trades if current_user.get_id() in (trade['first']['userid'], trade['second']['userid'])] return render_template('waivers.html', activepage='waivers', current_claims=current_claims, prev_claims=prev_claims, trades=trades, current_claim_count=len(current_claims), week_pagination=week_pagination(week), waiver_deadline=wgw['waiver'], view=view)
def __init__(self, token=''): """Always create network""" with shelve.open('lastfm') as db: session_key = db.get('session_key') self.network = LastFMNetwork( api_key=self.API_KEY, api_secret=self.API_SECRET, session_key=session_key, token=token ) if token: app.logger.info('saving session key: {}'.format(self.network.session_key)) db['session_key'] = self.network.session_key
def update_league_table(): teams = db.get('users') results = [] for gw in db.get('gameweeks', dict(scored=True)): for result in gw.get('schedule', []): homeresult = dict(team=result.get('home', ''), score=int(result.get('homescore', 0))) awayresult = dict(team=result.get('away', ''), score=int(result.get('awayscore', 0))) homeresult['win'] = awayresult['loss'] = 1 * (homeresult.get('score', 0) > awayresult.get('score', 0)) awayresult['win'] = homeresult['loss'] = 1 * (awayresult.get('score', 0) > homeresult.get('score', 0)) homeresult['draw'] = awayresult['draw'] = 1 * (homeresult.get('score', 0) == awayresult.get('score', 0)) results.append(homeresult) results.append(awayresult) for team in teams: team['wins'] = sum([result.get('win', 0) for result in results if result.get('team', '') == team.get('name', '')]) team['losses'] = sum([result.get('loss', 0) for result in results if result.get('team', '') == team.get('name', '')]) team['draws'] = sum([result.get('draw', 0) for result in results if result.get('team', '') == team.get('name', '')]) team['points'] = (team['wins'] * 2) + team['draws'] team['score'] = sum([result.get('score', 0) for result in results if result.get('team', '') == team.get('name', '')]) db.save_all(teams)
def scoreweek(weekno): gw = db.get('gameweeks', dict(week=weekno)) if len(gw) == 0: flash("Gameweek %s not found" % weekno) return redirect(url_for('scoring')) else: gw = gw[0] if gw['scored']: flash( "Scoring for gameweek %s is not open. Please re-open scoring for this week first." % weekno) return redirect(url_for('scoring')) else: return render_template('scoreweek.html', activepage="scoring", gameweek=gw)
def stream_list(stream): choice = stream.capitalize() choice_doc = db.get(choice) try: current_idx = choice_doc["idx"] last_stream = None if current_idx > 0: last_stream = choice_doc["list"][current_idx - 1] current_stream = choice_doc["list"][current_idx] choice_doc["idx"] += 1 db.save(choice_doc) except: choice_doc["idx"] = 0 db.save(choice_doc) return {"Warning": "End of List Reached Reseting Counter"} return {"last": last_stream, "current": current_stream, "stream": choice}
def begin_trade(): teamnames = (request.form.get('team1', ''), request.form.get('team2', '')) if len([teamname for teamname in set(teamnames) if teamname != '']) != 2: flash( "Did not find two unique team names to begin the trade - please try again" ) return redirect(url_for('scoring')) else: teams = db.get('users', dict(name=lambda name: name in teamnames)) if len(teams) != 2: flash( "Could not find two users matching the usernames provided - please try again" ) return redirect(url_for('scoring')) else: return redirect( url_for('trade', team1=teams[0]['_id'], team2=teams[1]['_id']))
def json_club_players(clubid): query = request.args.get('q', '').lower() club = db.get_by_id(clubid) players = sorted(db.get( 'players', { 'club': club['name'], 'searchname': lambda sn: (query in sn) }), key=sort_player) return jsonify({ 'players': [ dict(id=player['_id'], text='%s %s' % (player['position'], player['name'])) for player in players ] })
def scorefixture(weekno, fixtureno): gw = db.get('gameweeks', dict(week=weekno)) if len(gw) == 0: flash("Gameweek %s not found" % weekno) return redirect(url_for('scoring')) else: gw = gw[0] if gw['scored']: flash( "Scoring for gameweek %s is not open. Please re-open scoring for this week first." % weekno) return redirect(url_for('scoring')) else: try: fixture = gw['fixtures'][fixtureno - 1] except IndexError: flash("Fixture %s not found in the week %s." % (fixtureno, weekno)) return redirect(url_for('scoring')) if request.method == 'POST': players = get_fixture_players(fixture) homegoals = goals_from_scorefixture_form( request.form, 'home', players) awaygoals = goals_from_scorefixture_form( request.form, 'away', players) fixture.update(homelineup=lineup_from_scorefixture_form( request.form, 'home', players), awaylineup=lineup_from_scorefixture_form( request.form, 'away', players), homegoals=homegoals, homescore=len(homegoals), awaygoals=awaygoals, awayscore=len(awaygoals)) db.save(gw) return render_template('scorefixture.html', activepage="scoring", gameweek=gw, fixture=fixture, weekno=weekno, fixtureno=fixtureno)
def post(self): """ http -F POST :5000/api/v01/login [email protected] password="******" http -F POST :5000/api/v01/register [email protected] password="******" """ data = request.json or {} # mandatory fields errs = check_mandatory_fields(data, ["email", "password"]) if errs: return make_response(jsonify(errs), 422) endpointUsed = re.sub("^.*?([^/]*)$", r"\1", request.path) # login if (endpointUsed == "login"): # verify if email exists in db uid = db.get("z:usersByEmail:{email}".format(email=data["email"])) user = db.hgetall("z:users:{uid}".format(uid=uid)) if uid else {} # verify email/password if user and sha256.verify(data["password"], user["password"]): return self.login(uid, user) else: return self.response("wrong creds") # register else: # verify email by simple validation for now # https://www.scottbrady91.com/Email-Verification/Python-Email-Verification-Script match = re.match( "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", data["email"]) if match == None: return self.response("wrong format", "email") dataFiltered = filter_dict(data, self.exposedFields) dataFiltered["password"] = sha256.hash(data["password"]) dataFiltered["uid"] = uuid.uuid4() ret = db.replaceOrInsertUser(args=dict2list(dataFiltered)).lower() if ret == "ok": return self.login(dataFiltered["uid"]) else: return self.response(*ret.split(":"))
def update_gallery(uuid, **kwargs): gallery = get(Gallery, uuid=uuid) if not gallery.published and kwargs.get('published', False): kwargs['published_at'] = datetime.datetime.utcnow() gallery = update(gallery, kwargs) current_items = [item.get('uuid') for item in kwargs.get('items', [])] item_list = get_list(GalleryItem, gallery_uuid=gallery.uuid) delete_items = [item.uuid for item in item_list if item.uuid not in current_items] for uuid in delete_items: GalleryItem.delete(uuid) for item in kwargs.get('items', []): if item.get('uuid'): GalleryItem.update(uuid=item.pop('uuid'), **item) else: item['gallery_uuid'] = gallery.uuid GalleryItem.add_item(**item) return gallery.to_dict()