May 14, 2021 Django
The Internet is a hostile environment. Before you deploy a Django project, you should spend some time checking settings, considering security, performance, and operations.
Django contains many security features. S ome are built-in and always enabled. O ther options are optional because they are not always appropriate or because they are not easy to develop. For example, forcing HTTPS may not be available for all sites and is impractical for local development.
Performance optimization is another trade-off. F or example, caching is useful in production and not for local development. The requirements for error reporting are also very different.
The following list includes the following settings:
Many of these settings are sensitive and should be considered confidential. If you want to publish the source code for your project, it is common practice to publish the appropriate settings for development and use a private setup module for production.
Use this option to automate some of the checks described below. Make sure that you follow the instructions in the option documentation to run it for the production setup file.
check --deploy
The key must be a large random value and must be kept confidential.
Ensure that keys used in production are not used anywhere else and avoid submitting them to source control. This reduces the number of vectors from which an attacker can obtain a key.
Instead of hard-coding the key in the settings module, consider loading the key from an environment variable:
import os SECRET_KEY = os.environ['SECRET_KEY']
Or from a file:
with open('/etc/secret_key.txt') as f: SECRET_KEY = f.read().strip()
You must never enable debugging in production.
Of course, you are using development for your project, as this will enable convenient features such as full traceability in your browser. DEBUG = True
However, this is a very bad idea for a production environment because it reveals a lot of information about the project: excerpts from the source code, local variables, settings, libraries used, and so on.
At that time, Django simply couldn't work without the right values. DEBUG = FalseALLOWED_HOSTS
This setting is required to protect your site from certain CSRF attacks. If you use wildcards, you must perform your own validation on the HostHTTP header, otherwise make sure you are not vulnerable to such attacks.
You should also configure the Web server in front of Django to authenticate the host. I nstead of forwarding requests to Django, it should respond to or ignore requests to incorrect hosts with static error pages. T his way, you'll avoid false errors in django logs (or e-mail messages if you configure error reports in this way). For example, on nginx, you can set the default server to return "444 No Response" on an unrecognized host:
server { listen 80 default_server; return 444; }
If you use caching, connection parameters may vary in development and production. Django defaults to local memory caching for each process, which may not be desirable.
Cache servers typically have weak authentication. Make sure that they only accept connections from your application server.
Database connection parameters may vary in development and production.
Database passwords are very sensitive. You should do the same as you SECRET_KEY.
For maximum security, make sure that the database server accepts only connections from the application server.
If you haven't set up a backup for your database, do it now!
If your site sends e-mail, you'll need to set these values correctly.
By default, Django sends e-mail messages from webmaster s localhost and root s localhost. H owever, some mail providers reject e-mail messages from these addresses. To use a different sender address, modify the DEFAULT_FROM_EMAIL and SERVER_EMAIL settings.
Static files are automatically provided by the development server. In production, you must define a STATIC_ROOT that you copy to the collectstatic.
For more information, see Managing static files (for example, images, JavaScript, CSS).
Media files are uploaded by your users. T hey don't trust it! M ake sure that your Web server never tries to interpret them. For example, if a user uploads .php file, the Web server should not execute the file.
Now is a good time to review the backup strategy for these files.
Any website that allows users to log on should implement site-wide HTTPS to avoid clear text transmission of access tokens. I n Django, access tokens include logins/passwords, session cookies, and password reset tokens. ( If you want to send password reset tokens by e-mail, you can't do much to protect them.) )
Protecting sensitive areas, such as user accounts or administrators, is not enough because HTTP and HTTPS use the same session cookies. Your network server must redirect all HTTP traffic to HTTPS and can only transfer HTTPS requests to Django.
After you set up HTTPS, enable the following settings.
Set true to avoid accidental transmission of CSRF cookies on HTTP.
Set true to avoid accidentally transmitting session cookies on HTTP.
Settings disable only a few features that are useful in development. I n addition, you can adjust the following settings. DEBUG = False
Consider using cached sessions to improve performance.
If you use a database-supported session, periodically clear the old session to avoid storing unnecessary data.
Enabling persistent database connections can greatly speed up if you connect to a database account for a significant portion of the request processing time.
This is of great help to virtual hosts with limited network performance.
Cache-enabled template loaders typically improve performance because they avoid compiling each template every time it needs to be rendered. For more information, see the Template Loader documentation.
When you push your code into production, it is expected to be robust, but unexpected errors cannot be ruled out. Thankfully, Django can catch errors and notify you accordingly.
Before putting the site into production, review the logging configuration and check that it works as expected as soon as you receive some traffic.
For more information about logging, see logging.
ADMINS will notify 500 errors by e-mail.
MANAGERS will receive a notification of 404 errors. IGNORABLE_404_URLS can help filter out false reports.
For more information about reporting errors by e-mail, see Error Reporting.
Errors reported via e-mail do not scale well
Consider using an error monitoring system such as Sentry before your inbox is flooded with reports. Sentinel can also summarize logs.
Django contains some default views and templates for HTTP error codes. Y ou may want to override the default template by creating the following templates in the root template directory: 404.html,500.html,403.html, and 400 .html. The default error view using these templates is sufficient to meet the requirements of 99% of Web applications, but you can also customize it.
For more information:
https://docs.djangoproject.com/en/3.0/