Запросы с multipart/form-data и без возврата файла 400
Я хочу преобразовать (рабочий) 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
, Я заменяю файл, запрошенный в первой позиции кортежа, которому я передаю 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)