2017-04-06 54 views
-2

我似乎在從Python中的Flask連接查詢PYODBC連接時遇到問題。最初我使用相同的連接使整個文件,但注意到當你點擊獲取請求的URL時,它不會返回最新的數據。所以我調整了腳本,每次啓動獲取請求時啓動並終止連接,這將返回相同的非更新數據。我注意到偶爾它會更新數據,但大部分時間不會。無法使用PYODBC和FLASK Python獲取更新的DB數據

請幫助更好地澄清此過程。

def getChg(s, cursor, arr): 
getIncResolved = "SELECT COUNT(incident.number) FROM SCHEMA.OAUSER.incident incident WHERE incident.dv_resolved_by = '" + str(s) + "' AND incident.resolved_at BETWEEN '" + str(past) + "' AND '" + str(current) + "' AND incident.dv_opened_by != '" + str(s) + "';" 
getTaskResolved = "SELECT COUNT(sc_task.number) FROM SCHEMA.OAUSER.sc_task sc_task WHERE sc_task.dv_closed_by = '" + str(s) + "' AND sc_task.closed_at BETWEEN '" + str(past) + "' AND '" + str(current) + "' AND sc_task.dv_opened_by != '" + str(s) + "';" 
getCallStarted = "SELECT COUNT(new_call.number) FROM SCHEMA.OAUSER.new_call new_call WHERE new_call.opened_at BETWEEN '" + str(past) + "' AND '" + str(current) + "' AND new_call.dv_opened_by = '" + str(s) + "';" 
i = 0 
t = 0 
c = 0 
cursor.execute(getIncResolved) 
for row in cursor.fetchall(): 
    i = row[0] 

cursor.execute(getTaskResolved) 
for row in cursor.fetchall(): 
    t = row[0] 
cursor.execute(getCallStarted) 
for row in cursor.fetchall(): 
    c = row[0] 
if c > -1: 
    test = {'Agent': str(s), 'Calls': c, 'Inc': i, 'Task': t} 
    arr.append(test) 



@app.route('/data',methods=['GET', 'POST']) 
def api_root(): cnxn=pyodbc.connect('DSN=ServiceNow;Uid=ServiceOps;Pwd=********;',autocommit=True) 
cursor = cnxn.cursor() 
data = [] 
staffjson = request.get_json(force=True) 
staff = staffjson['users'] 
print(staff) 
del data[:] 
for s in staff: 
    getChg(s, cursor, data) 
print(data) 
cnxn.close() 
return json.dumps(data) 
+1

正確縮進代碼。這是不可讀的。 –

+0

**您可以使用SQL注入。**不要使用連接來構建查詢,使用參數化查詢。 – davidism

+0

謝謝你。此ODBC驅動程序只允許SELECT的。將不會寫入數據庫。爲適應更好的習慣,我將調整爲參數化查詢。 –

回答

0

Current變量僅在腳本的初始啓動時創建。因此,一旦它被加載,它就不會更新到當前時間。

現在在每個請求中創建變量,並按我的預期工作。