Using Python in Azure Functions
Although Python is a supported language in Azure Functions now, it isn’t what I’d call a first-class citizen. Below are some common pitfalls and workarounds to get an Azure Function written in Python to work.
Changing versions
Most likely you’ll want to use the latest version of Python, to do this:
- Check the current version that is installed. Inside the Kudu command prompt:
python -c "import sys; print(sys.version)"
- If you need to upgrade go to ‘Site Extensions’ in Kudu > Gallery > Search for Python > Install it and copy the path it installs to (see below):
- Go back to the function app in the Azure portal and go to Application Settings > Scroll down to the ‘Handler mappings’ section > Click ‘Add new handler mapping’ > Enter the following:
- Rerun the version check to make sure it has worked.
Installing packages
I’d highly recommend creating a virtual environment to install packages. This keeps everything separate and nicely isolated. To do this:
- In Kudu change the current directory to your function app directory. This is usually
d:/home/site/wwwroot/<function app name>
- Install the virtualenv package
python -m pip install virtualenv
- Create a new virtual environment:
python -m virtualenv <env name>
- Change into the
<env name>/Scripts
directory and runactivate.bat
to activate the virtual environment (the command line will be prefixed with the environment name so you know this has worked). - Update pip if required:
python -m pip install -U pip
- Install your packages!
Update your code to use the virtual environment
The final step is pointing your code at the virtual environment so the packages can be found. Add the following code to the beginning of your script/s (replacing myenv
with the name of your virtual environment):
import sys
import os.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname( __file__ ), 'myenv/Lib/site-packages')))
Now you should be good to go! Any problems or if you know of a better way just let me know.