我已经在Python中构建了一个Azure App函数,该函数在虚拟环境中本地运行良好,并且发布到Azure时也运行良好。我现在回到它做一些进一步的工作,当尝试在本地运行时,出现以下错误。网上没有什么可以帮助我了解为什么会发生此错误的信息?我尚未更改本地代码。
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
)
答案 0 :(得分:1)
“卸载Azure CLI核心工具并使用选择安装 https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local#v2 它工作正常!希望有帮助。”
参考:https://github.com/MicrosoftDocs/azure-docs/issues/24489#issuecomment-463158145
答案 1 :(得分:0)
问题解决了。尽管通常提供的互联网文档说明您可以使用以下内容在Windows上启动Python虚拟环境:
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文章https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-first-function-python中的明确说明。
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