Securing your Python web applications is essential to protect user data and build trust. One popular way to achieve this is by using Let's Encrypt, a free and automated certificate authority that provides SSL/TLS certificates. This guide explains how to set up Let's Encrypt with common Python web frameworks like Django and Flask.
Prerequisites
- A server with a public IP address
- Root or sudo access to the server
- Domain name pointing to your server
- Python installed (version 3.6+ recommended)
- Web server (Apache, Nginx, or similar)
Installing Certbot
Certbot is the recommended client for obtaining and renewing Let's Encrypt certificates. Install Certbot on your server using your package manager. For example, on Ubuntu:
sudo apt update
sudo apt install certbot
Obtaining a Certificate
Use Certbot to request a certificate for your domain. For example, with Nginx:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
Follow the prompts to complete the process. Certbot will automatically configure your web server to use SSL.
Configuring Django or Flask
Once your server has SSL enabled, ensure your application uses HTTPS. For Django, update your settings.py:
SECURE_SSL_REDIRECT = True
For Flask, run your app behind a secure proxy or web server that handles SSL termination. You can also enforce HTTPS within Flask:
from flask_sslify import SSLify
sslify = SSLify(app)
Renewing Certificates
Let's Encrypt certificates are valid for 90 days. Certbot sets up automatic renewal by default. To test renewal, run:
sudo certbot renew --dry-run
Conclusion
Using Let's Encrypt with your Python web frameworks enhances security without additional costs. By following these steps, you can easily obtain, install, and renew SSL certificates, ensuring your web applications are protected and trustworthy.