Azure Python应用程序功能不再在本地运行-模块'azure.functions_worker'没有属性'start_async' [英] Azure Python App Function no longer runs locally - module 'azure.functions_worker' has no attribute 'start_async'

查看:61
本文介绍了Azure Python应用程序功能不再在本地运行-模块'azure.functions_worker'没有属性'start_async'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Python中构建了一个Azure App函数,该函数在虚拟环境中可以在本地良好运行,并且在发布到Azure时也可以正常运行.我现在回到它来做一些进一步的工作,当尝试在本地运行时,出现以下错误.网上没有什么可以帮助我了解为什么会发生此错误的信息?我尚未更改本地代码.

I have built an Azure App function in Python which was running fine locally within the virtual environment, and also worked fine when published to Azure. I have come back to it now to do some further work, and when trying to run locally I get the below errors. There isn't much if anything available online that helps me understand why this error is occurring? I Have not changed the local code yet.

Python版本

PS C:\temp\python_function> python --version
Python 3.7.1

运行命令

PS C:\temp\python_function> func host start

结果

[16/04/2019 1:11:51 AM] Starting language worker process:python  "C:\Users\jmatson\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\workers\python\worker.py" --host 127.0.0.1 --port 60810 --workerId 0d7f3e36-a0a2-4478-aa49-c46e2c48cb77 --requestId 0e417fc7-eccb-4fcb-b889-b197ecfad53d --grpcMaxMessageLength 134217728
[16/04/2019 1:11:51 AM] python process with Id=15040 started
[16/04/2019 1:11:51 AM] Adding dependency download request to python language worker
[16/04/2019 1:11:52 AM] Traceback (most recent call last):
[16/04/2019 1:11:52 AM]   File "C:\Users\jmatson\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\workers\python\worker.py", line 37, in main
[16/04/2019 1:11:52 AM]     return aio_compat.run(azure.functions_worker.start_async(
[16/04/2019 1:11:52 AM] AttributeError: module 'azure.functions_worker' has no attribute 'start_async'
[16/04/2019 1:11:52 AM] Traceback (most recent call last):
[16/04/2019 1:11:52 AM]   File "C:\Users\jmatson\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\workers\python\worker.py", line 46, in <module>
[16/04/2019 1:11:52 AM]     main()
[16/04/2019 1:11:52 AM]   File "C:\Users\jmatson\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\workers\python\worker.py", line 37, in main
[16/04/2019 1:11:52 AM]     return aio_compat.run(azure.functions_worker.start_async(
[16/04/2019 1:11:52 AM] AttributeError: module 'azure.functions_worker' has no attribute 'start_async'
[16/04/2019 1:11:52 AM] Language Worker Process exited.
[16/04/2019 1:11:52 AM] python exited with code 1
 AttributeError: module 'azure.functions_worker' has no attribute 'start_async'.

下面添加了代码:

import logging
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import boto3
import uuid
import io
import os
import json
import requests
import matplotlib.dates as mdates
import azure.functions as func
from scipy.ndimage.filters import gaussian_filter1d
from scipy.interpolate import make_interp_spline, BSpline
from scipy.interpolate import spline
from pandas.plotting import register_matplotlib_converters
from matplotlib.dates import MonthLocator

register_matplotlib_converters()

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    sns.set_style("dark")

    rowcount = req.params.get('rows')
    if not rowcount:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            rowcount = req_body.get('rows')

    if rowcount:
        rowcount = int(rowcount)

        headers = {'Content-Type': 'application/json'}
        api_url = f'https://<removed>.execute-api.ap-southeast-2.amazonaws.com/Prod/tables/<removed>/all?&server=P781S001&ordercol=daily_sales_date&order=DESC&rowlimit={str(rowcount)}'
        response = requests.get(api_url, headers=headers)
        if response.status_code == 200:
            json_data = json.loads(response.content.decode('utf-8'))
        else:
            return func.HttpResponse(
                "Couldn't contact the InSite API. No data returned.",
                status_code=400
            )

        print os.environ['AWS_ACCESS_KEY']
        dates = [i['daily_sales_date'] for i in json_data]
        values = [i['daily_sales'] for i in json_data]

        df = pd.DataFrame({'dates':dates, 'values':values})
        df['dates']  = [pd.to_datetime(i) for i in df['dates']]
        fig, ax = plt.subplots()

        ax.plot(df['dates'].values, df['values'].values)
        ax.set(xlabel='date', ylabel='sales ($)',
            title='Sales from ' + str(min(df['dates'].values)) + ' to ' + str(max(df['dates'].values)))
        ax.xaxis.set_major_locator(MonthLocator())
        ax.grid()

        session = boto3.Session(
            aws_access_key_id='',
            aws_secret_access_key='',
        )
        s3 = session.resource('s3')

        img_data = io.BytesIO()
        plt.savefig(img_data, format='png')
        img_data.seek(0)

        s3.Bucket('api-dev-jupyter-notebook-s3').put_object(Key='graph_sales.png', ContentType='image/png', Body=img_data, ACL='public-read')
        return func.HttpResponse(f"You requested {rowcount} rows. Sample data {dates[0]} {str(values[0])}")
    else:
        return func.HttpResponse(
             "This method requires you to state the amount of rows you want to query. E.g. rows=20.",
             status_code=400
        )

推荐答案

问题已解决.尽管互联网文档普遍可用,但您可以使用以下内容在Windows上启动Python虚拟环境:

Problem solved. While generally available internet documentation states you can use the below to launch your Python virtual environment on Windows:

Launch virtualenv
In your Command Prompt navigate to your project:

cd your_project
Within your project:

virtualenv env
Activate your virtualenv:

on Windows, virtualenv creates a batch file

\env\Scripts\activate.bat
to activate virtualenv on Windows, activate script is in the Scripts folder :

\path\to\env\Scripts\activate

这似乎不起作用,并且(至少)引起了我所观察到的错误.相反,我遵循了Microsoft文章中的明确说明-

This doesn't appear to work and causes (at least) the errors I've observed. Instead, I have followed the explicit instructions within the Microsoft article - https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-first-function-python which does work.

PS C:\temp\python_function> py -3.6 -m venv .env
PS C:\temp\python_function> .env\scripts\activate
(.env) PS C:\temp\python_function> func host start

这篇关于Azure Python应用程序功能不再在本地运行-模块'azure.functions_worker'没有属性'start_async'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆