0
我有一個SQL表,我循環發送單個發佈請求到每個記錄的服務器。所有記錄應該是單獨的JSON。如何通過記錄循環發送單個POST請求到服務器?
我期待這樣的事情:
while there are rows in table:
write the number of rows as json and output files.
while there are rows being written as jsons and output files:
server is pinged for the number of jsons and output files.
如果objects_list.append(d)
處於環路和fetchmany
變化fetchall
返回所有記錄,作爲一個JSON對象,我想通過該表進行迭代,並有各記錄在下面的結構中作爲單個json發送到服務器。因此,當所有記錄被寫爲json對象並通過請求發送到服務器時,迭代整個表並打破循環。
樣品JSON { "MetaData": {}, "SRData": { "SRNumber": "1-3580671" } }
我使用Pyodbc遍歷我的表,拉我想發送到服務器的記錄。
我的腳本返回第一條記錄,我想循環遍歷該表,並在where子句中定義的特定時間範圍內返回X條記錄。
如何成功將每行作爲單個JSON返回並將其發送到服務器?
代碼:
import pyodbc
import json
import collections
import requests
import time
import logging
import httplib
import datetime
import logging
import logging.handlers
start = time.time()
connstr = 'DRIVER={SQL Server};SERVER=server;DATABASE=ServiceRequest; UID=SA;PWD=pwd'
conn = pyodbc.connect(connstr)
cursor = conn.cursor()
cursor.execute("""SELECT SRNUMBER FROM MYLA311 """)
rows = cursor.fetchmany()
objects_list = []
for row in rows:
d = collections.OrderedDict()
d['SRNumber']= row.SRNUMBER
objects_list.append(d)
output = {"MetaData": {},
"SRData": d}
print output
j = json.dumps(output)
b = json.dumps(output, sort_keys=True, indent=4)
objects_file = 'C:\Users\Administrator\Desktop\JSONOutput.txt'
f = open(objects_file,'w')
url = "https://myla311.lacity.org/myla311router/mylasrbe/1/UpsertSANSR"
headers = {'Content-type': 'text/plain', 'Accept': '/'}
r = requests.post(url, data= json.dumps(output), headers=headers, verify=False)
print 'It took', time.time()-start, 'seconds.'
print r.text
conn.close()
輸出:
{
"MetaData": {},
"SRData": {
"SRNumber": "1-3140751"
}
}
{"status":{"code":311,"message":"Service Request Successfully updated","cause":""},"Response":{"PrimaryRowId":"1-1VBF3","ListOfServiceRequest":{"ServiceRequest":[{"SRNumber":"1-3140751"}]}}}
沒了,同樣的輸出,我認爲這是比這更復雜一點,好像我需要爲我的輸出,在遍歷各行的while循環表作爲新的JSON對象並寫入新的對象文件。 – geoffreyGIS
如果將objects_list.append(d)放入for循環中,該怎麼辦? – maxymoo
不,我認爲你想從表中返回所有記錄作爲單個JSON,我想從表中返回所有記錄作爲單個JSON。 – geoffreyGIS