|
| 1 | +# Vendoring Packages: FastAPI + Jinja2 Example |
| 2 | + |
| 3 | +*Note: You must have Python Packages enabled on your account for built-in packages to work. Request Access to our Closed Beta using [This Form](https://forms.gle/FcjjhV3YtPyjRPaL8)* |
| 4 | + |
| 5 | +This is an example of a Python Worker that uses a built-in package (FastAPI) with a vendored package (Jinja2). |
| 6 | + |
| 7 | +## Adding Packages |
| 8 | + |
| 9 | +Built-in packages can be selected from [this list](https://developers.cloudflare.com/workers/languages/python/packages/#supported-packages) and added to your `requirements.txt` file. These can be used with no other explicit install step. |
| 10 | + |
| 11 | +Vendored packages are added to your source files and need to be installed in a special manner. The Python Workers team plans to make this process automatic in the future, but for now, manual steps need to be taken. |
| 12 | + |
| 13 | +### Vendoring Packages |
| 14 | + |
| 15 | +[//]: # (NOTE: when updating the instructions below, be sure to also update the vendoring.yml CI workflow) |
| 16 | + |
| 17 | +First, install Python3.12 and pip for Python 3.12. |
| 18 | + |
| 19 | +*Currently, other versions of Python will not work - use 3.12!* |
| 20 | + |
| 21 | +Then create a virtual environment and activate it from your shell: |
| 22 | +```console |
| 23 | +python3.12 -m venv .venv |
| 24 | +source .venv/bin/activate |
| 25 | +``` |
| 26 | + |
| 27 | +Within our virtual environment, install the pyodide CLI: |
| 28 | +```console |
| 29 | +.venv/bin/pip install pyodide-build |
| 30 | +.venv/bin/pyodide venv .venv-pyodide |
| 31 | +``` |
| 32 | + |
| 33 | +Next, add packages to your vendor.txt file. Here we'll add jinja2 |
| 34 | +``` |
| 35 | +jinja2 |
| 36 | +``` |
| 37 | + |
| 38 | +Lastly, add these packages to your source files at `src/vendor`. For any additional packages, re-run this command. |
| 39 | +```console |
| 40 | +.venv-pyodide/bin/pip install -t src/vendor -r vendor.txt |
| 41 | +``` |
| 42 | + |
| 43 | +### Using Vendored packages |
| 44 | + |
| 45 | +In your wrangler.toml, make the vendor directory available: |
| 46 | + |
| 47 | +```toml |
| 48 | +[[rules]] |
| 49 | +globs = ["vendor/**"] |
| 50 | +type = "Data" |
| 51 | +fallthrough = true |
| 52 | +``` |
| 53 | + |
| 54 | +Now, you can import and use the packages: |
| 55 | + |
| 56 | +```python |
| 57 | +import jinja2 |
| 58 | +# ... etc ... |
| 59 | +``` |
| 60 | + |
| 61 | +### Developing and Deploying |
| 62 | + |
| 63 | +To develop your Worker, run `npx wrangler@latest dev`. |
| 64 | + |
| 65 | +To deploy your Worker, run `npx wrangler@latest deploy`. |
0 commit comments