得到工作,波斯特不

2024-09-19 20:40:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个小型的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参数,因此它没有看到任何数据。我做错什么了?你知道吗

谢谢你在实践中帮助我学习。你知道吗


Tags: import服务器jsonurlresponsetimeoutusernamepassword