Python
Last updated
Was this helpful?
Last updated
Was this helpful?
Taken and summarised from https://snyk.io/blog/python-security-best-practices-cheat-sheet/
is “a library for validating Python data structures, such as those obtained from config-files, forms, external services or command-line parsing, converted from JSON/YAML (or something else) to Python data-types.
is “an allowed-list-based HTML sanitizing library that escapes or strips markup and attributes.”
Major frameworks come with their own sanitation functions, like ’s flask.escape()
or ’s django.utils.html.escape()
. The goal of any of these functions is to secure potentially malicious HTML input like:
A typical example is an . Instead of stitching strings and variables together to generate an SQL query, it is advisable to use named-parameters to tell the database what to treat as a command and what as data.
Or even better, use Object-Relational Mapping (ORM), such as , which would make the example query look like this:
Here you get more readable code, as well as ORM optimizations like caching, plus more security and performance!
This means that instead of using a global Python version and global Python dependencies for all your projects, you can have project-specific virtual environments that can use their own Python (and Python dependency) versions!
As of Python version 3.5, the use of venv
is recommended and with version 3.6 pyvenv
was deprecated.
By default, most frameworks have debugging switched on. For example, Django has it enabled in settings.py. Make sure to switch debugging to False
in production to prevent leaking sensitive application information to attackers.
Python has a built-in module named string
. This module includes the Template
class, which is used to create template strings.
Consider the following example.
For the above code, the variable greeting is evaluated as: “Hello World, my name is Hayley.”
This string format is a bit cumbersome because it requires an import statement and is less flexible with types. It also doesn’t evaluate Python statements the way f-strings do. These constraints make template strings an excellent choice when dealing with user input.