简体   繁体   English

为 Azure Function 导入 Python 模块

[英]Importing Python modules for Azure Function

How can I import modules for a Python Azure Function?如何为 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:\home\site\wwwroot\detect_measure\run.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与完整记录的答案Python 库有关的问题 Web 作业

You need to include a requirements.txt file with your code which lists all the python dependencies of your function 您需要在代码中包含一个requirements.txt文件,其中列出了函数的所有python依赖项

From the docs: https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-python#python-version-and-package-management 从文档中: https : //docs.microsoft.com/zh-cn/azure/azure-functions/functions-reference-python#python-version-and-package-management

For example, your reqirements.txt file would contain: 例如,您的reqirements.txt文件将包含:

requests==2.19.1

Python support is currently experimental for Azure Functions, so documentation isn't very good. 目前对Azure函数的Python支持处于试验阶段,因此文档不是很好。

You need to bring your own modules. 您需要自带模块。 None are available by default on Azure Functions. 默认情况下,Azure Functions中没有可用的功能。 You can do this by uploading it via the portal UX or kudu (which is handy for lots of files). 您可以通过门户UX或kudu(对于很多文件而言非常方便)上载它来完成此操作。

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 您可以在“真正的” Python支持的跟踪问题上留下您想要的软件包,如何管理软件包的评论-https: //github.com/Azure/azure-webjobs-sdk-script /问题/ 335

Install python packages from the python code itself with the following snippet:使用以下代码段从 python 代码本身安装 python 包:

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.首次触发 azure function 时,将安装列表中提到的所需库。 for the subsequent triggers, you can comment/ remove the installation code.对于后续触发器,您可以注释/删除安装代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM