模仿python中的卷曲

时间:2014-07-29 20:11:11

标签: python curl python-requests urllib

以下卷曲代码有效:

curl --form addressFile=@t.csv --form benchmark=Public_AR_Census2010 http://geocoding.geo.census.gov/geocoder/locations/addressbatch

t.csv就是

1, 800 Wilshire Blvd, Los Angeles, CA, 90017

我如何在python中模仿这个。到目前为止,我所有的尝试都导致了“糟糕的请求”。我也试图将所有内容保存在内存中 - 不写入文件。

一次尝试:

import requests
url = "http://geocoding.geo.census.gov/geocoder/json/addressbatch"

# data is csv like string with , and \n
ddata = urllib.urlencode({'addressFile' : data, 'benchmark' : 'Public_AR_Current'})
r = requests.get(url + "?" + ddata) # Forcibly closed by remote

requests.put("http://geocoding.geo.census.gov/geocoder/json/addressbatch", ddata)

1 个答案:

答案 0 :(得分:2)

一种选择是使用requests

import requests

url = "http://geocoding.geo.census.gov/geocoder/locations/addressbatch"
data = {'benchmark': 'Public_AR_Census2010'}
files = {'addressFile': open('t.csv')}

response = requests.post(url, data=data, files=files)
print response.content

打印:

"1"," 800 Wilshire Blvd,  Los Angeles,  CA,  90017","Match","Exact","800 Wilshire Blvd, LOS ANGELES, CA, 90017","-118.25818,34.049366","141617176","L"

如果您需要处理内存中的csv数据,请初始化StringIO缓冲区:

from StringIO import StringIO
import requests

csv_data = "1, 800 Wilshire Blvd, Los Angeles, CA, 90017"
buffer = StringIO()
buffer.write(csv_data)
buffer.seek(0)

url = "http://geocoding.geo.census.gov/geocoder/locations/addressbatch"
data = {'benchmark': 'Public_AR_Census2010'}
files = {'addressFile': buffer}

response = requests.post(url, data=data, files=files)
print response.content

使用真实文件打印相同的结果。