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 __init__(self, userid, reciever, origin, destination, weight='1', status='recieved', service_class='standard', category='domestic', current_location='unknown', description='none', charge='0'): self.userid = userid self.reciever = reciever self.origin = origin self.destination = destination self.weight = weight self.status = status self.service_class = service_class self.category = category self.current_location = current_location self.description = description self.charge = charge create_order_table_query = 'CREATE TABLE IF NOT EXISTS orders(\ parcelid serial PRIMARY KEY NOT NULL, userid varchar NOT NULL,\ reciever varchar, origin varchar, destination varchar, weight\ varchar, status varchar, service_class varchar, category varchar,\ current_location varchar, description varchar, charge varchar\ )' cursor.execute(create_order_table_query) db.save()
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 index(): """View function for the home page. If there is form data, check it for validity and create a drop from that data if it's valid.""" form = DropForm() if form.validate_on_submit(): drop = models.Drop() if form.title.data != None and form.title.data != '': drop.title = form.title.data drop.created_at = datetime.datetime.utcnow() drop.data = form.drop_data.data drop.publicly_listed = form.publicly_listed.data drop.expires = form.expires if form.expires_in.data != None: expires_in = pytimeparse.parse(form.expires_in.data) if expires_in != None: drop.expires_in = expires_in else: # the string provided in the post request isn't valid drop.expires_in = app.config['DATADROP_DEFAULT_EXPIRES_IN'] flash( "The given expiration time isn't valid; defaulted to {}.". format(app.config['DATADROP_DEFAULT_EXPIRES_IN'])) drop.self_destructs = form.self_destructs if form.self_destructs_in.data != None: drop.self_destructs_in = form.self_destructs_in.data db.save(drop) # now that the drop is in the database (and has a unique urlstring), redirect the user to it's page return redirect(url_for('show_drop', urlstring=drop.urlstring)) else: # form didn't validate; probably a get request return render_template('index.html', form=form)
def brew(): j = request.get_json(True) if 'brewing' not in j: abort(400) pin.set_state(j['brewing']) t = None if app.BREW_TIMER is not None: app.BREW_TIMER.cancel() if j['brewing']: app.BREW_TIMER = Timer(TIME, stop_brew) app.BREW_TIMER.start() t = datetime.datetime.now().strftime(_TIME_FMT) db.save('brew_time', { 'time': t }) t = 360.0 else: db.delete('brew_time') return jsonify({ 'brewing': j['brewing'], 'time': t })
def dao_add_sprint(metric): metric_exists = db.Session().query(TeamMetric).filter_by( project_id=metric.project_id, sprint_id=str(metric.sprint_id)).first() if metric_exists: return db.save(TeamMetric(**metric.__dict__))
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 create_player(): playername = request.form.get('playername', '') position = request.form.get('position', '') club = request.form.get('club', '') if '' in (playername, position, club): flash("Insufficient information provided to create player") return redirect(url_for('scoring')) else: p = new_player(playername, position, club) db.save(p) return redirect(url_for('players', q=p.get('searchname', '')))
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 modifypost(): """ 修改post信息 :return: """ if request.method == 'POST' and request.is_xhr: data = request.form.to_dict() db = models.Post.query.get(data['id']) db.small = data['small'] db.container = data['container'] db.mtime = datetime.utcnow() db.save() return make_response()
def dao_upsert_sprint(metric): db_metric = db.Session().query(TeamMetric).filter_by( project_id=metric.project_id, sprint_id=str(metric.sprint_id)).first() if db_metric: db.update(TeamMetric, filters={ 'project_id': metric.project_id, 'sprint_id': metric.sprint_id }, **metric.__dict__) else: db.save(TeamMetric(**metric.__dict__))
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 api_create_drop(): """API view function to create a new drop.""" if request.form.get('data') == None: return jsonify( {"error": "You must provide some data when creating a new drop."}), 400 drop = models.Drop() title = request.form.get('title') if title != None and title != '': drop.title = title drop.created_at = datetime.datetime.utcnow() drop.data = request.form.get('data') publicly_listed = request.form.get('publicly_listed', app.config['DATADROP_DEFAULT_LISTED']) drop.publicly_listed = publicly_listed expires = request.form.get('expires', app.config['DATADROP_DEFAULT_EXPIRES']) drop.expires = expires expires_in_string = request.form.get( 'expires_in', app.config['DATADROP_DEFAULT_EXPIRES_IN']) # set the parsed expire time (in seconds); if it's invalid, the default is used drop.expires_in = pytimeparse.parse(expires_in_string) self_destructs = request.form.get( 'self_destructs', app.config['DATADROP_DEFAULT_SELF_DESTRUCTS']) drop.self_destructs = self_destructs self_destructs_in = int( request.form.get('self_destructs_in', app.config['DATADROP_DEFAULT_SELF_DESTRUCTS_IN'])) drop.self_destructs_in = self_destructs_in drop_key_strings = request.form.getlist('drop_keys') if drop_key_strings != None and drop_key_strings != []: # for each drop key that was provided, check if it exists in the database; # if it doesn't, create it drop_keys = [] # a list of key instances for k in drop_key_strings: potential_key = db.DropKey.filter_by(key=k.lower()).one_or_none() if potential_key == None: potential_key = db.save(models.DropKey(key=k.lower())) drop_keys.append(potential_key) drop.drop_keys = drop_keys # to avoid unique urlstring errors made_urlstring = False while made_urlstring == False: u = utils.random_string(app.config['DATADROP_URLSTRING_LENGTH']) if db.Drop.filter_by(urlstring=u).one_or_none() == None: made_urlstring = True drop.urlstring = u db.save(drop) # now build the response r = get_drop_dict(drop, include_drop_keys=True, just_created=True) return jsonify(r), 201
def __init__(self, name, email, password, user_type='user'): self.name = name self.email = email self.password = password # self.tel = tel self.user_type = user_type create_user_table_query = 'CREATE TABLE IF NOT EXISTS users(\ userid SERIAL PRIMARY KEY NOT NULL, name varchar,\ email varchar unique not null, password_hash varchar not null,\ user_type varchar\ )' cursor.execute(create_user_table_query) db.save()
def createpost(): """ 创建post :return: """ if request.method == 'POST' and request.is_xhr: data = request.form.to_dict() db = models.Post(name=data['title']) db.small = data['small'] db.category = data['categoryid'] db.author = g.user.id db.container = data['container'] db.save() return make_response()
def show_raw_drop(urlstring): """Return the drop with the given urlstring (if it exists); this is different from show_drop because it doesn't put the normal datadrop web things around it (headings, navigation, etc).""" drop = db.Drop.filter_by(urlstring=urlstring).one_or_none() if drop != None: drop.views += 1 if drop.self_destructs and drop.views >= drop.self_destructs_in: db.delete(drop) db.commit() else: db.save(drop) # explicitly create the response object here, because the mimetype needs to be text/plain resp = Response(drop.data, mimetype='text/plain') return resp else: return render_template('drop_not_found.html'), 404
def undo_week_scoring(gw): # Clear the scores in the fantasy gameweek for (teamname, lineup) in gw.get('lineups', dict()).iteritems(): for player in lineup: player.update(score=0) for fixture in gw['schedule']: fixture['homescore'] = fixture['awayscore'] = 0 gw.update(scored=False) db.save(gw) # Update the league table and player score totals update_league_table() update_player_scores()
def create_asana_image(asana_uuid, image_url, primary_image=False): asana_image = AsanaImage(uuid=str(uuid4()), asana_uuid=asana_uuid, image_url=image_url, primary_image=primary_image) asana_image = save(asana_image) return asana_image.to_dict()
def create_asana_attribute(asana_uuid, name, value): asana_attribute = AsanaAttribute(uuid=str(uuid4()), asana_uuid=asana_uuid, name=name, value=value) asana_attribute = save(asana_attribute) return asana_attribute.to_dict()
def show_drop(urlstring): """Return a page containing the given drop (if the given urlstring exists).""" # an edge case to handle URLs that have a period on the end (some people don't clean up urls in sentences, imagine that) if urlstring.endswith('.'): urlstring = urlstring[:-1] drop = db.Drop.filter_by(urlstring=urlstring).one_or_none() if drop != None: # a drop with the provided urlstring exists drop.views+=1 if drop.self_destructs and drop.views >= drop.self_destructs_in: db.delete(drop) db.commit() else: db.save(drop) return render_template('drop.html', drop=drop) else: # no drop return render_template('drop_not_found.html'), 404
def dao_upsert_git_metric(metric): db_metric = db.Session().query(GitMetric).filter_by( team_id=metric["team_id"], name=metric["name"], pr_number=metric["pr_number"]).first() if db_metric: db.update(GitMetric, filters={ 'team_id': metric["team_id"], 'name': metric["name"], 'pr_number': metric["pr_number"] }, **metric) else: db.save(GitMetric(**metric))
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 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 transfer_player(): player_id = request.form.get('transferplayer', 0) new_club = request.form.get('newclub', '') if player_id > 0: player = db.get_by_id(player_id) if (player_id == 0) or (not player): flash("Player not found or not specified - please try again") return redirect(url_for('scoring')) elif new_club == '': flash("No club specified - please try again") return redirect(url_for('scoring')) else: if new_club == 'No PL Club': player['club'] = '' else: player['club'] = new_club db.save(player) return redirect(url_for('players', q=player.get('searchname', '')))
def newuser(name, username, password, draftorder=0, token=None): "Create a new user" tokens = [user['token'] for user in db.get('users')] while (token is None) or (token in tokens): token = ''.join( random.choice(string.ascii_lowercase + string.digits) for _ in xrange(20)) user = dict(userid=username, password=generate_password_hash(password), name=name, token=token, wins=0, draws=0, losses=0, points=0, score=0, draftorder=draftorder) db.save(user, 'users')
def do_week_scoring(gw): # 0. Helper function / DRY for the home and away sides later players = dict() def scoreplayer(player, teamgoals, cleansheet): start = 1 * player.get('start', False) finish = 1 * player.get('finish', False) goals = sum([1 for goal in teamgoals if goal['scorer'] and goal['scorer']['_id'] == player['_id']]) assists = sum([1 for goal in teamgoals if goal['assist'] and goal['assist']['_id'] == player['_id']]) cleansheet = 1 * cleansheet cleansheetpoints = dict(G=3, D=2, M=0, F=0)[player.get('position', 'F')] player.update(score=(start + finish + (3 * goals) + (2 * assists) + (cleansheet * cleansheetpoints))) players[player.get('_id', '')] = player # 1. Score the players in the PL fixture (homelineup/awaylineup) for fixture in gw.get('fixtures', []): for player in fixture.get('homelineup', []): scoreplayer(player, fixture.get('homegoals', []), len(fixture.get('awaygoals', [])) == 0) for player in fixture.get('awaylineup', []): scoreplayer(player, fixture.get('awaygoals', []), len(fixture.get('homegoals', [])) == 0) # 2. Copy scores to the players in the fantasy gameweek, total each team during the process scores = dict() for (teamname, lineup) in gw.get('lineups', dict()).iteritems(): for player in lineup: player.update(players.get(player['_id'], dict())) scores[teamname] = scores.get(teamname, 0) + player.get('score', 0) # 3. Update the team score totals in the Fantasy fixtures for fixture in gw['schedule']: fixture['homescore'] = scores.get(fixture['home'], 0) fixture['awayscore'] = scores.get(fixture['away'], 0) # 4. Save the gameweek gw.update(scored=True) db.save(gw) # 5. Update the league table and player score totals update_league_table() update_player_scores()
def changeweek(weekno, action): if action not in ('open', 'close', 'complete', 'activate'): abort(404) gw = db.get('gameweeks', dict(week=weekno)) if gw: gw = gw[0] if action == 'close': do_week_scoring(gw) elif action == 'open': undo_week_scoring(gw) elif action == 'complete': gw['completed'] = True db.save(gw) update_next_fixtures() elif action == 'activate': gw['completed'] = False db.save(gw) update_next_fixtures() return redirect(url_for('scoring'))
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 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 brew(): j = request.get_json(True) if 'brewing' not in j: abort(400) pin.set_state(j['brewing']) t = None if app.BREW_TIMER is not None: app.BREW_TIMER.cancel() if j['brewing']: app.BREW_TIMER = Timer(TIME, stop_brew) app.BREW_TIMER.start() t = datetime.datetime.now().strftime(_TIME_FMT) db.save('brew_time', {'time': t}) t = 360.0 else: db.delete('brew_time') return jsonify({'brewing': j['brewing'], 'time': t})
def create_asana(**kwargs): for field in REQUIRED_FIELDS: if not kwargs.get(field): raise ValueError('%s required' % field) asana = Asana(uuid=str(uuid4()), name=kwargs.pop('name', '')) asana = save(asana) # create image AsanaImage.create_asana_image(asana.uuid, kwargs.get('image_url'), True) # create attributes for name in kwargs.keys(): AsanaAttribute.create_asana_attribute(asana.uuid, name, kwargs.get(name)) return asana.to_dict()
def post(self): values = request.form.items() id = db.save(doc) return_js = {'id':id} return jsonify(return_js)
def dbseed(): with open('signup_form.json') as survey_file: db.save(parsers.survey_from_json(survey_file.read()))
def new_log(self, mood, stress, timestamp=datetime.now()): db.save(Log(timestamp=timestamp, mood=mood, stress=stress, user=self)) self.update()
def post(self): values = request.form.items() id = db.save(doc) return_js = {'id': id} return jsonify(return_js)
def dbseed(): with open('onboarding.json') as onboard_file: db.save(parsers.onboard_from_json(onboard_file.read()))
def change_password(self, newpassword): self.dbuser['password'] = generate_password_hash(newpassword) db.save(self.dbuser)
def add_user(): name = request.values.get('name', None) db.save(User(name)) return create_response({'content': 'user created'})