


To create a sign-in page for a blog using Python, you’ll need a web framework like Flask or Django to handle user authentication. Below is a step-by-step guide using Flask (a lightweight framework) for simplicity.
1. Prerequisites
- Install Python and required libraries:
pip install flask flask-sqlalchemy flask-login flask-wtf bcrypt
2. Project Structure
your_blog/ ├── app.py ├── templates/ │ └── login.html └── models.py
3. Set Up Flask App and Database
app.py
from flask import Flask, render_template, redirect, url_for, flash from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import DataRequired, Email import bcrypt app = Flask(__name__) app.config['SECRET_KEY'] = 'your-secret-key' # Replace with a secure key app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db' # SQLite database db = SQLAlchemy(app) login_manager = LoginManager(app) login_manager.login_view = 'login' # User Model (in models.py or here) class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(100), unique=True) password = db.Column(db.String(100)) # Login Form class LoginForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email()]) password = PasswordField('Password', validators=[DataRequired()]) submit = SubmitField('Sign In') @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) # Routes @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user and bcrypt.checkpw(form.password.data.encode('utf-8'), user.password): login_user(user) flash('Logged in successfully!', 'success') return redirect(url_for('dashboard')) # Redirect to blog dashboard else: flash('Invalid email or password.', 'danger') return render_template('login.html', form=form) @app.route('/dashboard') @login_required def dashboard(): return "Welcome to your blog dashboard!" if __name__ == '__main__': with app.app_context(): db.create_all() # Create database tables app.run(debug=True)
4. Create the Sign-In Page Template
templates/login.html
<!DOCTYPE html> <html> <head> <title>Sign In</title> </head> <body> <h1>Sign In to Your Blog</h1> {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} <div class="alert alert-{{ category }}">{{ message }}</div> {% endfor %} {% endif %} {% endwith %} <form method="POST"> {{ form.hidden_tag() }} <div> {{ form.email.label }}<br> {{ form.email(size=30) }} </div> <div> {{ form.password.label }}<br> {{ form.password(size=30) }} </div> <div> {{ form.submit() }} </div> </form> <p>Don't have an account? <a href="{{ url_for('register') }}">Register here</a>.</p> </body> </html>
5. Key Features Explained
- User Authentication:
- Uses
flask-login
to manage user sessions. - Passwords are hashed with
bcrypt
for security.
- Form Handling:
flask-wtf
creates secure forms with validation (e.g., email format).
- Database:
- Stores user credentials in SQLite (replace with PostgreSQL/MySQL for production).
- Security:
- CSRF protection (enabled by Flask-WTF).
- Password hashing (never store plaintext passwords!).
6. Test the Sign-In Page
- Run the app:
python app.py
- Visit
http://localhost:5000/login
in your browser. - Use a test user (create one via Flask shell first):
from app import app, db, User with app.app_context(): hashed_password = bcrypt.hashpw('your_password'.encode('utf-8'), bcrypt.gensalt()) user = User(email='user@example.com', password=hashed_password) db.session.add(user) db.session.commit()
7. Next Steps
- Add a registration page to create new users.
- Implement password reset functionality.
- Use CSS/JavaScript to style the page.
- Deploy with Gunicorn + Nginx for production.
Example Workflow
- User enters email/password → form validates input.
- Server checks credentials → logs user in or shows error.
- Authenticated users access protected routes (e.g.,
/dashboard
).
For a Django version, use Django’s built-in django.contrib.auth
module. Let me know if you’d like a Django-specific guide! 🚀
No Responses