from flask import Flask, request, abort, url_for, redirect # This is a really simplistic way of doing logins. It works-ish, but is very limited. # It's presented as an intermediate between "doing forms" and "proper sessions." app = Flask(__name__) # just using a simple dict here; this stuff would usually be in a database. users = {"alice": "qwert", "bob": "asdfg", "charlie": "zxcvb"} loginPage = """ Basic form
""" curProfile = """ Your profile! Welcome back! """ otherProfile = """ {user}'s profile! This is {user}'s profile page. """ # hop on over to the login page. @app.route("/") def default(): return redirect(url_for("login")) # the form's "action" attribute is the URL to POST to. @app.route("/login/") def login(): return loginPage.format(url=url_for("profile")) # multiple decorators can appear on one declaration. it's like nesting # function calls. f(g(x)). @app.route("/profile/", methods=["GET", "POST"]) @app.route("/profile/", methods=["GET", "POST"]) def profile(username=None): # note the username parameter - if there is a username given in the path, it will be # filled in here. if request.method == "POST": if not username: if users[request.form["user"]] == request.form["pass"]: return curProfile else: abort(401) elif username in users: return redirect(url_for("profile", username=request.form["user"])) else: abort(404) else: if username and username in users: return otherProfile.format(user=username) else: abort(404) # we can set up custom handlers for errors; this way we can serve our own 404 page for instance. @app.errorhandler(404) def fourohfour(error): return "FOUR OH FOOOOOUR!!!!!!!!", 404 if __name__ == "__main__":