Flask - Before_request Login
In Progress!

Flask References:



Code example using app.before_request

  1. The following code has a notion of a session based on the cookie used by a browser.
  2. Thus - more than one window or tab in a browser will share the same cookie, and will have the same login status.
  3. Using a different browser will result in a different login status.
  4. The secret key should be hard to guess in a real application, of course.
  5. ALL pages require login in this approach, since before_request is called before all requests.
  6. Be sure to do app.run() LAST, so Python sees the names of the functions before it runs the code.
  7. And before_request BEFORE the app.route calls.
from flask import Flask, redirect, render_template, request, session, url_for
app = Flask(__name__)

# following is required to use session, as in session['x']

app.secret_key = "something" # ND

@app.before_request
def before_request():
   if 'visited' in session:
      pass
   else:
      return login()
# code below will not run code in login() function       
#         return render_template("login.html")

@app.route('/login', methods=['GET', 'POST'])
def login():
   if request.method == 'POST':
      u =  request.form['username']
      p =  request.form['password']
      if u == 'admin' and p == 'password':
         session['visited'] = True
         return redirect(url_for('home'))
      else:
         message = "wrong credentials"
   else:
      message = "you must log in"
   return render_template("login.html", error=message)

@app.route('/logout', methods=['GET', 'POST'])
def logout():
   if 'visited' in session:
      session.pop('visited')
   message = "Logged out successfully"
   return render_template("login.html", error=message)

# standard run host server command:  
# More reliable:
if __name__ == "__main__":
    app.run(debug=True)

End of example.


Screens:

/ page
/update.html page

Notes:


Code:

# w8_v02.py

# from ip2geotools.databases.noncommercial import DbIpCity
# response = DbIpCity.get('147.229.2.90', api_key='free')
# print (response)

def s01 (st):
   return  """
   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
   <html>
      <head>
        
         <meta http-equiv="content-type" content="text/html; charset=UTF-8">
         <title>""" + st + """</title></head><body>"""
        
sib = """
         <h1>Login type POST:</h1>
         <ul>
         <li>form: action=login method=post
         <li>label: User Name:
         <li>input: type=text name=un
         <li>label: Password:
         <li>input: type=password name=pwd
         <li>input: type="submit" class=submit value="log in"
         </ul>
         <form action=/ method=post>
            <label>User Name:</label>
            <input type=text name=un>
            <br>
            <label>Password:</label>
            <input type=password name=pwd>
            <br>
            <input type="submit" value="log in">
         </form>
"""

s99 = """</body></html>"""

sic = """
         <h1>Login type POST:</h1>
         <form action=update.html method=post>
            <label>New Password:</label>
            <input type=password name=pwda>
            <br>
            <label>Confirm New Password:</label>
            <input type=password name=pwdb>
            <br>
            <input type="submit" value="Accept">
            <input type="submit" value="Cancel" formaction=/>
         </form>
"""

users = {"admin":"123", "nick":"abc"}
ip = "1.1.1.1"
a = "a"
b = "b"
st = "empty"

from flask import Flask
from flask import request, redirect

app = Flask(__name__)

# @app.route("/index.html", methods=['GET', 'POST'])
# @app.route('/login', methods=['GET', 'POST'])
@app.route('/', methods=['GET', 'POST'])

def helloIndex():
   global a, b, ip, st
   pg = s01("version 01") + sib + s99
   ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
   st = "ip: " + ip + " - request: " + str(request)
   print (st)
   a = request.form.get ("un")
   b = request.form.get ("pwd")
# User found:
   if a != None and users.get(a) == b:
      pg = redirect ("/update.html")
# User NOT found:
   return pg

# do both get & post to get POST values
# default is just get values
@app.route('/update.html', methods=['GET', 'POST'])

# http://10.0.0.66:8080/update.html
def update():
   if request.method == 'POST':
      w1 = request.form
      u   = str(w1.get("pwda"))
      p   = str(w1.get("pwdb"))
      print ("---- URL: " + request.url + " ---- Posting: " + str(w1))
      return redirect ("/")
   print ("Getting")
   s2  = str(s01 ("w8_02.py, version 02"))
   s2 += "st: " + st + "<p>"
   s2 += sic
   s2 += s99
   return s2

# standard run host server command:  
# app.run(host='0.0.0.0', port= 8080)
# More reliable:
if __name__ == "__main__":
    app.run(host='0.0.0.0', port= 8080, debug=True)


Port

If you get a "OSError: [Errno 48] Address already in use" kind of error, (on port 5000) try:
In a Unix-like environment, try - for port 5000 here, get pid and kill it:

(end)