python请求不将我的POST数据发送为content-type:multipart / form-data auto

时间:2019-03-22 18:18:59

标签: python python-requests

我已经编写了一个脚本,该脚本将在文件夹中搜索所有图像并从excel文件中获取所有信息,并将该数据发布到API

我已经完成了所有我遇到的一切,直到python请求假设我要发送我的 POST数据自动content-type:multipart/form-data,但这并没有将我的发布数据作为 dict 对象,脚本以Content-Type: application/x-www-form-urlencoded

的形式发送请求
import requests
import logging
import os
import json
import csv

try:
    import http.client as http_client
except ImportError:
    # Python 2
    import httplib as http_client
http_client.HTTPConnection.debuglevel = 1

# You must initialize logging, otherwise you'll not see debug output.
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

url_and = "https://api.test.com/api/3.0/listings/"

android_token = '8fas8d7f9a8s7d9f87as9d8f7sa9df7s9f'
headers = {
    'Authorization': "Token " + android_token,
    'platform': 'android',
}

data_android = {}

with open("listingData1.csv", "r") as f_input:
    csv_input = csv.DictReader(f_input)

    for row in csv_input:
        data_android = {
        'mailing_details':row['shipping'],
        'abcoupay':'false',
        'price':row['price'],
        'description':row['desc'],
        'title':row['title'],
        'meetup':'false',
        'condition':'2',
        'mailing':'true',
        'collection_id':row['cat']
        }

        search_path = row['image']
        urls = []
        for file in os.listdir(os.getcwd()+search_path):
            if file.endswith((".jpg",".jpeg",".png",".JPG",".JPEG",".PNG")):
                x = os.getcwd()+"\\"+search_path+"\\"+file
                urls.append(x)


        files = {'photo_%s' % x: ('photo_%s.jpg' % x, open(file, 'rb'), 'image/jpeg') for x, file in enumerate(urls)}

        response = requests.request("POST", url_and,data=data_android,headers=headers)
        print(response.text.encode("utf-8"))

python请求发送http请求之类的

POST /api/3.0/listings/ HTTP/1.1
Host: api.test.com
Connection: keep-alive
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.21.0
platform: android
Authorization: Token as8fa7d87af7s9d8f79as8df0
Content-Length: 986
Content-Type: application/x-www-form-urlencoded

meetup=false&testupay=false&description=%95+Product+Details%0A%95+Suitable+for+very+small+dogs+and+cats%2C+rabbits+and+other+rodent+carriers+such+as+guinea+pigs%2C+ferrets%2C+rats+and+chinchillas.+Made+of+sturdy+plastic%2C+it+is+sturdy+and+convenient.+A+suitable+grill+allows+air+to+circulate+on+both+sides.+The+door+is+made+Of+plastic+coated+steel.+Thanks+to+the+ergonomic+handle%2C+the+mobile+utility.+It+has+a+mix+of+colors+to+choose+from.+--------%0A%95+80cm+length+X+56cm+width+X+65cm+height%0A%95+Approx.+4.1kg+after+assembly%0A%95+Suitable+for+pets+below+16kg%0A%95+Ideal+for+pet+transportation%0A%95+PP+plastic+material%3B+durable+and+sturdy%0A%95+Great+ventilation+and+air+flow%0A%95+Smart+lock+system%0A%95+Can+be+dismantled+for+easy+storage%0A%95+%2A+Please+check+that+this+item+meets+your+airline%27s+specific+requirements+prior+to+air+travel+usage+%2A%0A&mailing_details=FREE&collection_id=45&price=190&title=Pet+Cat+Dog+Carrier+Portable+Breathable&mailing=true&condition=2'

1 个答案:

答案 0 :(得分:1)

问题是发出POST请求时您正在使用数据而不是文件

如果像我在下面所做的那样将请求更改为使用文件字段,则请求应将Content-Type设置为multipart / form-data

response = requests.request("POST", url_and, files=data_android, headers=headers)