← flask-blog

sessions, request hooks- l14

66f1531baa09e3575e118c85633399fba4cbe12e · ovidiucs · May 14, 2015 10:32

+25 −5 · 3 files changed

  • flask-blog.py +16 −5
  • templates/other.html +5 −0
  • templates/session.html +4 −0
diff --git a/flask-blog.py b/flask-blog.py
index 8680696..d6fa8b1 100644
--- a/flask-blog.py
+++ b/flask-blog.py
@@ -1,6 +1,7 @@
 import os
 import imghdr
-from flask import Flask, render_template, request, session
+from datetime import datetime
+from flask import Flask, render_template, request, session, g
 from flask.ext.bootstrap import Bootstrap
 from flask.ext.wtf import Form
 from wtforms import StringField, SubmitField, FileField, ValidationError
@@ -92,13 +93,23 @@ def index4():
     return render_template('upload.html', form=form, image=image)
 
 
-@app.route('/session')
-def index5():
-    if 'count' not in session:
+@app.before_request
+def before_request():
+    if not 'count' in session:
         session['count'] = 1
     else:
         session['count'] += 1
-    return render_template('session.html', count=session['count'])
+    g.when = datetime.now().strftime('%H:%M:%S')
+
+
+@app.route('/session')
+def index5():
+    return render_template('session.html', count=session['count'], when=g.when)
+
+
+@app.route('/other')
+def index6():
+    return render_template('other.html', count=session['count'], when=g.when)
 
 @app.errorhandler(404)
 def not_found(e):
diff --git a/templates/other.html b/templates/other.html
new file mode 100644
index 0000000..4445c37
--- /dev/null
+++ b/templates/other.html
@@ -0,0 +1,5 @@
+<h1>Other Page</h1>
+<p>You have a total of {{ count }} page views in this site, the last of which
+    was at {{ when }}.</p>
+<p><a href="{{ url_for('index5') }}">Click here</a>to see the session page
+    .</p>
\ No newline at end of file
diff --git a/templates/session.html b/templates/session.html
new file mode 100644
index 0000000..1e8668e
--- /dev/null
+++ b/templates/session.html
@@ -0,0 +1,4 @@
+<h1>Index Page</h1>
+<p>You have a total of {{ count }} page views in this site, the last of which
+    was at {{ when }}.</p>
+<p><a href="{{ url_for('index6') }}">Click here</a> to see the other page.</p>
\ No newline at end of file