curl到Python请求的转换

bakd9h0s  于 2022-11-13  发布在  Python
关注(0)|答案(7)|浏览(431)

我正在尝试将curl中的以下工作请求转换为python请求(使用Requests)。

curl --data 'query={"tags":["test1","test2"]}' http://www.test.com/match

(我使用了一个假的url,但该命令可以使用真实的的url)
接收端(在 flask 中运行)执行以下操作:

@app.route("/match", methods=['POST'])
def tagmatch():
    query = json.loads(request.form['query'])
    tags = query.get('tags')
    # ... does stuff ...
    return json.dump(stuff)

在curl(7.30)中,运行在Mac OS X(10.9)上,上面的命令正确地返回了一个使用标签查询过滤的JSON列表。
我的Python脚本如下所示,它返回一个400错误请求错误。

import requests

payload = {"tags":["test1", "test2"]}
# also tried  payload = 'query={"tags":["test1","test2"]}'
url = 'http://www.test.com/match'

r = requests.post(url, data=payload)

if __name__=='__main__':
     print(r.text)
ars1skjm

ars1skjm1#

https://curlconverter.com/上有一个开放源码的cURL到Python请求的转换助手。它并不完美,但在很多时候都有帮助。特别是对于转换Chrome的“复制为cURL”命令。如果你需要以编程方式进行转换,也有一个node library

d6kp6zgx

d6kp6zgx2#

您的服务器需要JSON,但您没有发送。请尝试以下操作:

import requests
import json

payload = {'query': json.dumps({"tags":["test1", "test2"]})}
url = 'http://www.test.com/match'

r = requests.post(url, data=payload)

if __name__=='__main__':
    print r.text
nuypyhwy

nuypyhwy3#

保存你一命
一个更简单的方法是:
1.打开POSTMAN
1.点击左上方的“导入”选项卡。
1.选择“原始文本”选项并粘贴cURL命令。
1.点击导入,你将在你的 Postman 构建器命令!
希望这对你有帮助!
作者:Onkaar Singh

lb3vh1jj

lb3vh1jj4#

尝试使用uncurl库。它很好地完成了它的工作。我已经试过了。

u = uncurl.parse(
        "curl -X GET 'https://mytesturl.com/' -H  'accept: application/json' -H  'Authorization: 1234567890'")
    print(u)

它打印,

requests.get("https://mytesturl.com/",
    headers={
        "Authorization": "1234567890",
        "accept": "application/json"
    },
    cookies={},
)
scyqe7ek

scyqe7ek5#

请尝试以下操作:
https://github.com/spulec/uncurl

import uncurl

print uncurl.parse("curl 'https://pypi.python.org/pypi/uncurl' -H 
'Accept-Encoding: gzip,deflate,sdch'")
v64noz0r

v64noz0r6#

我为Sublime Text编写了一个名为Requester的HTTP客户端插件,它的一个特性是将对cURL的调用转换为请求,反之亦然。
如果你使用的是Sublime Text,这可能是你最快、最简单的选择。如果不是,这里的代码实际上处理了从cURL到Requests的转换。它基于uncurl,但是有很多改进和bug修复。

import argparse
import json
try:
    from urllib.parse import urlencode, parse_qsl
except ImportError:  # works for Python 2 and 3
    from urllib import urlencode
    from urlparse import parse_qsl

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('command')
    parser.add_argument('url')
    parser.add_argument('-X', '--request', default=None)
    parser.add_argument('-d', '--data', default=None)
    parser.add_argument('-G', '--get', action='store_true', default=False)
    parser.add_argument('-b', '--cookie', default=None)
    parser.add_argument('-H', '--header', action='append', default=[])
    parser.add_argument('-A', '--user-agent', default=None)
    parser.add_argument('--data-binary', default=None)
    parser.add_argument('--compressed', action='store_true')

    parsed_args = parser.parse_args()

    method = 'get'
    if parsed_args.request:
        method = parsed_args.request

    base_indent = ' ' * 4
    post_data = parsed_args.data or parsed_args.data_binary or ''
    if post_data:
        if not parsed_args.request:
            method = 'post'
        try:
            post_data = json.loads(post_data)
        except ValueError:
            try:
                post_data = dict(parse_qsl(post_data))
            except:
                pass

    cookies_dict = {}

    if parsed_args.cookie:
        cookies = parsed_args.cookie.split(';')
        for cookie in cookies:
            key, value = cookie.strip().split('=')
            cookies_dict[key] = value

    data_arg = 'data'
    headers_dict = {}
    for header in parsed_args.header:
        key, value = header.split(':', 1)
        if key.lower().strip() == 'content-type' and value.lower().strip() == 'application/json':
            data_arg = 'json'

        if key.lower() == 'cookie':
            cookies = value.split(';')
            for cookie in cookies:
                key, value = cookie.strip().split('=')
                cookies_dict[key] = value
        else:
            headers_dict[key] = value.strip()
    if parsed_args.user_agent:
        headers_dict['User-Agent'] = parsed_args.user_agent

    qs = ''
    if parsed_args.get:
        method = 'get'
        try:
            qs = '?{}'.format(urlencode(post_data))
        except:
            qs = '?{}'.format(str(post_data))
        print(post_data)
        post_data = {}

    result = """requests.{method}('{url}{qs}',{data}\n{headers},\n{cookies},\n)""".format(
        method=method.lower(),
        url=parsed_args.url,
        qs=qs,
        data='\n{}{}={},'.format(base_indent, data_arg, post_data) if post_data else '',
        headers='{}headers={}'.format(base_indent, headers_dict),
        cookies='{}cookies={}'.format(base_indent, cookies_dict),
    )
    print(result)

你可以用这段代码创建一个脚本,比如curl_to_request.py,然后从命令行调用这个脚本,它对Python 2和Python 3都有效。

python curl_to_request.py curl -X POST -d 'key2=value2&key1=value1' 'http://httpbin.org/post'

python curl_to_request.py curl -X POST -H 'Content-Type: application/json' -d '{"key2": "value2", "key1": "value1"}' 'http://httpbin.org/post'

python curl_to_request.py curl -X POST -H 'Content-Type: application/json' -d '[1, 2, 3]' 'http://httpbin.org/post'

python curl_to_request.py curl -X POST -H 'Content-Type: application/json' -d '{"name": "Jimbo", "age": 35, "married": false, "hobbies": ["wiki", "pedia"]}' 'http://httpbin.org/post'

python curl_to_request.py curl -X GET 'http://httpbin.org/get?key2=value2&key1=value1'

python curl_to_request.py curl -X GET -H 'key1: value1' -H 'key2: value2' 'http://httpbin.org/headers'

python curl_to_request.py curl -X GET -b 'key1=value1;key2=value2' 'http://httpbin.org/cookies'
roqulrg3

roqulrg37#

从使用requests和Flask的代码来看,您似乎没有发布正确的数据格式。payload 应该是这样的:

payload = {'query': {'tags': ['test1', 'test2']},}

当使用requests.post()时,这看起来不像是正常的post数据。所以如果你在这里发布了html表单,可能会更清楚地解决这个问题。
下面是另一个类似的问题:使用Python请求传递登录名/密码

相关问题