Compare commits

...

2 Commits

Author SHA1 Message Date
Ruben van de Ven e866dd28ce Apply changes made on the server 4 years ago
Ruben van de Ven 69ab0cc31a Fix sessions and score generation 4 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
import numpy as np
from itertools import zip_longest
import collections
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
listofdicts=[] #to be able to import and use json content
datafromjson = []
max_wordpath_items = 500 # limit the nr. of items, as to prevent possible glitches with bots
#test getting json file from id
id = "17"
jsonfilefordescription = "files/"+id+"/"+id+".json"
# #test getting json file from id
# id = "17"
# jsonfilefordescription = "files/"+id+"/"+id+".json"
#arrays with the user path of words and numbers
pathofwords = []
@ -42,17 +44,18 @@ pathofnumbers = []
app.secret_key = 'your secret'
app.config['SESSION_TYPE'] = 'filesystem'
session = {}
session['wordpath'] = []
session['clicktime'] = []
session['id'] = []
session['veryfirstnow'] = None
#VARS FOR THE SCORES
wordpath = []
idlist = []
timelist = []
timelistforoperations = []
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'] = []
if 'clicktime' not in session:
session['clicktime'] = []
if 'id' not in session:
session['id'] = []
if 'veryfirstnow' not in session:
session['veryfirstnow'] = datetime.now().isoformat()
# preparing the index.json file for the navbar
index_dict = {}
@ -103,13 +106,10 @@ for path, subdirs, files in os.walk('./static/files/'):
@app.route("/")
def home():
sessionid = "current_user.id"
#add the very first time of connection to the interface
if session['veryfirstnow'] is None :
session['veryfirstnow'] = datetime.now()
setupSession()
return render_template('home.html', wordlist_dict=wordlist_dict)
def functionsession():
return(session)
@ -121,8 +121,7 @@ def context_processor():
@app.route('/about/')
def about():
if session['veryfirstnow'] is None :
session['veryfirstnow'] = datetime.now()
setupSession()
return render_template('about.html')
@ -134,8 +133,7 @@ def about():
@app.route('/description')
def description():
if session['veryfirstnow'] is None :
session['veryfirstnow'] = datetime.now()
setupSession()
idno=request.args.get('id')
jsonfilefordescription = "files/"+idno+"/"+idno+".json"
@ -146,28 +144,41 @@ def description():
#open json file, list filepaths in array and loop with thefile
textfile=""
textfiles=[]
namefile=[]
with open("static/"+jsonfilefordescription, 'r') as f:
data_dict = json.load(f)
datafromjson = data_dict["files"]
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:
if file.lower().endswith(('.html')):
namefile.append(file)
with open("static/"+file,"r", encoding='utf-8') as f:
textfile = f.read()
textfile = Markup(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'])
def diverge():
if session['veryfirstnow'] is None :
session['veryfirstnow'] = datetime.now()
setupSession()
searchterm=request.args.get('search')
now = datetime.now() #description time
session['wordpath'].append(searchterm)
session['clicktime'].append(now)
# 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.
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)
# @app.route('/listofwords')
@ -188,8 +199,7 @@ def diverge():
@app.route("/get-file")
def get_file():
if session['veryfirstnow'] is None :
session['veryfirstnow'] = datetime.now()
setupSession()
fullscore = None
@ -198,25 +208,38 @@ def get_file():
timelist = session["clicktime"]
veryfirstnow = session['veryfirstnow']
clickongetfiletime = datetime.now()
tadam = 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 = str(thetime)
thetime = dt.datetime.strptime(thetime, '%Y-%m-%d %H:%M:%S.%f')
initialtime = thetime - veryfirstnow
print(thetime)
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 = int(initialtime)
initialtime = "."*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 :
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)
prev = None
@ -228,7 +251,7 @@ def get_file():
print(timelistforoperations)
print(idlist)
# WEAVING DELAYS AND WORDS TOGETHER AS A HUGE STRING OF CHARACTERS
for (word, time) in zip(wordpath,timelistforoperations):
# for (word, time, uniqueid) in zip(wordpath,timelistforoperations, idlist):
# print("word : "+word+"\n")
@ -247,7 +270,7 @@ def get_file():
# print(difftime)
else:
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 = difftime.total_seconds()
@ -292,7 +315,7 @@ def get_file():
# Using list comprehension
out = [(fullscore[i:i+n]) for i in range(0, len(fullscore), n)]
#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
if tadam is None:
@ -313,9 +336,6 @@ def get_file():
"attachment;filename=yourveryspecialscore.txt"})
######################################################################################
#INDEX PAGE
######################################################################################

2
static/.gitignore

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

14
static/css/main.css

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

1
templates/description.html

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

2
templates/home.html

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

Loading…
Cancel
Save