我正在使用 Python/Flask 為大學(xué)作業(yè)編寫一個網(wǎng)絡(luò)應(yīng)用程序,為了保持我的 app.py 文件整潔,我有一個函數(shù)來查詢存儲在另一個文件中的數(shù)據(jù)庫。此函數(shù)使用 pymysql 和 json 模塊,我無法以使其工作的方式加載這些模塊 - 我不斷收到一個屬性錯誤,說 pymysql 未定義。我已經(jīng)嘗試將導(dǎo)入語句放在我的模塊文件 (DBjson.py)、我的模塊中包含的函數(shù)和 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)關(guān)于如何進行這項工作的任何幫助?謝謝!編輯 - 我編寫了一個測試腳本,我可以從中加載我的模塊并運行我的函數(shù)沒問題 - 我在 DBjson.py 模塊文件的開頭和函數(shù)之外有我的導(dǎo)入語句。這是我不知道的 Flask/范圍界定的一些怪癖嗎?PS - 感謝您到目前為止的所有回復(fù)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條經(jīng)驗 獲得超6個贊
在您的代碼中有一個縮進錯誤,所有語句都必須在您創(chuàng)建的函數(shù)/方法內(nèi)。
`def method():
#code here`
并且在頁面開頭定義函數(shù)/方法之前嘗試導(dǎo)入庫也不錯??!
在您的場景中,請將所有與函數(shù)/方法相關(guān)的語句放在函數(shù)/方法中?。?/p>

慕尼黑8549860
TA貢獻1818條經(jīng)驗 獲得超11個贊
Python 對縮進非常無情。您的模塊代碼縮進不正確。
這樣做的正確方法是:
def Function(): #your code indented in here
添加回答
舉報
0/150
提交
取消