我正在编写一个小型Python 2.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的图像抛出HTTP 414错误。如果我运行上面的代码,API服务器会给出一个错误,表明它没有看到clientCode参数,因此它可以理解它没有看到任何数据。我做错了什么?
感谢您帮我练习。
答案 0 :(得分:0)
我仍然不确定为什么请求的行为方式如此,但我重新编写代码以使用httplib,它可以工作。