我有一个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"}]}}}