我有一个SQL表,我正在循环以向服务器发送每个记录的单个发布请求。所有记录都应该是单独的JSON。
我期待这样的事情:
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返回,该JSON会对发送给它的服务器进行ping操作?
代码:
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"}]}}}
答案 0 :(得分:0)
如果您将cursor.fetchmany()
更改为cursor.fetchall()
,是否有效?如果你将objects_list.append(d)
放在for循环中并设置
output = {"MetaData": {}, "SRData": objects_list}