具有multipart / form-data且没有文件的请求返回400

时间:2018-06-12 09:34:59

标签: python-3.x python-requests multipartform-data

我想将(working)curl命令转换为Python:

$ curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: text/html; charset=utf-8; profile="https://www.mediawiki.org/wiki/Specs/HTML/1.7.0"' -F wikitext=%27%27%27Mahikari%27%27%27%20is%20a%20%5B%5BJapan%5D%5Dese%20%5B%5Bnew%20religious%20movement%5D%5D -F body_only=true   'https://en.wikipedia.org/api/rest_v1/transform/wikitext/to/html'
<p id="mwAQ">%27%27%27Mahikari%27%27%27%20is%20a%20%5B%5BJapan%5D%5Dese%20%5B%5Bnew%20religious%20movement%5D%5D</p>

使用Requests,我将{I}传递给files的元组的第一个位置请求的文件替换为None(显然是此API的重载功能),但我可以'仍然这个代码工作。它返回400

    import requests
    text = """
    The '''Runyon classification''' of nontuberculous [[mycobacteria]] based on the rate of growth, production of yellow pigment and whether this pigment was 
    produced in the dark or only after exposure to light.

    It was introduced by Ernest Runyon in 1959.
    """
    multipart_data = {
            'wikitext': (None, urllib.parse.quote(text)),
            'body_only': (None, 'true'),
    }
    url = 'https://en.wikipedia.org/api/rest_v1/transform/wikitext/to/html'
    headers = {'Content-Type': 'multipart/form-data', 'Accept': 'text/html; charset=utf-8; profile="https://www.mediawiki.org/wiki/Specs/HTML/1.7.0"'}
    r = requests.post(url, files=multipart_data,  headers=headers)  # , headers={'Content-Type': 'multipart/form-data', 'Accept': 'text/html; charset=utf-8; profile="https://www.mediawiki.org/wiki/Specs/HTML/1.7.0"'})
    if r.status_code == 200:

更新

我尝试了使用requests_toolbelt.multipart.encoder.MultipartEncoder的其他解决方案,但仍无效:

    from requests_toolbelt.multipart.encoder import MultipartEncoder
    text = """
    The '''Runyon classification''' of nontuberculous [[mycobacteria]] based on the rate of growth, production of yellow pigment and whether this pigment was produced in the dark or only after exposure to light.

It was introduced by Ernest Runyon in 1959.
    """
    from requests_toolbelt.multipart.encoder import MultipartEncoder

    multipart_data = MultipartEncoder(
        fields=(
            ('wikitext', urllib.parse.quote(text)),
            ('body_only', 'true'),
        )
    )
    url = 'https://en.wikipedia.org/api/rest_v1/transform/wikitext/to/html'
    headers = {'Content-Type': 'multipart/form-data', 'Accept': 'text/html; charset=utf-8; profile="https://www.mediawiki.org/wiki/Specs/HTML/1.7.0"'}
    r = requests.post(url, data=multipart_data,  headers=headers)

0 个答案:

没有答案