Now that you have a cool website, maybe you want to have users so that you can allow people to further customize their experience. Here on PythonProgramming.net, we track the tutorials that users complete, for example, customizing the view based on completed tutorials.
Creating a user system is no simple undertaking, however. Consider all of the implications involved with a user-system:
Flask does come with a few methods for handling users and logging in. We will make use of at least the sessions, but I have not come to enjoy most of the available choices. I wound up mostly making my own system, which is not recommended. I will show my methodology, but I encourage you to try the Flask versions as well, maybe they will make more sense to you, or maybe they will be improved by the time you are reading this tutorial.
Regardless of what you specifically do regarding users and logins, the next tutorials will still be useful to you, covering things like encryption, databases, sql injections, dynamic content based on users...etc, all of which you will likely find useful to know.
To have users, we'll need a login page, so let's add one by adding the following function to our __init__.py file:
@app.route('/login/', methods=["GET","POST"]) def login_page(): return render_template("login.html")
The only unfamiliar thing here might be the GET and POST methods.
GET and POST are request methods that allow people to interact with the server.
GET allows the user to retrieve data, and POST allows them to submit data.
Now we need a login.html template:
{% extends "header.html" %} {% block body %} <body> <div class="container"> <br> <h4>Please Login:</h4> <br> <form action="" class="form-inline" method="post"> <input type="text" class="form-control" placeholder = "Username" name="username" value="{{request.form.username}}"> <input type="password" class="form-control" placeholder = "Password" name="password" value="{{request.form.password}}"> <input class="btn btn-default" type="submit" value="Login"> </form> </div> </body> {% endblock %}
Simple enough, the login.html page contains a form with a submit button. The form allows for a username and password to be input and submitted. Here, the password will also be input as asterisks, and hidden.
Now we have a login page, which we can even use. We can type in any username and any password here, and submit the form, though nothing will happen. While we're allowing the GET and POST requests, we're not actually doing anything with them. That's what we're going to cover next.