无法使用PYODBC和FLASK Python获取更新的数据库数据

时间:2017-04-06 14:15:17

标签: python flask pyodbc

我似乎遇到了从Python中的Flask连接查询PYODBC连接的问题。最初我使用相同的连接使整个文件,但注意到当你点击Get请求的URL时,它不会返回最新的数据。所以我调整脚本以在每次启动get请求时启动并终止连接,这将返回相同的非更新数据。我注意到它偶尔会更新数据,但大多数情况下都不会。

请帮助更好地澄清这一过程。

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 :(得分:0)

Current变量仅在脚本的初始启动时创建。因此,一旦加载它永远不会更新到当前时间。

现在每个请求都创建了变量,并且正如我预期的那样工作。