Importing Python modules for Azure Function

Question:

How can I import modules for a Python Azure Function?

import requests

Leads to:

2016-08-16T01:02:02.317 Exception while executing function: Functions.detect_measure. Microsoft.Azure.WebJobs.Script: Traceback (most recent call last):
  File "D:homesitewwwrootdetect_measurerun.py", line 1, in <module>
    import requests
ImportError: No module named requests

Related, where are the modules available documented?

Related question with fully documented answer
Python libraries on Web Job

Asked By: Ryan Galgon

||

Answers:

Python support is currently experimental for Azure Functions, so documentation isn’t very good.

You need to bring your own modules. None are available by default on Azure Functions. You can do this by uploading it via the portal UX or kudu (which is handy for lots of files).

You can leave comments on which packages you’d like, how you’d like to manage you packages here on the tracking issue for “real” Python support – https://github.com/Azure/azure-webjobs-sdk-script/issues/335

Answered By: Chris Anderson

You need to include a requirements.txt file with your code which lists all the python dependencies of your function

From the docs:
https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-python#python-version-and-package-management

For example, your reqirements.txt file would contain:

requests==2.19.1
Answered By: Zain Rizvi

Install python packages from the python code itself with the following snippet:

def install(package):
    # This function will install a package if it is not present
    from importlib import import_module
    try:
        import_module(package)
    except:
        from sys import executable as se
        from subprocess import check_call
        check_call([se,'-m','pip','-q','install',package])


for package in ['requests','hashlib']:
    install(package)

Desired libraries mentioned the list gets installed when the azure function is triggered for the first time. for the subsequent triggers, you can comment/ remove the installation code.

Answered By: Sairam Parshi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.