我正在尝试在 Azure 自动化计数中运行 Python 脚本。
目标是连接到公共 API、检查货币并写回 MySQL 数据库。 MySQL 数据库位于 Azure 中。
这是我的代码:
#!/usr/bin/env python3
import requests
import mysql.connector
import os
#from dotenv import load_dotenv
from mysql.connector import Error
#load_dotenv()
needToGet = ["AED", "AUD", "CAD", "CHF", "EUR", "GBP", "HKD", "ILS", "INR", "JPY", "KWD", "MXN", "NZD", "RUB", "SEK", "TRY", "ZAR", "DKK", "NOK", "GBX"]
currency = ','.join(needToGet)
url = 'https://openexchangerates.org/api/latest.json'
path = '?app_id=2dbfde0172a54732a87ff34cbb21c8ba&symbols=' + currency
data = requests.get(url + path).json()
forInsert = []
for cur in needToGet:
if cur in data['rates']:
forInsert.append(data['rates'][cur])
else:
forInsert.append('null')
stringForInsert = ','.join(map(str, forInsert))
try:
connection = mysql.connector.connect("*******.mysql.database.azure.com",
"exchange",
"exchange@*****",
"******")
mySql_insert_query = """INSERT INTO currency (""" + currency + """)
VALUES
(""" + stringForInsert + """) """
cursor = connection.cursor()
cursor.execute(mySql_insert_query)
connection.commit()
print(cursor.rowcount, "Record inserted successfully into exchange table")
cursor.close()
except mysql.connector.Error as error:
print("Failed to insert record into exchange table {}".format(error))
finally:
if connection.is_connected():
connection.close()
print("MySQL connection is closed")
但我收到以下错误:
Traceback (most recent call last):
File "C:\Temp\w4ezxc4a.mkf\3525cb9a-e211-4b86-91b4-2a7d740ce109", line 29, in <module>
connection = mysql.connector.connect("****.mysql.database.azure.com",
File "C:\WPy64-3800\python-3.8.0.amd64\lib\site-packages\mysql\connector\__init__.py", line 273, in connect
return MySQLConnection(*args, **kwargs)
File "C:\WPy64-3800\python-3.8.0.amd64\lib\site-packages\mysql\connector\connection.py", line 73, in __init__
super(MySQLConnection, self).__init__(*args, **kwargs)
TypeError: __init__() takes 1 positional argument but 5 were given
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Temp\w4ezxc4a.mkf\3525cb9a-e211-4b86-91b4-2a7d740ce109", line 48, in <module>
if connection.is_connected():NameError: name 'connection' is not defined
如果我在本地运行脚本,它可以正常工作。
回答1
正如@BoarGules 关于错误 NameError: name 'connection' is not defined
所建议的那样。感谢您发布您的建议作为帮助其他社区成员的答案,以便遇到类似问题的其他人可以解决他们的问题。
解决上述问题的解决方法:-
由于
TypeError: __init()__ takes 1 positional argument but 5 were given
,您对mysql.connector.connect()
的调用失败。虽然try
提供了失败connection
的规范,并且except
和finally
都在编码时假设它总是会成功,因为它们都引用了那个connection
。
有关更多信息,请参阅此 SO THREAD|https://stackoverflow.com/questions/71040417/how-can-we-run-a-standard-python-script-in-azure-and-save-files-to-a-data-lake 中运行标准 Python 脚本。