Browse Source

Fix sessions and score generation

master
Ruben van de Ven 5 years ago
parent
commit
69ab0cc31a
  1. 78
      contextualise.py

78
contextualise.py

@ -9,6 +9,7 @@ import re
from PIL import Image, ImageDraw, ImageFont from PIL import Image, ImageDraw, ImageFont
import numpy as np import numpy as np
from itertools import zip_longest from itertools import zip_longest
import collections
app = Flask(__name__, static_url_path='', static_folder="static", template_folder="templates") app = Flask(__name__, static_url_path='', static_folder="static", template_folder="templates")
@ -29,10 +30,11 @@ thefile = None #selected file for description
positioninarray = 8 #counter positioninarray = 8 #counter
listofdicts=[] #to be able to import and use json content listofdicts=[] #to be able to import and use json content
datafromjson = [] datafromjson = []
max_wordpath_items = 200 # limit the nr. of items, as to
#test getting json file from id # #test getting json file from id
id = "17" # id = "17"
jsonfilefordescription = "files/"+id+"/"+id+".json" # jsonfilefordescription = "files/"+id+"/"+id+".json"
#arrays with the user path of words and numbers #arrays with the user path of words and numbers
pathofwords = [] pathofwords = []
@ -42,17 +44,18 @@ pathofnumbers = []
app.secret_key = 'your secret' app.secret_key = 'your secret'
app.config['SESSION_TYPE'] = 'filesystem' app.config['SESSION_TYPE'] = 'filesystem'
session = {} def setupSession():
# session should be configured from within request context
# so this function should be called on each request
if 'wordpath' not in session:
# Flask sessions are serialised into a cookie, so we cannot use the deque here
session['wordpath'] = [] session['wordpath'] = []
if 'clicktime' not in session:
session['clicktime'] = [] session['clicktime'] = []
if 'id' not in session:
session['id'] = [] session['id'] = []
session['veryfirstnow'] = None if 'veryfirstnow' not in session:
session['veryfirstnow'] = datetime.now().isoformat()
#VARS FOR THE SCORES
wordpath = []
idlist = []
timelist = []
timelistforoperations = []
# preparing the index.json file for the navbar # preparing the index.json file for the navbar
index_dict = {} index_dict = {}
@ -103,13 +106,10 @@ for path, subdirs, files in os.walk('./static/files/'):
@app.route("/") @app.route("/")
def home(): def home():
sessionid = "current_user.id" setupSession()
#add the very first time of connection to the interface
if session['veryfirstnow'] is None :
session['veryfirstnow'] = datetime.now()
return render_template('home.html', wordlist_dict=wordlist_dict) return render_template('home.html', wordlist_dict=wordlist_dict)
def functionsession(): def functionsession():
return(session) return(session)
@ -121,8 +121,7 @@ def context_processor():
@app.route('/about/') @app.route('/about/')
def about(): def about():
if session['veryfirstnow'] is None : setupSession()
session['veryfirstnow'] = datetime.now()
return render_template('about.html') return render_template('about.html')
@ -134,8 +133,7 @@ def about():
@app.route('/description') @app.route('/description')
def description(): def description():
if session['veryfirstnow'] is None : setupSession()
session['veryfirstnow'] = datetime.now()
idno=request.args.get('id') idno=request.args.get('id')
jsonfilefordescription = "files/"+idno+"/"+idno+".json" jsonfilefordescription = "files/"+idno+"/"+idno+".json"
@ -150,7 +148,13 @@ def description():
data_dict = json.load(f) data_dict = json.load(f)
datafromjson = data_dict["files"] datafromjson = data_dict["files"]
itemid = data_dict["id"] itemid = data_dict["id"]
session["id"].append(itemid) # a glitch of Flask sessions: if you do session['wordpath'].append() it creates an empty list
# hence we get it, append it, and set it.
# since Flask's session variables are json serialised (to be stored in a cookie), they do not
# support collections.deque, therefore we create that on each request to limit the items
ids = collections.deque(session['id'], maxlen=max_wordpath_items)
ids.append(itemid)
session["id"] = list(ids) # ... and therefore, we have to convert it back
for file in datafromjson: for file in datafromjson:
if file.lower().endswith(('.html')): if file.lower().endswith(('.html')):
with open("static/"+file,"r", encoding='utf-8') as f: with open("static/"+file,"r", encoding='utf-8') as f:
@ -161,13 +165,18 @@ def description():
@app.route('/diverge', methods=['GET']) @app.route('/diverge', methods=['GET'])
def diverge(): def diverge():
if session['veryfirstnow'] is None : setupSession()
session['veryfirstnow'] = datetime.now()
searchterm=request.args.get('search') searchterm=request.args.get('search')
now = datetime.now() #description time now = datetime.now() #description time
session['wordpath'].append(searchterm) # a glitch of Flask sessions: if you do session['wordpath'].append() it creates an empty list
session['clicktime'].append(now) # hence we get it, append it, and set it.
wp = collections.deque(session['wordpath'], maxlen=max_wordpath_items)
wp.append(searchterm)
session['wordpath'] = list(wp)
clicktime = collections.deque(session['clicktime'], maxlen=max_wordpath_items)
clicktime.append(now.isoformat()) # make sure we have a determined format to stringify
session['clicktime'] = list(clicktime)
return render_template('diverge.html', wordlist_dict=wordlist_dict, searchterm=searchterm, index_dict=index_dict) return render_template('diverge.html', wordlist_dict=wordlist_dict, searchterm=searchterm, index_dict=index_dict)
# @app.route('/listofwords') # @app.route('/listofwords')
@ -188,8 +197,7 @@ def diverge():
@app.route("/get-file") @app.route("/get-file")
def get_file(): def get_file():
if session['veryfirstnow'] is None : setupSession()
session['veryfirstnow'] = datetime.now()
fullscore = None fullscore = None
@ -203,20 +211,23 @@ def get_file():
tadam = None tadam = None
initialtime = None initialtime = None
if not (timelist[0] is None): if len(timelist) and not (timelist[0] is None):
thetime = timelist[0] thetime = timelist[0]
thetime = str(thetime) thetime = str(thetime)
thetime = dt.datetime.strptime(thetime, '%Y-%m-%d %H:%M:%S.%f') print(thetime)
initialtime = thetime - veryfirstnow thetime = dt.datetime.strptime(thetime, "%Y-%m-%dT%H:%M:%S.%f")
firsttime = dt.datetime.strptime(veryfirstnow, "%Y-%m-%dT%H:%M:%S.%f")
initialtime = thetime - firsttime
initialtime = initialtime.total_seconds() initialtime = initialtime.total_seconds()
initialtime = int(initialtime) initialtime = int(initialtime)
initialtime = "."*initialtime initialtime = "."*initialtime
print(initialtime) print(initialtime)
timelistforoperations = []
for t in timelist : for t in timelist :
t = str(t) t = str(t)
yo = dt.datetime.strptime(t, '%Y-%m-%d %H:%M:%S.%f') yo = dt.datetime.strptime(t, "%Y-%m-%dT%H:%M:%S.%f")
timelistforoperations.append(yo) timelistforoperations.append(yo)
prev = None prev = None
@ -247,7 +258,7 @@ def get_file():
# print(difftime) # print(difftime)
else: else:
yo = str(veryfirstnow) yo = str(veryfirstnow)
yoyo = dt.datetime.strptime(yo, '%Y-%m-%d %H:%M:%S.%f') yoyo = dt.datetime.strptime(yo, '%Y-%m-%dT%H:%M:%S.%f')
difftime = time - yoyo difftime = time - yoyo
difftime = difftime.total_seconds() difftime = difftime.total_seconds()
@ -313,9 +324,6 @@ def get_file():
"attachment;filename=yourveryspecialscore.txt"}) "attachment;filename=yourveryspecialscore.txt"})
###################################################################################### ######################################################################################
#INDEX PAGE #INDEX PAGE
###################################################################################### ######################################################################################

Loading…
Cancel
Save