简体   繁体   中英

Numpy module not found when working with Azure Functions in VS Code and virtualenv

I'm new to working with azure functions and tried to work out a small example locally, using VS Code with the Azure Functions extension.

Example:

# First party libraries
import logging

# Third party libraries
import numpy as np
from azure.functions import HttpResponse, HttpRequest


def main(req: HttpRequest) -> HttpResponse:
    seed = req.params.get('seed')

    if not seed:
        try:
            body = req.get_json()
        except ValueError:
            pass
        else:
            seed = body.get('seed')

    if seed:
        np.random.seed(seed=int(seed))
        r_int = np.random.randint(0, 100)
        logging.info(r_int)
        return HttpResponse(
            "Random Number: " f"{str(r_int)}", status_code=200
            )
    else:
        return HttpResponse(
            "Insert seed to generate a number",
            status_code=200
            )

When numpy is installed globally this code works fine. If I install it only in the virtual environment, however, I get the following error:

*Worker failed to function id 1739ddcd-d6ad-421d-9470-327681ca1e69.
[15-Jul-20 1:31:39 PM] Result: Failure
Exception: ModuleNotFoundError: No module named 'numpy'. Troubleshooting Guide: https://aka.ms/functions-modulenotfound*

I checked multiple times that numpy is installed in the virtual environment, and the environment is also specified in the.vscode/settings.json file.

pip freeze of the virtualenv "worker_venv":

$ pip freeze
azure-functions==1.3.0
flake8==3.8.3
importlib-metadata==1.7.0
mccabe==0.6.1
numpy==1.19.0
pycodestyle==2.6.0
pyflakes==2.2.0
zipp==3.1.0

.vscode/settings.json file:

{
  "azureFunctions.deploySubpath": ".",
  "azureFunctions.scmDoBuildDuringDeployment": true,
  "azureFunctions.pythonVenv": "worker_venv",
  "azureFunctions.projectLanguage": "Python",
  "azureFunctions.projectRuntime": "~2",
  "debug.internalConsoleOptions": "neverOpen"
}

I tried to find something in the documentation, but found nothing specific regarding the virtual environment. I don't know if I'm missing something?

EDIT: I'm on a Windows 10 machine btw

EDIT: I included the folder structure of my project in the image below

在此处输入图像描述

EDIT: Added the content of the virtual environment Lib folder in the image below

在此处输入图像描述

EDIT: Added a screenshot of the terminal using the pip install numpy command below

在此处输入图像描述

EDIT: Created a new project with a new virtual env and reinstalled numpy, screenshot below, problem still persists.

在此处输入图像描述

EDIT: Added the launch.json code below

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Attach to Python Functions",
      "type": "python",
      "request": "attach",
      "port": 9091,
      "preLaunchTask": "func: host start"
    }
  ]
}

SOLVED

So the problem was neither with python, nor with VS Code. The problem was that the execution policy on my machine (new laptop) was set to restricted and therefore the .venv\Scripts\Activate.ps1 script could not be run.

To resolve this problem, just open powershell with admin rights and and run set-executionpolicy remotesigned . Restart VS Code and all should work fine

I didn't saw the error, due to the many logging in the terminal that happens when you start azure. I'll mark the answer of @HuryShen as correct, because the comments got me to the solution. Thank all of you guys

For this problem, I'm not clear if you met the error when run it locally or on azure cloud. So provide both suggestions for these two situation.

1. If the error shows when you run the function on azure, you may not have installed the modules success. When deploy the function from local to azure, you need to add the module to requirements.txt (as Anatoli mentioned in comment). You can generate the requirements.txt automatically by the command below:

pip freeze > requirements.txt

After that, we can find the numpy==1.19.0 exist in requirements.txt . 在此处输入图像描述

Now, deploy the function from local to azure by the command below, it will install the modules success on azure and work fine on azure.

func azure functionapp publish <your function app name> --build remote

2. If the error shows when you run the function locally. Since you provided the modules installed in worker_venv , it seems you have installed numpy module success. I also test it in my side locally, install numpy and it works fine. So I think you can check if your virtual environment( worker_venv ) exist in the correct location. Below is my function structure in local VS code, please check if your virtual environment locates in the same location with mine.

在此处输入图像描述

----- Update ------

Run the command to to set execution policy and then activate the virtual environment:

set-executionpolicy remotesigned
.venv\Scripts\Activate.ps1

I could solve my issue uninstalling python3 (see here for a guide https://stackoverflow.com/a/60318668/11986067 ).

After starting the app functions via F5 or func start , the following output was shown:

在此处输入图像描述

This version was incorrect. I have chosen python 3.7.0 when creating the project in the Azure extension. After deleting this python3 version, the correct version was shown and the Import issue was solved:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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