我正在使用 Python/Flask 为大学作业编写一个网络应用程序,为了保持我的 app.py 文件整洁,我有一个函数来查询存储在另一个文件中的数据库。此函数使用 pymysql 和 json 模块,我无法以使其工作的方式加载这些模块 - 我不断收到一个属性错误,说 pymysql 未定义。我已经尝试将导入语句放在我的模块文件 (DBjson.py)、我的模块中包含的函数和 app.py 中。这是我的模块代码:def fetchFromDB(host,port,dbname,user,password,query,jsonString=False): import pymysql # these import statements are in the function in this example - one of several places I've tried them! import json conn = pymysql.connect(host, user=user,port=port, passwd=password, db=dbname) cursorObject = conn.cursor(pymysql.cursors.DictCursor) with cursorObject as cursor: cursor.execute(query) result = cursor.fetchall() conn.close() if jsonString == True: try: for i in range(len(result)): result[i]['dateTime'] = result[i]['dateTime'].strftime('%Y-%m-%d %H:%M') except: pass result = json.dumps(result) return result以及来自我的 app.py 的路线:import pymysqlimport json@app.route('/')def index(): wds = DBjson.fetchFromDB(host,port,dbname,user,password,weatherQuery) bds = DBjson.fetchFromDB(host,port,dbname,user,password,bikesQuery) return render_template('weatherDateTime.html', wds=wds, bds=bds)关于如何进行这项工作的任何帮助?谢谢!编辑 - 我编写了一个测试脚本,我可以从中加载我的模块并运行我的函数没问题 - 我在 DBjson.py 模块文件的开头和函数之外有我的导入语句。这是我不知道的 Flask/范围界定的一些怪癖吗?PS - 感谢您到目前为止的所有回复import DBjsonquery = "SELECT * FROM dublinBikesInfo WHERE dateTime LIKE (SELECT MAX(datetime) FROM dublinBikesInfo);"#login details for AWS RDS DBhost="xyza"port=3306dbname="xyza"user="xyza"password="xyza"a = DBjson.fetchFromDB(host,port,dbname,user,password,query)print(a)
2 回答

摇曳的蔷薇
TA贡献1793条经验 获得超6个赞
在您的代码中有一个缩进错误,所有语句都必须在您创建的函数/方法内。
`def method():
#code here`
并且在页面开头定义函数/方法之前尝试导入库也不错!!
在您的场景中,请将所有与函数/方法相关的语句放在函数/方法中!!

慕尼黑8549860
TA贡献1818条经验 获得超11个赞
Python 对缩进非常无情。您的模块代码缩进不正确。
这样做的正确方法是:
def Function(): #your code indented in here
添加回答
举报
0/150
提交
取消