curl 到 python 请求的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20461194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:30:23  来源:igfitidea点击:

Conversion of curl to python Requests

pythonpython-2.7curlpython-requests

提问by zalc

I'm trying to convert the following working request in curl to a python request (using the Requests http://docs.python-requests.org/en/v0.10.7/).

我正在尝试将 curl 中的以下工作请求转换为 python 请求(使用请求http://docs.python-requests.org/en/v0.10.7/)。

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

(please note, I've used a fake url but the command does work with the real url)

(请注意,我使用了假网址,但该命令确实适用于真实网址)

The receiving end (ran in Flask) does this:

接收端(在 Flask 中运行)执行以下操作:

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

In curl (7.30), ran on Mac OS X (10.9) the command above properly returns a json list that filtered using the tag query.

在 curl (7.30) 中,在 Mac OS X (10.9) 上运行,上面的命令正确返回使用标签查询过滤的 json 列表。

My python script is as follows, it returns a 400 bad request.

我的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

I feel I'm missing something small and any help would be appreciated.

我觉得我错过了一些小东西,任何帮助将不胜感激。

Thank you

谢谢

采纳答案by Lukasa

Your server is expecting JSON, but you aren't sending it. Try this:

您的服务器需要 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

回答by flyer

From your code using requestsand in Flask, it seems like you don't post the right data format. The payloadshould be like this:

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

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

This seems not normal as post data when using requests.post(). So if you have posted the html form here, it may have been more clear to solve the problem.
Here is another similar question: Using Python Requests to pass through a login/password

使用requests.post(). 所以如果你把html表单贴在这里,解决问题可能就更清楚了。
这是另一个类似的问题:Using Python Requests to pass through a login/password

回答by Gourneau

There is a wonderful open source cURL to Python Requests conversion helper at http://curl.trillworks.com. It isn't perfect, but helps out a lot of the time. Especially for converting Chrome "Copy as cURL" commands. There is also a node libraryif you need to do the conversions programmatically

http://curl.trillworks.com 上有一个很棒的开源 cURL 到 Python 请求转换助手。它并不完美,但在很多时候会有所帮助。特别是用于转换 Chrome 的“Copy as cURL”命令。如果您需要以编程方式进行转换,还有一个节点库

cURL from Chrome

来自 Chrome 的 cURL

回答by kylebebak

I wrote an HTTP client plugin for Sublime Text called Requester, and one of its features is to convert calls to cURL to Requests, and vice versa.

我为 Sublime Text 编写了一个 HTTP 客户端插件,名为Requester,它的功能之一是将调用 cURL转换为 Requests,反之亦然

If you're using Sublime Text this is probably your fastest, easiest option. If not, here's the code that actually handles the conversion from cURL to Requests. It's based uncurl, but with various improvements and bug fixes.

如果您使用 Sublime Text,这可能是您最快、最简单的选择。如果没有,这里是实际处理从 cURL 到请求的转换的代码。它基于uncurl,但有各种改进和错误修复。

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)

You could make a script with this code, e.g. curl_to_request.py, and call this script from the command line like so. It will work for both Python 2 and Python 3.

您可以使用此代码创建一个脚本,例如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'

回答by Pegasus

try this:

尝试这个:

https://github.com/spulec/uncurl

https://github.com/spurec/uncurl

import uncurl

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

回答by MKRNaqeebi

Save your life

拯救你的生命

A simpler approach would be:

一个更简单的方法是:

  1. Open POSTMAN
  2. Click on the "import" tab on the upper left side.
  3. Select the Raw Text option and paste your cURL command.
  4. Hit import and you will have the command in your Postman builder!
  1. 打开邮递员
  2. 单击左上角的“导入”选项卡。
  3. 选择原始文本选项并粘贴您的 cURL 命令。
  4. 点击导入,您将在 Postman 构建器中拥有该命令!

Hope this helps!

希望这可以帮助!

credit: Onkaar Singh

图片来源:Onkaar Singh

回答by snr

Try to use uncurllibrary. It is pretty nice to do its job. I've tried it.

尝试使用uncurl库。做它的工作非常好。我试过了。

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

It prints,

它打印,

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