Я создал функцию приложения Azure в Python, которая прекрасно работала локально в виртуальной среде, а также хорошо работала при публикации в 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
)