Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Flask login without Database in Python
Flask, a lightweight web framework for Python, offers various tools and libraries for building dynamic web applications. When it comes to implementing user authentication in Flask, developers often turn to traditional database systems. However, there are cases where using a database might be unnecessary or overkill, such as small-scale applications or rapid prototyping. In such scenarios, implementing a Flask login system without a database can be a simple and efficient solution. By using memory data structures and Flask's session object, developers can create a basic login system that stores user information without the need for a database.
Setting Up Flask
To start setting up Flask, you will need to install it on your local machine. Installing Flask is a simple process using the pip package manager ?
pip install flask
This command will download and install Flask along with any necessary dependencies.
Creating the Flask Application
Let's create a complete Flask application with login functionality. Create a new file called app.py and add the following code ?
from flask import Flask, render_template, request, redirect, url_for, session
app = Flask(__name__)
app.secret_key = "your_secret_key_here"
# In-memory user storage (replace with your users)
users = {
'admin': 'password',
'user1': 'mypass123',
'demo': 'demo'
}
@app.route('/')
def index():
if 'username' in session:
return redirect(url_for('home'))
return redirect(url_for('login'))
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
# Validate user credentials
if username in users and users[username] == password:
session['username'] = username
return redirect(url_for('home'))
else:
return render_template('login.html', error='Invalid credentials')
return render_template('login.html')
@app.route('/home')
def home():
if 'username' not in session:
return redirect(url_for('login'))
return render_template('home.html')
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(debug=True)
Creating Templates
Login Template
Create a templates directory and add login.html ?
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<style>
body { font-family: Arial; margin: 50px; }
form { max-width: 300px; }
input { margin: 10px 0; padding: 8px; width: 100%; }
.error { color: red; }
</style>
</head>
<body>
<h1>Login</h1>
{% if error %}
<p class="error">{{ error }}</p>
{% endif %}
<form method="POST">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<input type="submit" value="Login">
</form>
<p>Try: admin/password or user1/mypass123</p>
</body>
</html>
Home Template
Create home.html in the templates directory ?
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<style>
body { font-family: Arial; margin: 50px; }
.welcome { color: green; }
a { background: #007bff; color: white; padding: 10px; text-decoration: none; border-radius: 4px; }
</style>
</head>
<body>
<h1 class="welcome">Welcome, {{ session['username'] }}!</h1>
<p>You have successfully logged in without a database.</p>
<a href="{{ url_for('logout') }}">Logout</a>
</body>
</html>
How It Works
The login system works by storing user credentials in a Python dictionary (users) instead of a database. When a user submits the login form, Flask validates the credentials against this dictionary. If valid, the username is stored in the session, allowing access to protected pages.
Key components:
-
Session Management: Flask's
sessionobject stores user state - In-Memory Storage: User credentials stored in a Python dictionary
- Route Protection: Check for session data before allowing access
Running the Application
Save all files and run the application ?
python app.py
The output will show ?
* Running on http://127.0.0.1:5000 * Debug mode: on
Open your browser and navigate to http://127.0.0.1:5000 to test the login system.
Security Considerations
While this approach works for development and small applications, consider these limitations:
- Passwords are stored in plain text (use hashing in production)
- User data is lost when the application restarts
- No user registration or password reset functionality
- Limited scalability for multiple users
Conclusion
Implementing a Flask login system without a database provides a lightweight solution for simple applications and prototypes. Using Flask sessions and in-memory storage, you can quickly create functional authentication. However, for production applications requiring robust security and user management, consider transitioning to a database-backed system.
