使用Python请求库500错误获取Ajax Json输出

时间:2015-02-26 12:28:59

标签: python ajax json

我已完成此代码以从http://www.yurticikargo.com/bilgi-servisleri/Sayfalar/en-yakin-sube.aspx的网页获取输出 但我收到500错误。无法理解为什么

import requests
import json


class Yurtici(object):
    baseUrl = 'http://www.yurticikargo.com/'
    ajaxRoot1 = '_layouts/ArikanliHolding.YurticiKargo.WebSite/ajaxproxy-sswservices.aspx/'
    ajaxRoot2 = '_layouts/ArikanliHolding.YurticiKargo.WebSite/ajaxproxy-unitservices.aspx/GetUnit'

    getTown = 'GetTownByCity'

    urlGetTown = baseUrl + ajaxRoot1 + getTown
    urlGetUnit = baseUrl + ajaxRoot2  
    headers = {'content-type': 'application/json','encoding':'utf-8'}

    def __init__(self):
        pass

    def ilceler(self, plaka=34): # Default testing value
        payload = {'cityId':plaka}
        url = self.urlGetTown
        r = requests.post(url, data=json.dumps(payload), headers=self.headers)
        return r.json() # OK


    def subeler(self, ilceNo=3401): # Default testing value
        # 5902 Çerkezköy 
        payload=  {'cityID':34,'townID':ilceNo,'unitOnDutyFlag':'null','closestFlag':0}
        url = self.urlGetUnit
        headers = {'content-type': 'application/json','encoding':'utf-8'}
        r = requests.post(url, data=json.dumps(payload), headers=headers)
        return r.json()
        print  r.status_code, r.raw.read()

if __name__ == '__main__':        
    a = Yurtici()
   #print a.ilceler(34) # OK
    print a.subeler()   # NOT OK !!!

1 个答案:

答案 0 :(得分:1)

只是预感,我发现'unitOnDutyFlag'值存在问题。将python dict编码为json时,如果输出中需要null,则dict中的值应为None

尝试更改行:

payload = {'cityID':34,'townID':ilceNo,'unitOnDutyFlag':'null','closestFlag':0}

为:

payload = {'cityID':34,'townID':ilceNo,'unitOnDutyFlag': None,'closestFlag':0}

实施例

# nulljson.py
import json

data = {
    'foo': 'null',
    'bar': None
}

print json.dumps(data)

输出:

$ python nulljson.py
{"foo": "null", "bar": null}

请注意,"foo"的值是字符串 "null",而不是真正的null值。