如何在Python

时间:2015-07-03 06:31:24

标签: python json python-requests

我正在使用请求来调用使用JSON响应的Web服务。问题是这个JSON启用了分页,这基本上意味着我每次调用服务时都可以返回100个记录。当我调用服务器时,我可能会收到100,然后是100,然后是23,然后循环关闭,但是我将存储在我的变量中的唯一记录是最后的23个。下面的JSON中的参数增加以返回a新的记录集是StartRowNum。这从0开始,并根据程序运行的循环次数增加,即如果有200条记录,则检索最后100条的StartRowNum将是101,如果有300条记录则为201,依此类推。 我如何存储第一个和第二个100?

    f2 =open('C:\Users\GeoffreyWest\Desktop\Request.json')
    data2 = jsonpickle.decode((f2.read()))
    data2 = jsonpickle.encode(data2)
    lastpage = 'false'
    startrow = 0
    newquery = 'new'
    pagesize = 100
    url2 = "URL"
    headers2 = {'Content-type': 'text/plain', 'Accept': '/'}

    while lastpage == 'false':
    r2 = requests.post(url2, data=data2, headers=headers2)
    print r2.text
    decoded2 = json.loads(r2.text)
    f2 =open('C:\Users\GeoffreyWest\Desktop\Request.json')
    data2 = jsonpickle.decode((f2.read()))
    if decoded2['Response']['LastPage'] == 'false':
        data2['QueryRequest']['PageSize'] = pagesize
        startrow = startrow + data2['QueryRequest']['PageSize']
        data2['QueryRequest']['StartRowNum'] = startrow
        data2['QueryRequest']['NewQuery'] = 'false'
        data2 = jsonpickle.encode(data2)
        print startrow
    else:
        lastpage = 'true'

发送到服务器的JSON示例:

{
    "MetaData": {},
    "QueryRequest": {
        "LastUpdatedDate": "06/29/2015 23:00:00",
        "srType": [
            "Bulky Items",
            "Electronic Waste",
            "Metal/Household Appliances",
            "Dead Animal Removal",
            "Service Not Complete",
            "Manual Pickup",
            "Brush Items Pickup",
            "Move In/Move Out",
            "Containers",
            "Illegal Dumping Pickup"
        ],
        "NewQuery": "new", 
        "PageSize": "100",
        "StartRowNum": "0"

    }
}

0 个答案:

没有答案