Compare commits

...

2 Commits

Author SHA1 Message Date
Ruben van de Ven e866dd28ce Apply changes made on the server 5 years ago
Ruben van de Ven 69ab0cc31a Fix sessions and score generation 5 years ago
  1. 106
      contextualise.py
  2. 2
      static/.gitignore
  3. 14
      static/css/main.css
  4. 1
      templates/description.html
  5. 2
      templates/home.html

106
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 = 500 # limit the nr. of items, as to prevent possible glitches with bots
#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['wordpath'] = [] # session should be configured from within request context
session['clicktime'] = [] # so this function should be called on each request
session['id'] = [] if 'wordpath' not in session:
session['veryfirstnow'] = None # Flask sessions are serialised into a cookie, so we cannot use the deque here
session['wordpath'] = []
#VARS FOR THE SCORES if 'clicktime' not in session:
wordpath = [] session['clicktime'] = []
idlist = [] if 'id' not in session:
timelist = [] session['id'] = []
timelistforoperations = [] if 'veryfirstnow' not in session:
session['veryfirstnow'] = datetime.now().isoformat()
# 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"
@ -146,28 +144,41 @@ def description():
#open json file, list filepaths in array and loop with thefile #open json file, list filepaths in array and loop with thefile
textfile="" textfile=""
textfiles=[] textfiles=[]
namefile=[]
with open("static/"+jsonfilefordescription, 'r') as f: with open("static/"+jsonfilefordescription, 'r') as f:
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')):
namefile.append(file)
with open("static/"+file,"r", encoding='utf-8') as f: with open("static/"+file,"r", encoding='utf-8') as f:
textfile = f.read() textfile = f.read()
textfile = Markup(textfile) textfile = Markup(textfile)
textfiles.append(textfile) textfiles.append(textfile)
return render_template('description.html', datafromjson=datafromjson, itemid=itemid, textfiles=textfiles, idno=idno, index_dict=index_dict) return render_template('description.html', datafromjson=datafromjson, itemid=itemid, textfiles=textfiles, idno=idno, index_dict=index_dict, namefile=namefile)
@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 +199,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
@ -198,25 +208,38 @@ def get_file():
timelist = session["clicktime"] timelist = session["clicktime"]
veryfirstnow = session['veryfirstnow'] veryfirstnow = session['veryfirstnow']
clickongetfiletime = datetime.now() clickongetfiletime = datetime.now()
tadam = None tadam = None
initialtime = None initialtime = None
if not (timelist[0] is None): # USER IP ADDRESS OBTENTION
if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
userip = request.environ['REMOTE_ADDR']
else:
userip = request.environ['HTTP_X_FORWARDED_FOR'] # if behind a proxy
# CALCULATION OF INITIAL TIME BEFORE FIRST CLICK
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)
#CALCULATE FILE NUMBER
dirListing = os.listdir("scores/")
scorenumber = len(dirListing)
# CONVERSION OF TIME INTO FORMATS THAT CAN BE USED FOR CALCULATIONS
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
@ -228,7 +251,7 @@ def get_file():
print(timelistforoperations) print(timelistforoperations)
print(idlist) print(idlist)
# WEAVING DELAYS AND WORDS TOGETHER AS A HUGE STRING OF CHARACTERS
for (word, time) in zip(wordpath,timelistforoperations): for (word, time) in zip(wordpath,timelistforoperations):
# for (word, time, uniqueid) in zip(wordpath,timelistforoperations, idlist): # for (word, time, uniqueid) in zip(wordpath,timelistforoperations, idlist):
# print("word : "+word+"\n") # print("word : "+word+"\n")
@ -247,7 +270,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()
@ -292,7 +315,7 @@ def get_file():
# Using list comprehension # Using list comprehension
out = [(fullscore[i:i+n]) for i in range(0, len(fullscore), n)] out = [(fullscore[i:i+n]) for i in range(0, len(fullscore), n)]
#joining the strings with linebreaks #joining the strings with linebreaks
tadam = '\n'.join(out) tadam = '\n'.join(out) +"\n\nScore number : "+str(scorenumber)+ "\nGenerated at : "+str(clickongetfiletime)+"\nBy author : "+ userip
# have a message in file if no nav has been recorded so it's less dull than error page # have a message in file if no nav has been recorded so it's less dull than error page
if tadam is None: if tadam is None:
@ -313,9 +336,6 @@ def get_file():
"attachment;filename=yourveryspecialscore.txt"}) "attachment;filename=yourveryspecialscore.txt"})
###################################################################################### ######################################################################################
#INDEX PAGE #INDEX PAGE
###################################################################################### ######################################################################################

2
static/.gitignore

@ -0,0 +1,2 @@
files

14
static/css/main.css

@ -66,6 +66,14 @@ h2,h3{
a{ a{
color: black; color: black;
} }
div.home > a{
border-bottom: 1px dashed black;
padding: 0.1em;
margin: 0.5em;
line-height: 1.5em;
}
.text a:visited{ .text a:visited{
color: red; color: red;
} }
@ -111,12 +119,12 @@ div.homecontent{
div.home{ div.home{
/* padding: 1em 5em 1em 7.5em; */ /* padding: 1em 5em 1em 7.5em; */
padding-left: 9em; padding-left: 15em;
padding-top: 2em; padding-top: 2em;
padding-bottom: 3em; padding-bottom: 3em;
padding-right: 0.5em; padding-right: 5em;
text-align: justify; text-align: justify;
font-size: 1em; font-size: 0.8em;
} }
div.home a{ div.home a{

1
templates/description.html

@ -27,6 +27,7 @@
{% set count=[0] %} {% set count=[0] %}
{% for item in datafromjson %} {% for item in datafromjson %}
{% if item.lower().endswith(('.html')) %} {% if item.lower().endswith(('.html')) %}
<h3> {{ namefile[count[0]][12:-5] }}</h3>
{{ textfiles[count[0]] }} {{ textfiles[count[0]] }}
{% if count.append(count.pop() + 1) %}{% endif %} {% if count.append(count.pop() + 1) %}{% endif %}
<br/><br/><br/> <br/><br/><br/>

2
templates/home.html

@ -11,7 +11,7 @@
{% for word in wordlist_dict %} {% for word in wordlist_dict %}
{% set address = "/diverge?search=" + word %} {% set address = "/diverge?search=" + word %}
<a href={{address}}>{{ word }}</a> <a href={{address}}>{{ word }}</a>
{% endfor %} {% endfor %}
</div> </div>

Loading…
Cancel
Save