简体   繁体   中英

How to convert Curl to Python request code?

I want to make a curl to python converter.

curl -X POST -H "data1:value1" -H "data2:value2" -d "{"datapart1":"random1","datapart2":"random2"}" "https://example.com"'

And i want to convert:

import requests

url = 'https://example.com'

data = '{"datapart1":"random1","datapart2":"random2"}'

headers = {'data1': 'value1', 'data2': 'value2'}

r = requests.post(url, data=data, headers=headers)
print(r.text)

I think you want this https://formatter.xyz/curl-to-python-converter

you try it that

curlconverter.com is a curl -> Python requests converter. It also outputs other languages.

It's implemented in JavaScript (actually TypeScript), so you can use it in your tool if you implement it in JavaScript too (instead of Python) or you can use one of the ways of calling JavaScript code from Python .

Alternatively, it has a command line interface you can call from Python. First, install the command line tool with npm install -g curlconverter then call it from Python with subprocess :

import subprocess

def curl_to_code(command, language='python'):
    return subprocess.run(['curlconverter', '--language', language, '-'], text=True, input=command, capture_output=True).stdout

print(curl_to_code("curl --data helloworld example.com"))

Disclaimer: I contribute to curlconverter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM