def index(): cu='' if len(session.keys())!=0: cu=session[session.keys()[0]] else: cu='guest' return render_template("index.html", current_user=cu)
def kaltura_session_loader_base(kaltura_id, app, session, return_status=False): # Refresh Kaltura Session If not print "Current in session" + repr(session) if "ksessionkey" in session and session['kaltura_id'] == kaltura_id: print session.keys() print "I already have session" return create_session(kaltura_id, session["ksessionkey"]) else: # if True: try: session['kaltura_id'] = kaltura_id kaltura_count = int(os.environ.get("KALTURA_INSTANCES", "1")) if kaltura_count >= 1: settings = properties.load_kaltura_settings().get(kaltura_id) session["ksessionkey"] = get_new_session_key(settings) else: settings = properties.load_kaltura_settings() session["ksessionkey"] = get_new_session_key(settings) return create_session(kaltura_id, session["ksessionkey"]) except Exception as inst: inst = Exception # Error in Initiating session against Kaltura Server Session app.logger.warn(repr(inst)) type, value, traceback = sys.exc_info() app.logger.warn(type) app.logger.warn(value) app.logger.warn(traceback) return "Unexpected error:" + "<p>" + repr(sys.exc_info()) + \ "</p>" if return_status else False
def user_profile(username=''): if len(session.keys())!=0: user=session[session.keys()[0]] else: user='' posts = utils.finduserposts(username) return render_template("profile.html", username=username, user=user, posts=posts)
def test_source_is_deleted_while_logged_in(self, logger): """If a source is deleted by a journalist when they are logged in, a NoResultFound will occur. The source should be redirected to the index when this happens, and a warning logged.""" with self.client as client: codename = new_codename(client, session) resp = client.post('login', data=dict(codename=codename), follow_redirects=True) # Now the journalist deletes the source filesystem_id = crypto_util.hash_codename(codename) crypto_util.delete_reply_keypair(filesystem_id) source = Source.query.filter_by(filesystem_id=filesystem_id).one() db_session.delete(source) db_session.commit() # Source attempts to continue to navigate resp = client.post('/lookup', follow_redirects=True) self.assertEqual(resp.status_code, 200) self.assertIn('Submit documents for the first time', resp.data) self.assertNotIn('logged_in', session.keys()) self.assertNotIn('codename', session.keys()) logger.assert_called_once_with( "Found no Sources when one was expected: " "No row was found for one()")
def addCount(): if not "count" in session.keys(): session["count"]=1 else: session["count"]+=1 print session.keys() return render_template("index.html")
def signout(): if 'username' in session.keys(): session.pop('username') if 'id' in session.keys(): session.pop('id') if 'email' in session.keys(): session.pop('email') return redirect(url_for('home'))
def before_request(): print session.keys(), session.values() print("before request") print ('username' in session, "in session?") g.db = connect_db() g.user = None if "username" in session: g.user = get_user(session['username'])
def checkSession(self): print 'session.keys()', session.keys() if 'logged_in' in session.keys() and 'username' in session.keys(): self.logged_in = True else: self.logged_in = False return self.logged_in
def index(): if not "DM" in session.keys(): session["DM"] = DirManager() if not "TM" in session.keys(): session["TM"] = TableManager() return render_template( "dir.html", cur_dir=session["DM"].cur_dir, dirs=session["DM"].listdir(), files=session["TM"].tables )
def decorated_view(*args, **kwargs): if request.endpoint in app.view_functions: if 'SignIn' not in session.keys(): print session if 'username' not in session.keys(): return redirect('/') else: return redirect('/password_set') return f(*args, **kwargs)
def home(): if request.method=="GET": if 'uname' in session.keys() and 'pword' in session.keys(): return redirect(url_for('index')) return render_template("home.html") else: session['uname'] = request.form['username'] session['pword'] = request.form['password'] return redirect(url_for('index'))
def index(): if 'uname' in session.keys() and 'pword' in session.keys(): if session['uname']=="Doctor" and session['pword']=="shaco": return render_template("index.html",name=session['uname']) else: session.clear() return render_template("index2.html") else: return redirect(url_for('home'))
def reset(): for key in session.keys(): del(session[key]) session['results_computed'] = False if app.config['DEBUG']: print session.keys() return (start())
def report(): from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas assert_data() df = session['df'] # For example, user could sumbit 2013-10:2014-02 but we need to make this # into '2013-10':'2014-10' if 'idx' in session.keys() and len(session['idx'])>0: session['_filter'] idx = session['idx'] if idx.find(':') > -1: lidx, ridx = idx.split(':') df = df[lidx:ridx] else: df = df[idx] startDate = session['startDate'] endDate = session['endDate'] if startDate != '' and endDate != '': # Filter the data frame to only be a subset of full time range startDate = pandas.Timestamp(startDate) endDate = pandas.Timestamp(endDate) df = df[startDate:endDate] figures = [] if 'tags' in session.keys() and len(session['tags'])>0: figures += GBA.density_cloud_by_tags(df, session['tags'], silent=True) if 'pnodes' in session.keys() and len(session['pnodes'])>0: import matplotlib.pylab as plt plt.ioff() pnodes = session['pnodes'] df = GBA.price_at_pnodes(df, pnodes) cols = ['COST',] + ['pnode_'+p for p in pnodes] figures.append(df[cols].plot().figure) figures.append(df[cols].cumsum().plot().figure) session.drop('tags') s = '<h1>Figures</h1>' figures_rendered = [] for n, fig in enumerate(figures): s+='<img src="plt/%d.png" /><br />' % n canvas=FigureCanvas(fig) png_output = StringIO() canvas.print_png(png_output) figures_rendered.append(png_output.getvalue()) session['figures'] = figures_rendered s += '<p><a href="/dashboard">Back to dashboard</a></p><br /><br />' return s
def get_locale(): langs = current_app.config.get("LANGUAGES") lang_from_headers = request.accept_languages.best_match(langs.keys()) if "lang" not in session.keys(): session["lang"] = lang_from_headers if not lang_from_headers and "lang" not in session.keys(): # Caso não seja possível detectar o idioma e não tenhamos a chave lang # no seção, fixamos o idioma padrão. session["lang"] = current_app.config.get("BABEL_DEFAULT_LOCALE") return session["lang"]
def makeParty(data): if d: print session.keys() if d: print 'id' not in session.keys() if 'id' in session: sessionid = session['id'] else: sessionid = data['sessionid'] if d: print "makeParty:", sessionid room = data['room'].upper() newParty = p.Party(room, sessionid) if d: print "user: "******"created party: " + room url = 'http://vynl.party/party/' + room emit('makeParty', {'id': sessionid})
def check_admin_and_session(): if session and 'username' in session.keys(): try: if not auth.auth(session['_id'], session['username'], session['token']): for x in session.keys(): session.pop(x, None) return redirect('/') elif not "static" in request.path: auth.update_session(session['_id'], session['username'],\ session['token'], {"current_page": request.path}) except: for x in session.keys(): session.pop(x, None) return redirect('/')
def game_play(): print "working" treasure = 0 if not 'cash' in session.keys(): session['cash']= 0 if not 'results' in session.keys(): session['results']=[] if not 'name' in session.keys(): session['name']='' if not 'treasure' in session.keys(): session['treasure']= treasure return render_template('index.html', treasure=treasure)
def button(): #print request.form #two = request.form["two"] if "two" in session.keys(): session["count"]+=2 if "clear" in session.keys(): session["count"]=0 #reset = request.form["reset"] #if request.form["two"]: # session["count"]+=2 #else: #session["count"]=0 print request.form return redirect('/')
def add_to_favorites(): iD = request.form.get("id") zipcode = request.form.get("zipcode") #check if user is logged in if 'user_id' in session.keys(): user_id = session["user_id"] py_zipcode = find_zipcode_from_input(zipcode) city = py_zipcode.city #check to see if favorite is already in DB fav_in_db = Favorites.query.filter_by(neighborhood_id=zipcode).first() if fav_in_db is None: #favorite instance to sotre in DB favorite = Favorites(user_id=user_id, neighborhood_id=zipcode) db.session.add(favorite) db.session.commit() flash("%s %s is addded as your Favorite" % (city, zipcode)) return jsonify(status="added", id=iD) else: db.session.delete(fav_in_db) db.session.commit() flash("%s %s is deleted from your Favorite" % (city, zipcode)) return jsonify(status="deleted", id=iD)
def decorated_function(*args, **kwargs): if 'email' not in session.keys() or session['email'] is None: return redirect(url_for('users.login_user', next=request.path)) if session['email'] not in app.config['ADMINS']: return redirect(url_for('users.login_user')) return func(*args, **kwargs)
def index(): if 'userName' in session.keys(): userName = session['userName'] userId = session['userId'] return render_template("landingSession.html", userName=userName,userId=userId) else: return render_template("landing.html")
def get_savable_pano_config(): """ returns a yml string of the session variables that are included here :return: """ keys_to_copy = set(session.keys()) return yaml.dump(keys_to_copy)
def check_active_session(login_session): """check for session status and error if not""" if "user_info" in login_session.keys(): return True else: flash("Error user not logged in.") return False
def view_item_delete(id): """show a form for deleting an item""" resp = dict(item=None, error=False) form = ItemDeleteForm() # check session status and user is logged in if check_active_session(login_session) and "user_info" in login_session.keys(): # try to fetch the item resp["item"] = session.query(Item).get(id) if not resp["item"]: flash("Item not found") resp["error"] = True if resp["error"]: resp["html"] = redirect("/item/") else: # ensure user has logged in before sending template if login_session["user_info"]["user_id"] == resp["item"].user_id: resp["html"] = render_template( "itemDelete.html", item=resp["item"], form=form, login_session=login_session ) else: resp["error"] = True resp["html"] = redirect("/item/%s/" % id) flash("Error: only the item owner can delete this item") else: resp["html"] = redirect("/login") return resp["html"]
def metadata(): """Store extra fields, if any, and prepare and upload meta.xml.""" if 'file_uuid' not in session.keys(): return redirect(url_for('main')) # Parse metafields if coming from there if session['from'] == 'metafields': session['extra_fields'] = {} for i in request.form.keys(): if i != 'submitBtn' and not i.endswith("_dwc"): term_dict = {"description": request.form[i], "term": request.form["%s_dwc" % i]} session['extra_fields'][i] = term_dict # Create meta.xml meta = render_meta() # Upload to NDB datastore uploader = Uploader() uploader.upload_meta(meta) # Render metadata template session['from'] = 'metadata' return render_template('metadata.html')
def upload(): """Render and upload eml.xml, and create entry in registry table.""" if 'file_uuid' not in session.keys(): return redirect(url_for('main')) # Create eml.xml eml = render_eml(request) # Upload to NDB datastore uploader = Uploader() uploader.upload_eml(eml) # Create CartoDB registry record success = uploader.cartodb_meta(request.form) if success == False: return render_template('metadata.html') # Store datum session.pop('geodeticDatum', None) session['geodeticDatum'] = request.form['datum'] if 'datum' in request.form and request.form['datum'] != "" else "WGS84" # Create occurrence.txt # uploader.build_occurrence() # TODO: Implement build_dwca and move to Cloud Storage with googleapis session['from'] = 'upload' return render_template('upload_cartodb.html')
def get_anime(id): anime = Anime.query.get_or_404(id) anime_urls = anime.video_url.split(' ') # 根据文件后缀判断是图片还是视频 if anime_urls[0].split('.')[-1] in pic_appendix or len(anime_urls[0].split('.')[-1]) > 5: flag = 'anime' else: flag = 'video' if 'vote' in session.keys(): if session['vote'] == 1: ip = request.remote_addr if r3.get(ip): flash("每天只能投一次票!") else: anime.liked_count += 1 db.session.add(anime) db.session.commit() flash("投票成功") r3.set(ip, ip) session['vote'] = 0 return redirect(url_for('main.get_anime', id=anime.id)) else: session['vote'] = 0 return render_template('main/anime.html', anime=anime, flag=flag, anime_urls=anime_urls)
def logout(): # Is there a destination post-logout? dsturl = None if request.referrer and local_request(request.referrer): dsturl = request.referrer else: dsturl = None # End the session in the database already_logged_out = False if 'li' in session: ses = db.session result = ses.execute( text("SELECT ret, col, msg FROM aaa.logout(:sid) AS (ret BOOL, col TEXT, msg TEXT)", bindparams=[bindparam('sid', session['i'])])) ses.commit() # For now, don't test the result of the logout call. Regardless of # whether or not a user provides us with a valid session ID from the # wrong IP address, terminate the session. Shoot first, ask questions # later (i.e. why was a BadUser in posession of GoodUser's session # ID?!) else: already_logged_out = True # Nuke every key in the session for k in session.keys(): session.pop(k) # Set a flash message after we nuke the keys in session if already_logged_out: flash('Session cleared for logged out user') else: flash('You were logged out') return render_template('aaa/logout.html', dsturl=dsturl)
def main(): """Return main page.""" # If coming from parsing content, show errors if 'errors' in session.keys(): errors = session['errors'] # Else, clear session except for any messages and start fresh else: messages = session.get('_flashes', None) session.clear() if messages is not None: session['_flashes'] = messages errors = [] # Mandatory headers and header types session.pop('mandatory_fields_types', None) session.pop('mandatory_fields', None) session['mandatory_fields_types'] = { 'scientificName': 'text', 'decimalLatitude': 'number', 'decimalLongitude': 'number', 'eventDate': 'text', 'recordedBy': 'text', # 'geodeticDatum': 'text', 'coordinateUncertaintyInMeters': 'number' } session['mandatory_fields'] = session['mandatory_fields_types'].keys() # Tracking variable session['from'] = 'main' return render_template("main.html", errors=errors)
def shopping(): if ('addr' in session.keys()) and session['addr']==request.remote_addr: return(render_template('1.5_shopping.html')) else: return(redirect('/login/notfound'))
def profile_edit(): if 'addr' in session.keys() and session['addr']==request.remote_addr: k1=p[0] return(render_template('1.8_profile_edit.html',l=k1)) else: return(redirect('/login/notfound'))
def decorated_function(*args, **kwargs): if 'email' not in session.keys() or session['email'] is None: return redirect(url_for('users.login_user', next=request.path)) return func(*args, **kwargs)
def register(): # VALIDATIONS ====================== # First name validations if len(request.form['first_name']) < 1: flash("First name cannot be blank!", 'first_name') elif not NAME_REGEX.match(request.form['first_name']): flash( "First name must contain at least two letters and contain only letters!" ) # ================================== # Last name validations if len(request.form['last_name']) < 1: flash("First name cannot be blank!", 'last_name') elif not NAME_REGEX.match(request.form['last_name']): flash( "Last name must contain at least two letters and contain only letters!" ) # ================================== # Email validations if len(request.form['email-reg']) < 1: flash("Email cannot be blank!", 'email-reg') elif not EMAIL_REGEX.match(request.form['email-reg']): flash("Invalid Email Address!", 'email-reg') elif check_duplicates(request.form['email-reg']): flash("We encountered a problem.", 'email-reg') # ================================== # Password validations if len(request.form['password']) < 1: flash("Password cannot be blank!", 'password') elif not PW_REGEX.match(request.form['password']): flash( "Password must be at least 8 characters long and contain letters, numbers and the following: @#$%^&+=", 'password') # ================================== # Password confirmation validations if len(request.form['confpassword']) < 1: flash("Please re-enter password", 'confpassword') elif request.form['confpassword'] != request.form['password']: flash("Passwords must match", 'confpassword') # ================================== # If there are any errors, displays them and redirects back to home. if '_flashes' in session.keys(): return redirect("/") # Successful registration else: # Displays welcome message on success page. session['recentreg'] = True # Hashes password pwhash = bcrypt.generate_password_hash(request.form['password']) # Creates account in the database # Query ==================== mysql = connectToMySQL('thewall') query = "INSERT INTO users (first_name, last_name, email, pwhash, created_at) VALUES(%(first_name)s, %(last_name)s, %(email)s, %(pwhash)s, NOW());" data = { 'first_name': request.form['first_name'], 'last_name': request.form['last_name'], 'email': request.form['email-reg'], 'pwhash': pwhash, } mysql.query_db(query, data) # ========================= # First time login login_validation(request.form['email-reg'], request.form['password']) return redirect('/success')
def debugSession(self): if cfg.DEBUG: for key in session.keys(): cfg.debug(f"KEY: {key} -> {session.get(key)}", True)
def logout(): [session.pop(key) for key in list(session.keys())] return redirect(url_for("home"))
def session_api(): return jsonify(list(session.keys()))
def home(): return render_template('home.html', codes=session.keys())
def decorated_function(*args, **kwargs): if 'email' not in session.keys() or session['email'] is None: # after user login they will go back to original website return redirect(url_for('users.login_user', next=request.path)) return func(*args, **kwargs)
def realizar_pago(): # Hay que haber iniciado sesion para realizar la compra if 'usuario' not in session.keys(): return redirect(url_for('login')) else: logged_user = session['usuario'] usersfolder = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'usuarios') personalfolder = os.path.join(usersfolder, logged_user, 'data.dat') # diccionario con el data.dat dict = data_to_dict(personalfolder) dinero_actual = dict['Saldo'] # Calculamos el precio que se está intentando pagar lista_peliculas = None precio_pedido = 0 if 'peliculas_carrito' in session.keys(): lista_peliculas = session['peliculas_carrito'] for pelicula in lista_peliculas: precio_pedido += pelicula['precio'] * pelicula['cantidad'] # En el carrito de la compra, escribo que no hay suficiente dinero if float(dinero_actual) < float(precio_pedido): error = { 'mensaje': 'Saldo insuficiente. Su saldo actual es {0:.2f}'.format( float(dinero_actual)) + "$. Añada saldo para completar la compra" } return render_template('carrito.html', title='Carrito', lista_peliculas=lista_peliculas, precio=precio_pedido, aux=error) # Reemplazamos el data.dat para actualizar el saldo restante # Vaciamos la informacion del carrito de la sesion else: update_historial_pedidos() session.pop('peliculas_carrito', None) session.modified = True f = open(personalfolder, "w+") for key in dict: if key == 'Saldo': f.write("{} : {}\n".format( key, str( round( float(dinero_actual) - float(precio_pedido), 2)))) else: f.write("{} : {}\n".format(key, dict[key])) f.close() session['saldo'] = str( round(float(dinero_actual) - float(precio_pedido), 2)) session.modified = True compra = { 'mensaje': 'Compra efectuada correctamente. Su saldo restante es {0:.2f}'. format(float(dinero_actual) - float(precio_pedido)) + "$" } return render_template('carrito.html', Title="Carrito", aux=compra)
def pedidos(): global catalogue # Si el usuario ha iniciado sesion, empezamos a cargar el historial if 'usuario' in session.keys(): if catalogue is None: leer_catalogo() usersfolder = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'usuarios') personal_folder = os.path.join(usersfolder, session['usuario']) historial_file = os.path.join(personal_folder, "historial.json") # Si el archivo esta vacio, di que no hay pedidos if os.stat(historial_file).st_size == 0: err_text = session[ 'usuario'] + ", todavia no ha realizado ningun pedido" context_dict = {'text': err_text} return render_template('pedidos.html', title="Pedidos", message=context_dict) historial_pedidos = open(historial_file, encoding="utf-8").read() pedidos = json.loads(historial_pedidos) lista_total = [] for line in pedidos['pedidos']: lista = [] precio_pedido = 0 num_peliculas = 0 lista.append(line['fecha']) # añade el número de artículos del pedido (incluyendo el número de articulos que están repetidos) # Vamos mirando cada id, pero tenemos que tener en cuenta cúantos se han pedido de ese id i = 0 for id in line['ids']: for elemento_catalogo in catalogue['peliculas']: if elemento_catalogo['id'] == id: precio_pedido += float( elemento_catalogo['precio']) * float( line['cantidad'][i]) num_peliculas += int(line['cantidad'][i]) elemento_catalogo['cantidad'] = line['cantidad'][i] lista.append(elemento_catalogo) i += 1 # añade el número de peliculas del pedido lista.append(len(lista) - 1) # añade el precio total del pedido lista.append(precio_pedido) # total_pelis = 0 # for cantidad in line['cantidad']: # total_pelis += int(cantidad) lista.append(num_peliculas) # Tendo una lista con la fecha del pedido, las peliculas de ese pedido, cuántas son y cual es su precio total lista_total.append(lista) # Lista de listas de pedidos return render_template('pedidos.html', title="Pedidos", lista_total=lista_total) # Si no has iniciado sesion, te muestra un mensaje de que tienes que iniciar sesion else: err_text = "Debes iniciar sesión para ver tu historial de pedidos" context_dict = {'text': err_text} return render_template('pedidos.html', title="Pedidos", message=context_dict)
def login(): # doc sobre request object en http://flask.pocoo.org/docs/1.0/api/#incoming-request-data # Si nos llaman con metodo get, significa que se acaba de registrar if request.args.get("username"): # Vaciamos la url de la sesion, para volver al index cuando iniciamos sesion session.pop('url_origen', None) session.modified = True # Le dejamos en la página de inicio de sesión para que acceda login_text = "Ahora puedes iniciar sesion con tu usuario " + request.args.get( "username") context_dict = {'text': login_text} return render_template('login.html', title="Sign In", message=context_dict) # Si acaban de pulsar el boton de iniciar sesion if request.method == 'POST': usersfolder = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'usuarios') personalfolder = os.path.join(usersfolder, request.form['Username'], 'data.dat') # Comprobamos si el usuario existe if not os.path.exists(usersfolder) or not os.path.exists( personalfolder): err_text = "No existe el usuario " + request.form['Username'] context_dict = {'text': err_text} return render_template('login.html', title="Sign In", message=context_dict) else: # dictionary with the data.dat file dict = data_to_dict(personalfolder) if dict['Username'] == request.form['Username'] and dict[ 'Password'] == hashlib.md5( str(request.form['Password']).encode( 'utf-8')).hexdigest(): session['usuario'] = request.form['Username'] session['saldo'] = dict['Saldo'] session.modified = True if 'url_origen' in session.keys(): # Si estas en login por voluntad propia, al iniciar sesion te devuelve al index if session[ 'url_origen'] is not "http://0.0.0.0:5001/login": resp = make_response(redirect(session['url_origen'])) resp.set_cookie('username', request.form['Username']) return resp resp = make_response(redirect(url_for('index'))) resp.set_cookie('username', request.form['Username']) return resp else: err_text = "Contraseña incorrecta para el usuario " + request.form[ 'Username'] context_dict = {'text': err_text} return render_template('login.html', title="Sign In", message=context_dict) else: session['url_origen'] = request.referrer session.modified = True return render_template('login.html', title="Sign In")
def print_scores(host, q): if request.method == 'GET': if ('handled_q' in session.keys()) and (session['handled_q'] == q): return render_template( 'main/visualization.html', auth=authenticate( host=host, on_callback=True if host == 'client' else False), host=host, q=q, scores=session['results']) if re.search("\w", q) is None: return redirect(url_for('main.search', host=host)) auth = authenticate(host=host, on_callback=True if host == 'client' else False) if True: # always run the demo date_time_obj = [ dt.date.today() - dt.timedelta(days=1), dt.date.today() - dt.timedelta(days=2), dt.date.today() - dt.timedelta(days=3), dt.date.today() - dt.timedelta(days=4), dt.date.today() - dt.timedelta(days=5), dt.date.today() - dt.timedelta(days=6), dt.date.today() - dt.timedelta(days=7) ] dummy_data = [[rand(), rand(), rand(), rand(), date_time_obj[i]] for i in range(len(date_time_obj))] dummy_data = pd.DataFrame(dummy_data, columns=[ "neg_sent", "pos_sent", "comp_sent", "polarity", "date" ]) dummy_data["date"] = pd.to_datetime(dummy_data["date"]) preprocesser = Preprocesser(dummy_data) session['results'] = { 'd_7_mean_scores': preprocesser.simple_mean(to_json=True), 'd_7_means_by_date': preprocesser.by_date_mean(unix=True, to_json=True) } session['handled_q'] = q return render_template('main/visualization.html', auth=auth, host=host, q=q, scores=session['results']) else: from app.main.methods.sentiment_engine import analyze_sentiments try: preprocesser = Preprocesser( analyze_sentiments( extract_tweets_from_q(query=q, api=twp.API( auth, wait_on_rate_limit=True), use_pages=False, num=200))) except TypeError: return render_template( 'main/visualization.html', auth=auth, host=host, q=q, form=SearchForm(submit_label='Try again')) else: session['results'] = { 'd_7_mean_scores': preprocesser.simple_mean(to_json=True), 'd_7_means_by_date': preprocesser.by_date_mean(unix=True, to_json=True) } print(session['results']) session['handled_q'] = q return render_template('main/visualization.html', auth=auth, host=host, q=q, scores=session['results']) return redirect( url_for('main.print_scores', host=host, q=SearchForm(submit_label='Try again').build_query()))
def signup(): if ('addr' in session.keys()) and session['addr']==request.remote_addr: return redirect("/login/profile") return(render_template('1.3_signup.html'))
def admin_login(): if ('addr3' in session.keys()) and session['addr3']==request.remote_addr: return(render_template('1.0_admin.html')) return render_template('1.0_admin_login.html',)
def logout(): for key in list(session.keys()): session.pop(key) return redirect('/')
def landing(): url = unauthenticated_api.get_authorize_url() username = '******' if 'user_info' in session.keys(): username = session['user_info']['username'] return render_template('cover.html', url=url, username=username)
def logout(): logout_user() if session: for key in list(session.keys()): session.pop(key) return redirect(url_for('home'))
def info_session(): result = '' for key in session.keys(): result += "<br/>" + key + " : " + str(session[key]) return "Session : " + result
def iscatterplot(download=None): """ renders the plot on the fly. https://gist.github.com/illume/1f19a2cf9f26425b1761b63d9506331f """ apps = current_user.user_apps plot_arguments = None reset_info = check_session_app(session, "iscatterplot", apps) if reset_info: flash(reset_info, 'error') # INITIATE SESSION session["filename"] = "Select file.." plot_arguments = figure_defaults() session["plot_arguments"] = plot_arguments session["COMMIT"] = app.config['COMMIT'] session["app"] = "iscatterplot" if request.method == 'POST': try: # READ SESSION FILE IF AVAILABLE # AND OVERWRITE VARIABLES if request.files["inputsessionfile"]: msg, plot_arguments, error = read_session_file( request.files["inputsessionfile"], "iscatterplot") if error: flash(msg, 'error') return render_template('/apps/iscatterplot.html', filename=session["filename"], apps=apps, **plot_arguments) flash(msg, "info") if request.files["inputargumentsfile"]: msg, plot_arguments, error = read_argument_file( request.files["inputargumentsfile"], "iscatterplot") if error: flash(msg, 'error') return render_template('/apps/iscatterplot.html', filename=session["filename"], apps=apps, **plot_arguments) flash(msg, "info") # IF THE UPLOADS A NEW FILE # THAN UPDATE THE SESSION FILE # READ INPUT FILE inputfile = request.files["inputfile"] if inputfile: filename = secure_filename(inputfile.filename) if allowed_file(inputfile.filename): df = read_tables(inputfile) cols = df.columns.tolist() if len(cols) < 2: error_msg = "Your table needs to have at least 2 columns. One for the x- and one for the y-value." flash(error_msg, 'error') return render_template('/apps/iscatterplot.html', filename=session["filename"], apps=apps, **plot_arguments) if session["plot_arguments"]["groups"] not in cols: session["plot_arguments"]["groups"] = ["None"] + cols columns_select=["markerstyles_cols", "markerc_cols", "markersizes_cols","markeralpha_col",\ "labels_col","edgecolor_cols","edge_linewidth_cols",] for parg in columns_select: if session["plot_arguments"][ "markerstyles_cols"] not in cols: session["plot_arguments"][parg] = [ "select a column.." ] + cols session["plot_arguments"]["xcols"] = cols session["plot_arguments"]["ycols"] = cols # IF THE USER HAS NOT YET CHOOSEN X AND Y VALUES THAN PLEASE SELECT if (session["plot_arguments"]["xvals"] not in cols) | ( session["plot_arguments"]["yvals"] not in cols): session["plot_arguments"]["xvals"] = cols[0] session["plot_arguments"]["yvals"] = cols[1] sometext = "Please select which values should map to the x and y axes." plot_arguments = session["plot_arguments"] flash(sometext, 'info') return render_template('/apps/iscatterplot.html', filename=filename, apps=apps, **plot_arguments) plot_arguments = session["plot_arguments"] flash("New file uploaded.", 'info') return render_template('/apps/iscatterplot.html', filename=filename, apps=apps, **plot_arguments) else: # IF UPLOADED FILE DOES NOT CONTAIN A VALID EXTENSION PLEASE UPDATE error_msg = "You can can only upload files with the following extensions: 'xlsx', 'tsv', 'csv'. Please make sure the file '%s' \ has the correct format and respective extension and try uploadling it again." % filename flash(error_msg, 'error') return render_template('/apps/iscatterplot.html', filename="Select file..", apps=apps, **plot_arguments) if not request.files["inputsessionfile"] and not request.files[ "inputargumentsfile"]: # SELECTION LISTS DO NOT GET UPDATED # lists=session["lists"] # USER INPUT/PLOT_ARGUMENTS GETS UPDATED TO THE LATEST INPUT # WITH THE EXCEPTION OF SELECTION LISTS plot_arguments = session["plot_arguments"] # if request.form["groups_value"] == "None": # plot_arguments["groups_value"]="None" if plot_arguments["groups_value"] != request.form[ "groups_value"]: if request.form["groups_value"] != "None": df = pd.read_json(session["df"]) df[request.form["groups_value"]] = df[ request.form["groups_value"]].apply( lambda x: secure_filename(str(x))) df = df.astype(str) session["df"] = df.to_json() groups = df[request.form["groups_value"]] groups = list(set(groups)) groups.sort() plot_arguments["list_of_groups"] = groups groups_settings = [] group_dic = {} for group in groups: group_dic={"name":group,\ "markers":plot_arguments["markers"],\ "markersizes_col":"select a column..",\ "markerc":random.choice([ cc for cc in plot_arguments["marker_color"] if cc != "white"]),\ "markerc_col":"select a column..",\ "markerc_write":plot_arguments["markerc_write"],\ "edge_linewidth":plot_arguments["edge_linewidth"],\ "edge_linewidth_col":"select a column..",\ "edgecolor":plot_arguments["edgecolor"],\ "edgecolor_col":"select a column..",\ "edgecolor_write":"",\ "marker":random.choice(plot_arguments["markerstyles"]),\ "markerstyles_col":"select a column..",\ "marker_alpha":plot_arguments["marker_alpha"],\ "markeralpha_col_value":"select a column.."} groups_settings.append(group_dic) plot_arguments["groups_settings"] = groups_settings elif request.form["groups_value"] == "None": plot_arguments["groups_settings"] = [] plot_arguments["list_of_groups"] = [] elif plot_arguments["groups_value"] != "None": groups_settings = [] group_dic = {} for group in plot_arguments["list_of_groups"]: group_dic={"name":group,\ "markers":request.form["%s.markers" %group],\ "markersizes_col":request.form["%s.markersizes_col" %group],\ "markerc":request.form["%s.markerc" %group],\ "markerc_col":request.form["%s.markerc_col" %group],\ "markerc_write":request.form["%s.markerc_write" %group],\ "edge_linewidth":request.form["%s.edge_linewidth" %group],\ "edge_linewidth_col":request.form["%s.edge_linewidth_col" %group],\ "edgecolor":request.form["%s.edgecolor" %group],\ "edgecolor_col":request.form["%s.edgecolor_col" %group],\ "edgecolor_write":request.form["%s.edgecolor_write" %group],\ "marker":request.form["%s.marker" %group],\ "markerstyles_col":request.form["%s.markerstyles_col" %group],\ "marker_alpha":request.form["%s.marker_alpha" %group],\ "markeralpha_col_value":request.form["%s.markeralpha_col_value" %group] } groups_settings.append(group_dic) plot_arguments["groups_settings"] = groups_settings if request.form["labels_col_value"] != "select a column..": df = pd.read_json(session["df"]) plot_arguments["available_labels"] = list( set(df[request.form["labels_col_value"]].tolist())) session["plot_arguments"] = plot_arguments plot_arguments = read_request(request) if "df" not in list(session.keys()): error_msg = "No data to plot, please upload a data or session file." flash(error_msg, 'error') return render_template('/apps/iscatterplot.html', filename="Select file..", apps=apps, **plot_arguments) # MAKE SURE WE HAVE THE LATEST ARGUMENTS FOR THIS SESSION filename = session["filename"] plot_arguments = session["plot_arguments"] # READ INPUT DATA FROM SESSION JSON df = pd.read_json(session["df"]) #CALL FIGURE FUNCTION fig = make_figure(df, plot_arguments) figure_url = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) return render_template('/apps/iscatterplot.html', figure_url=figure_url, filename=filename, apps=apps, **plot_arguments) except Exception as e: tb_str = handle_exception(e, user=current_user, eapp="iscatterplot", session=session) flash(tb_str, 'traceback') if not plot_arguments: plot_arguments = session["plot_arguments"] filename = session["filename"] return render_template('/apps/iscatterplot.html', filename=filename, apps=apps, **plot_arguments) else: if download == "download": # READ INPUT DATA FROM SESSION JSON df = pd.read_json(session["df"]) plot_arguments = session["plot_arguments"] # CALL FIGURE FUNCTION fig = make_figure(df, plot_arguments) pio.orca.config.executable = '/miniconda/bin/orca' pio.orca.config.use_xvfb = True #pio.orca.config.save() figfile = io.BytesIO() mimetypes = { "png": 'image/png', "pdf": "application/pdf", "svg": "image/svg+xml" } pa_ = {} for v in ["fig_height", "fig_width"]: if plot_arguments[v] != "": pa_[v] = False elif plot_arguments[v]: pa_[v] = float(plot_arguments[v]) else: pa_[v] = False if (pa_["fig_height"]) & (pa_["fig_width"]): fig.write_image(figfile, format=plot_arguments["downloadf"], height=pa_["fig_height"], width=pa_["fig_width"]) else: fig.write_image(figfile, format=plot_arguments["downloadf"]) figfile.seek(0) # rewind to beginning of file eventlog = UserLogging(email=current_user.email, action="download figure iscatterplot") db.session.add(eventlog) db.session.commit() return send_file(figfile, mimetype=mimetypes[plot_arguments["downloadf"]], as_attachment=True, attachment_filename=plot_arguments["downloadn"] + "." + plot_arguments["downloadf"]) return render_template('apps/iscatterplot.html', filename=session["filename"], apps=apps, **session["plot_arguments"])
def decorated_function(*args, **kwargs): if 'email' not in session.keys() or session['email'] is None: flash(u'You need to be signed in for this page.') return redirect(url_for('users.login_user', next=request.path)) return f(*args, **kwargs)
def logout(): '''Removes current user from session.keys()''' if "user" in session.keys(): session.pop("user") return redirect(url_for("login"))
def main(): """ Render the webapp index.html template :return index template: """ log.info(":WEB:/") if "username" in session.keys(): username = session["username"] else: username = None if username: log.info(":{0}:Found username cookies".format(username)) log.debug("Setting session data") if "logged-in" not in session.keys(): session["logged-in"] = False session["welcome-message"] = "Welcome to J.U.L.I.E" if configuration_data["debug"]: session["debug_http"] = True session["first-command"] = True if username: user_table = db["users"].find_one(username=username) if "user_token" in user_table.keys() and "user_token" in session.keys( ): user_token = session["user_token"] if user_table["user_token"] == user_token: log.info( ":{0}:User authenticated via user_token in cookies".format( username)) new_token = tools.get_user_token(username) db["users"].upsert( { "username": username, "user_token": new_token }, ['username']) session["logged-in"] = True user_first_name = user_table["first_name"] session["welcome-message"] = "Welcome back {0}".format( user_first_name) if "session_id" in session.keys( ) and session["session_id"] in core.sessions.keys(): session_id = session["session_id"] else: session_id = tools.gen_session(username, "WEB", db) session["session_id"] = session_id session["user_token"] = new_token log.info(":{0}:Generated session id for user {1}".format( session_id, username)) resp = make_response(render_template('index.html')) return resp else: log.debug("User tokens don't match.\n{0}\n{1}".format( request.cookies.get("user_token"), db["users"].find_one(username=username)["user_token"])) session["logged-in"] = False else: log.debug("Couldn't find user token in cookies") session["logged-in"] = False else: log.debug("Couldn't find username in cookies") session["logged-in"] = False #If the cookies aren't found return render_template('index.html')
def register(): debugHelp("REGISTER") # first name validation if len(request.form['first_name']) < 1: flash('First name cannot be empty', 'first_name') if request.form['first_name'].isalpha() == False: flash('First name must have letters only', 'first_name') if len(request.form['first_name']) < 3: flash('First name must have at least 3+ letters!', 'first_name') # last name validation if request.form['last_name'].isalpha() == False: flash('LAST name must have letters only', 'last_name') if len(request.form['last_name']) < 1: flash('LAST name cannot be empty', 'last_name') if len(request.form['last_name']) < 3: flash('LAST name must have at least 3+ letters!', 'last_name') # email validation if len(request.form['email']) < 1: flash("Email cannot be blank!", 'email') elif not EMAIL_REGEX.match(request.form['email']): flash("Invalid Email Address!", 'email') # password validation if len(request.form['password']) < 1: flash("password cannot be blank", 'password') if len(request.form['password']) < 6: flash('password must have AT LEAST 6 characters', 'password') # password confirm validation if request.form['password'] != request.form['password_confirm']: flash('passwords must match!', 'password_confirm') #db checks existing email data = { "email": request.form['email'] } query = "SELECT email FROM users WHERE email=%(email)s;" result = mysql.query_db(query, data) # if the db responds with a result then email aready exists in db, stop user from registering if (result): flash('cannot use this email', 'email') # final checks if '_flashes' in session.keys(): return redirect("/") else: # if there are no flash errors query to insert user to db and session name pw_hash = bcrypt.generate_password_hash(request.form['password']) data = { "first_name": request.form['first_name'], "last_name": request.form['last_name'], "email": request.form['email'], "password": pw_hash, } query = "INSERT INTO users(first_name, last_name, email, password, created_at, updated_at) VALUES (%(first_name)s, %(last_name)s, %(email)s, %(password)s, NOW(), NOW());" mysql.query_db(query, data) session['first_name'] = request.form['first_name'] # now query to select same user by email to get id and add to session data2 = { 'email': request.form['email'] } query2 = "SELECT id FROM users WHERE email=%(email)s" result2 = mysql.query_db(query2, data2) session['user_id'] = result2[0]['id'] return redirect("/wall")
def register(): mysql = connectToMySQL('private_wall') if request.form['first_name'] == "": flash("First name is required.") elif len(request.form['first_name']) < 2: flash("Name must be at least 2 characters.") if request.form['last_name'] == "": flash("Last name is required.") elif len(request.form['last_name']) < 2: flash("Name must be at least 2 characters.") if request.form['email'] == "": flash("Email is required.") elif not EMAIL_REGEX.match(request.form['email']): flash("Invalid email format") other_emails = mysql.query_db( "SELECT email FROM accounts WHERE email=%(email)s;", {"email": request.form['email']}) if other_emails: flash("This email has already been used to create an account.") if request.form['password'] == "": flash("Password is required.") elif len(request.form['password']) < 8: flash("Password must be at least 8 characters.") if request.form['confirm_pass'] == "": flash("Password confirmation is required.") elif request.form['confirm_pass'] != request.form['password']: flash("You must enter the same password in both fields.") if '_flashes' in session.keys(): return redirect('/') else: mysql = connectToMySQL('private_wall') pw_hash = bcrypt.generate_password_hash(request.form['password']) print(pw_hash) query = "INSERT INTO accounts (first_name, last_name, email, pw_hash, updated_at, created_at) VALUES (%(fn)s, %(ln)s, %(em)s, %(pwh)s, NOW(), NOW());" data = { "fn": request.form['first_name'], "ln": request.form['last_name'], "em": request.form['email'], "pwh": pw_hash } new_user = mysql.query_db(query, data) if new_user: session['current_user_id'] = new_user else: return redirect('/') return redirect('/success')
def yahoo_get_players(): #get own fantasy team players within a league if not 'yahoo_token' in session.keys(): return redirect( url_for('yahoo_oauth', next=url_for('yahoo_get_players') or None)) game_key = 'nfl' league_id = '1173612' team_id = '8' team_key_format = game_key + '.l.' + league_id + '.t.' + team_id #my_league_key = nfl_game_key + '.l.' + my_league_id my_league_key = '314.l.1173612' league_key = 'nfl.l.1173612' team_key = '314.l.1173612.t.8' temp = dict() # THIS SHOULDNT BE HARD CODED param = {'week': '12'} resp, content = get_yahoo_api_data('team/' + team_key + '/roster/players', session['yahoo_token'][0], session['yahoo_token'][1], extras=param) if resp.status == 401: return redirect( url_for('yahoo_oauth', next=url_for('yahoo_get_players') or None)) # call yahoo api HELPER yahoo_api_helper = YahooHelper() yahoo_api_helper.import_json_data(content, get='players') yahoo_api_helper.return_data() # this gets team data from collection, may just only need one API call. #full_content = content['fantasy_content']['team'][0] #last ['14'] parameter represents the player #full_content = content['fantasy_content']['team'][1]['roster']['0']['players']['14'] full_content = content['fantasy_content']['team'][1]['roster']['0'][ 'players']['14'] player_data = content['fantasy_content']['team'][1]['roster']['0'][ 'players']['1'] temp = player_data['player'][0][15] #iteritems() -> #iterkeys() #itervalues() data_wanted = ["u'player_key"] #, "u'player_id"] isolated = list() temp_list = list() temp_list2 = list() temp_value = player_data['player'][0] for value in temp_value: temp_list.append(type(value)) #for value in itertools.islice(value,4,5): # isolated = value if type(value) == dict: for attr in data_wanted: if value.has_key(u'player_key'): isolated = value[u'player_key'] pass for key, value in value.iteritems(): temp_list2.append(key) #isolated.append(value) #else: # temp_list = 'isn\'t a dict' roster_position = player_data['player'][1]['selected_position'][1][ 'position'] yahoo_player_key = player_data['player'][0][0]['player_key'] yahoo_player_id = player_data['player'][0][1]['player_id'] yahoo_full_name = player_data['player'][0][2]['name']['full'] yahoo_first_name = player_data['player'][0][2]['name']['first'] yahoo_players_team = player_data['player'][0][5] #yahoo_last_name = player_data['player'][0][2]['name']['last'] yahoo_last_name = player_data['player'][0][2]['name'] #yahoo_players_bye_week = player_data['player'][0][7]['bye_weeks']['week'] yahoo_players_bye_week = player_data['player'][0][7] #yahoo_players_team_abbr = player_data['player'][0][6]['editorial_team_abbr'] yahoo_players_team_abbr = player_data['player'][0][6] #yahoo_players_number = player_data['player'][0][8]['uniform_number'] yahoo_players_number = player_data['player'][0][8] #yahoo_players_position = player_data['player'][0][9]['display_position'] yahoo_players_position = player_data['player'][0][9] #position = player_data['player'][1][] return render_template('yahoo.html', what_data='players', isolated=isolated, temp_list=temp_list, temp_list2=temp_list2, temp=temp, resp=resp, data=content, player_data=player_data, full_content=content, roster_position=roster_position, yahoo_player_key=yahoo_player_key, yahoo_player_id=yahoo_player_id, yahoo_full_name=yahoo_full_name, yahoo_first_name=yahoo_first_name, yahoo_last_name=yahoo_last_name, yahoo_players_team=yahoo_players_team, yahoo_players_team_abbr=yahoo_players_team_abbr, yahoo_player_bye_week=yahoo_players_bye_week, yahoo_players_number=yahoo_players_number, yahoo_players_position=yahoo_players_position)
def register(): mysql = connectToMySQL('login_and_registration') query = "SELECT * FROM users WHERE email = %(email)s;" data = { 'email': request.form['email'], } result = mysql.query_db(query, data) if len(request.form["first_name"]) < 1: flash("first name required", "first_name") elif len(request.form["first_name"]) < 3: flash("first name needs to be at least 2 letters", "first_name") elif not NAME_REGEX.match(request.form["first_name"]): flash("first name cannot have numbers!", "first_name") else: session["first_name"] = request.form["first_name"] if len(request.form["last_name"]) < 1: flash("last name required", "last_name") elif len(request.form["last_name"]) < 3: flash("last name needs to be at least 2 letters", "last_name") elif not NAME_REGEX.match(request.form["last_name"]): flash("last name cannot have numbers!", "last_name") else: session["last_name"] = request.form["last_name"] if len(request.form["email"]) < 1: flash("email required", "email") elif not EMAIL_REGEX.match(request.form['email']): flash("You must input a valid email address!", "email") elif len(result) != 0: flash("This email already exists!", "email") else: session["email"] = request.form["email"] if len(request.form["password"]) < 1: flash("password required", "password") elif len(request.form["password"]) < 8: flash("password needs to be at least 8 characters", "password") if len(request.form["confirm_password"]) < 1: flash("confirm password required", "confirm_password") elif request.form["password"] != request.form["confirm_password"]: flash("password do not match!", "confirm_password") else: session["password"] = request.form["password"] if '_flashes' in session.keys(): return redirect("/") else: pw_hash = bcrypt.generate_password_hash(request.form['password']) session['email'] = request.form['email'] session['logged_in'] = True mysql = connectToMySQL('login_and_registration') query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at) VALUES (%(first_name)s, %(last_name)s, %(email)s, %(pass_hash)s, NOW(), NOW());" data = { 'first_name': request.form['first_name'], 'last_name': request.form['last_name'], 'email': request.form['email'], 'pass_hash': pw_hash } mysql.query_db(query, data) flash("You have successfully registered!", "status") return redirect("/success") return redirect("/success")
def do_everything(): """this function is executed for new users. this will populate the database with all necessary information. user_data -> league_data -> team_data -> team_stats -> ind_player_stats""" yahoo_parser = YahooHelper() yahoo_caller = YahooAPICaller() yahoo_db_helper = Db_Helper() # start timer that times API calls api_call_start_time = time.time() if not 'yahoo_token' in session.keys(): return redirect( url_for('yahoo_oauth', next=url_for('do_everything') or None)) # load oauth tokens to yahoo yahoo_caller.load_oauth_tokens(session['yahoo_token'][0], session['yahoo_token'][1]) # get_user() resp, content = yahoo_caller.get_user_info() yahoo_parser.import_json_data(content, get='user') user_guid = yahoo_parser.return_data() yahoo_league_id = '' list_of_user_dicts = yahoo_parser.import_json_data(content, get='user_v2') yahoo_db_helper.import_list_of_user_dicts(list_of_user_dicts) yahoo_db_helper.brians_import_user_info(user_id=session['user_id'], user_guid=user_guid) # this does what parse_league currently does yahoo_db_helper.brian_import_user_info_v2(user_id=session['user_id'], yahoo_league_id=yahoo_league_id, start_date=start_date, end_date=end_date, num_teams=num_teams, league_url=league_url, league_name=league_name, game_key=game_key, season_year=season_year) # load league_id for parser yahoo_caller.load_yahoo_league_key(yahoo_league_id) #get_league() resp, content = yahoo_caller.get_league_info() yahoo_parser.import_json_data(content, get='leagues') f_league_dict = yahoo_parser.return_data() yahoo_db_helper.brians_import_league_info(f_league_dict) #get_team() resp, content = yahoo_caller.get_team_info() yahoo_parser.import_json_data(content, get='teams') processed_data = yahoo_parser.return_data() #yahoo_db_helper.brians_import_team_info(processed_data) #^ will need to rewrite to return a dictionary, as of now, # the db insert calls will stay inside yahoo_parser. nfl_league_key = yahoo_league_id league_id = yahoo_db_helper.return_league_id(session['user_id']) num_teams = yahoo_db_helper.return_num_teams(league_id) print "num_teams: %s" % num_teams print "nfl_league_key: %s" % nfl_league_key print "league_id: %s" % league_id def get_weeks(): league = F_League.query.filter_by(user_id=session['user_id']).first() week = Week_Lookup.query.all() week_list = list() for w in week: if (w.start_date <= date.today()) and (w.start_date >= league.start_date): week_list.append(w.week_num) return week_list week_list = get_weeks() ## GET_PLAYERS() starts here #used temp to fix update_players #params : league_key, week, num_teams for week in week_list: # list of fantasy_players in entire league by week players_for_entire_league = yahoo_caller.get_all_players_data( week, nfl_league_key, num_teams) # loop over list of fantasy_players JSON data # parse the JSON and add them to database for players_per_week in players_for_entire_league: yahoo_parser.import_json_data(players_per_week, get='players_v2') processed_data = yahoo_parser.return_data() yahoo_db_helper.brians_import_players_data_v2(processed_data) ## GET_PLAYERS() ends here #get_team_stats() #^^^ will need to write a function to determine how many weeks the user has played. # for example if user started league in week 1 and it is currently week 10. # the function will need to call get_team_stats for EACH week. # right now, it is only handling one week. for week in week_list: resp, content = yahoo_caller.get_team_stats(week) yahoo_parser.import_json_data(content, get='team_stats') processed_data = yahoo_parser.return_data( ) #<== stats_dict returned here yahoo_db_helper.brians_import_team_stats( processed_data) #<== stats_dict being parsed #^^ magical insert to DB happens here for week in week_list: scores_for_player = yahoo_caller.get_weekly_stats_for_all_players_in_league( week, nfl_league_key, num_teams) for player_pts_for_week in scores_for_player: yahoo_parser.import_json_data(player_pts_for_week, get='weekly_stats') parsed_data = yahoo_parser.return_data() yahoo_db_helper.import_player_stats(parsed_data) #parsed_scores.append(parsed_data) parsed_content = "" api_call_end_time = time.time() api_call_time = api_call_end_time - api_call_start_time num_api_calls = yahoo_caller.return_api_call_count() resp = "API CALLS took: %s seconds." % api_call_time content = "API CALLS MADE: %s" % num_api_calls return render_template('yahoo.html', what_data='player_stats', resp=resp, content=content, processed_content=parsed_content)
def logout(): [session.pop(key) for key in list(session.keys())] session.clear() response = {'message': 'Logged out'} return response
def do_logout() -> str: if 'logged_in' not in session.keys(): return 'ログインしていません。' session.pop('logged_in') # sessionからlogged_inキーを削除 return 'ログアウトしました。'