Flask is a popular Python web framework that makes it easy to build web applications quickly. In this tutorial, we’ll walk through the steps of creating a simple login page using Flask.
Before we begin, make sure you have Flask installed on your machine. You can install Flask by running the following command:
pip install Flask
Once Flask is installed, create a new file called app.py
and import the Flask module:
from flask import Flask
Next, create an instance of the Flask class and assign it to the variable app
. This will be the main entry point for our application:
app = Flask(__name__)
Now we can define a route for the login page. A route is a URL pattern that is mapped to a function. In this case, we’ll create a function called login
that will handle the logic for our login page. To define a route, we use the @app.route
decorator.
@app.route('/login')
def login():
return 'This is the login page'
This route will be accessed at the URL /login
, and will return the string ‘This is the login page’ when a user visits that URL.
Now let’s add some HTML to our login page. We can do this by returning a template from our login
function. Flask uses Jinja templates, which allow us to insert variables into our HTML code.
First, create a folder called templates
and create a new file called login.html
inside it. Inside login.html
, add the following HTML code:
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Login</h1>
<form action="/login" method="post">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
This HTML code creates a simple login form with a username and password field, as well as a submit button. The form action is set to /login
, which means that when the form is submitted, it will send a POST request to the /login
route that we defined earlier.
Next, we’ll update our login
function to render this template. To do this, we’ll need to import the render_template
function from Flask and use it to render the login.html
template:
from flask import Flask, render_template
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# handle login logic here
return 'Login successful'
else:
return render_template('login.html')
Now when a user visits the /login
URL, they will see the login form that we created. When they submit the form, the login
function will be called with the POST
method and will handle the login logic.
To handle the login logic, we’ll need to add some code to check the submitted username and password against a list of valid credentials. Let’s start by adding a dictionary of valid users and their passwords to our app.py
file:
users = {
'user1': 'password1',
'user2': 'password2'
}
Then, we can update our login
function to check the submitted username and password against this dictionary:
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if username in users and users[username] == password:
return 'Login successful'
else:
return 'Invalid username or password'
else:
return render_template('login.html')
This code first retrieves the submitted username and password from the request.form
dictionary. It then checks if the username is in the users
dictionary and if the corresponding password is correct. If both conditions are true, it returns ‘Login successful’. If either condition is false, it returns
‘Invalid username or password’.
Now that we have a basic login page, there are a few additional features that we might want to add.
First, we can add a session to our login page to keep track of logged in users. To do this, we’ll need to import the session
object from Flask and set a session variable when a user logs in:
from flask import Flask, render_template, request, session
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if username in users and users[username] == password:
session['username'] = username
return 'Login successful'
else:
return 'Invalid username or password'
else:
return render_template('login.html')
We can then use the session
object to check if a user is logged in on other pages of our application. For example, we might want to display a different message on the login page for logged in users:
@app.route('/login', methods=['GET', 'POST'])
def login():
if 'username' in session:
return 'You are already logged in'
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if username in users and users[username] == password:
session['username'] = username
return 'Login successful'
else:
return 'Invalid username or password'
else:
return render_template('login.html')
We can also add a logout feature by adding a /logout
route that clears the session
object:
@app.route('/logout')
def logout():
session.clear()
return 'You have been logged out'
Finally, we’ll need to configure our application to use sessions. To do this, we’ll need to set a secret key for our application and enable the session
object:
app = Flask(__name__)
app.secret_key = 'my-secret-key'
# rest of the code here
With these changes, our login page is now complete. Users can log in and out of our application using the provided form, and the session
object will keep track of their login status.
full Flask Code :
from flask import Flask, render_template, request, session
app = Flask(__name__)
app.secret_key = 'my-secret-key'
users = {
'user1': 'password1',
'user2': 'password2'
}
@app.route('/login', methods=['GET', 'POST'])
def login():
if 'username' in session:
return 'You are already logged in'
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if username in users and users[username] == password:
session['username'] = username
return 'Login successful'
else:
return 'Invalid username or password'
else:
return render_template('login.html')
@app.route('/logout')
def logout():
session.clear()
return 'You have been logged out'
if __name__ == '__main__':
app.run()
Don’t forget to create a templates
folder and add the login.html
template file with the HTML code provided earlier in the tutorial.
That completes the tutorial on creating a login page with Flask. However, there are many other features and considerations that you might want to add to your login page, depending on your specific needs and requirements.
For example, you might want to add support for multiple users or roles, or add additional security measures such as two-factor authentication or password hashing. You might also want to consider integrating your login page with a database to store user information and credentials.
There are also many other features and libraries available for Flask that you might find useful when building your login page and other web applications. Some popular examples include:
- Flask-SQLAlchemy: A library for integrating Flask with a SQL database, such as MySQL or PostgreSQL
- Flask-WTF: A library for creating and validating forms in Flask
- Flask-Login: A library for handling user authentication and session management in Flask
By exploring these and other resources, you can build a more feature-rich and secure login page for your Flask application.
I hope this helps! If you have any other questions or need further assistance, don’t hesitate to ask.