我正在编写一个小型的python2.x应用程序,它从url中获取图像,将它们转换为base64,然后使用请求作为POST请求的参数提交给API服务器。我公认的业余代码如下:
import csv
import json
import requests
import base64
import getpass
f = raw_input("Enter CSV filename: ")
global clientCode
clientCode = raw_input("Enter customer code: ")
username = raw_input("Enter username: ")
password = getpass.getpass("Enter password: ")
global url
url = "https://" + clientCode + ".redacted.com/api"
def getSessionKey():
querystring = {"request":"verifyUser","username":username,"password":password,"clientCode":clientCode}
response = requests.request("GET", url, params=querystring, timeout=10)
jr = json.loads(response.text)
# print(response.text)
global sessionKey
sessionKey = jr['records'][0]['sessionKey']
errorCode = jr['status']['errorCode']
with open(f, 'rb') as myfile:
reader = csv.reader(myfile)
rownum = 0
getSessionKey()
for row in reader:
productID = row[0]
imageURL = row[1]
dlimage = requests.get(imageURL, stream=True, timeout=10)
encodedImage = base64.encodestring(dlimage.content)
imagequery = {'clientCode':clientCode,'sessionKey':sessionKey,'request':'saveProductPicture','productID':productID,'picture':encodedImage}
response = requests.post(url, data=imagequery, timeout=10)
print response.status_code
ir = json.loads(response.text)
errorCode = ir['status']['errorCode']
print errorCode
rownum = rownum + 1
现在,如果我将响应行更改为response = requests.get(url, params=imagequery, timeout=10)
,它就可以工作了。但由于这是一个GET请求,服务器会对任何大于1kb的图像抛出HTTP414错误。如果我像上面那样运行代码,API服务器会给出一个错误,表明它没有看到clientCode参数,因此它没有看到任何数据。我做错什么了?你知道吗
谢谢你在实践中帮助我学习。你知道吗
我仍然不知道为什么请求的行为是这样的,但是我重新编写了代码,改用httplib,它就可以工作了。你知道吗
相关问题 更多 >
编程相关推荐