简体   繁体   English

如何将curl命令转换为等效的python?

[英]How to turn curl command into python equivalent?

I'm trying to implement a python script which will set a webhook with the setWebhook method of telegram bot api. 我正在尝试实现一个python脚本,该脚本将使用电报bot api的setWebhook方法设置一个setWebhook As it is explained here after creating a self-signed certificate we can achieve this with this curl command: 正如在创建自签名证书后所解释的那样我们可以使用以下curl命令来实现此目的:

curl -F "url=https://<YOURDOMAIN.EXAMPLE>/<WEBHOOKLOCATION>" \
-F "certificate=@<YOURCERTIFICATE>.pem" https://api.telegram.org/bot<YOURTOKEN>/setWebhook

Calling this curl command set the webhook without any problem and I get updates through it. 调用此curl命令可以 毫无问题地设置webhook,我可以通过它进行更新。

But now I'm trying to achieve this with the python script so I could just call it with some command line arguments so it set webhook for me, get info about it or delete it. 但是现在我正在尝试使用python脚本实现这一目标,因此我可以使用一些命令行参数来调用它,以便它为我设置webhook,获取有关它的信息或删除它。 What I wrote so far is this: 到目前为止,我写的是:

files = {
        'file': ('certificate', open(configuration.CERTFILE, 'rb'))
    }

headers = {'Content-Type': 'multipart/form-data'}

data = {
        'url': configuration.WEBHOOK_URL,
    }

url = configuration.API % 'setWebhook'
rp = requests.post(url, headers=headers, data=data, files=files)

print('result of setWebhook: ', rp.status_code)

The status code of the response is 400 Bad Request . 响应的状态码 400 Bad Request I think that I'm sending the request the wrong way. 我认为我发送请求的方式有误。

Any ideas about what is wrong with my requests request to telegram bot api? 关于请求电报bot API的requests什么问题的任何想法?

The exact curl query taking two file parameters -F can be converted into python-requests into 带有两个文件参数-F的精确curl查询可以转换为python-requests

import requests

files = {
    'url': 'https://<YOURDOMAIN.EXAMPLE>/<WEBHOOKLOCATION>',
    'certificate': open('<YOURCERTIFICATE>.pem', 'rb')
}

requests.get('https://api.telegram.org/bot<YOURTOKEN>/setWebhook', files=files)

Removing headers parameter and renaming the key of the files parameter did the trick. 删除headers参数并重命名files参数的键就可以了。 So, now my code looks like this: 因此,现在我的代码如下所示:

files = {
    'certificate': ('certificate', open(configuration.CERTFILE, 'rb'))
}

data = {
    'url': configuration.WEBHOOK_URL,
}

url = configuration.API % 'setWebhook'
rp = requests.post(url, data=data, files=files)

and it works as intended. 它按预期工作。 Thanks gays! 谢谢同性恋!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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