# Python

> <mark style="color:orange;">Taken and summarised from <https://snyk.io/blog/python-security-best-practices-cheat-sheet/></mark>

### Input Sanitisation

* [schema](https://pypi.org/project/schema/) 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.
* [bleach](https://pypi.org/project/bleach/) is “an allowed-list-based HTML sanitizing library that escapes or strips markup and attributes.”&#x20;

Major frameworks come with their own sanitation functions, like [Flask](https://flask.palletsprojects.com/en/2.0.x/api/?highlight=escape#flask.escape)’s `flask.escape()` or [Django](https://docs.djangoproject.com/en/2.0/_modules/django/utils/html/)’s `django.utils.html.escape()`. The goal of any of these functions is to secure potentially malicious HTML input like:

```
>>> import bleach
>>> bleach.clean('an XSS <script>navigate(...)</script> example')
'an XSS &lt;script&gt;navigate(...)&lt;/script&gt; example'
```

### SQL Injection&#x20;

A typical example is an [SQL injection](https://snyk.io/learn/sql-injection/). 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.&#x20;

```
# Instead of this …
cursor.execute(f"SELECT admin FROM users WHERE username = '{username}'");
# ...do this...
cursor.execute("SELECT admin FROM users WHERE username = %(username)s", {'username': username}); 
```

Or even better, use Object-Relational Mapping (ORM), such as [sqlalchemy](https://www.sqlalchemy.org/), which would make the example query look like this:

```
query = session.query(User).filter(User.name.like('%{username}'))
```

Here you get more readable code, as well as ORM optimizations like caching, plus more security and performance!

### Usage of Virtual Envrionments

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.

### Disable Debugging Mode

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.

### String Formatting

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.

```
from string import Template
greeting_template = Template(“Hello World, my name is $name.”)
greeting = greeting_template.substitute(name=”Hayley”)
```

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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wiki.smhuda.com/pentesting/secure-code-review/python.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
