仅使用标准库将curl POST请求转换为Python [英] Convert a curl POST request to Python only using standard library

查看:896
本文介绍了仅使用标准库将curl POST请求转换为Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将此curl命令转换为可在Python中用于现有脚本的内容。

I would like to convert this curl command to something that I can use in Python for an existing script.

curl -u 7898678:X -H 'Content-Type: application/json' \
-d '{"message":{"body":"TEXT"}}' http://sample.com/36576/speak.json

TEXT是我想要替换为其余脚本生成的消息(这已经工作合理,虽然我不认为它是最好的做法或特殊性可靠。需要找出如何正确地学习编程(即不使用谷歌的汇编东西))

TEXT is what i would like to replace with a message generated by the rest of the script.(Which is already working reasonable, although I don't think it is following best practices or particularity reliable. - need to find out how to properly learn to program (ie not use google for assembling stuff))

我希望这可以使用标准库如果可能的话。 p>

I would like this to work with the standard library if possible.

推荐答案


我希望这可以与标准库一起使用。

I would like this to work with the standard library if possible.

标准库提供 urllib httplib

>>> import httplib, urllib
>>> params = urllib.urlencode({'apple': 1, 'banana': 2, 'coconut': 'yummy'})
>>> headers = {"Content-type": "application/x-www-form-urlencoded",
...            "Accept": "text/plain"}
>>> conn = httplib.HTTPConnection("example.com:80")
>>> conn.request("POST", "/some/path/to/site", params, headers)
>>> response = conn.getresponse()
>>> print response.status, response.reason
200 OK

如果要执行 curl 本身,但你可以调用 os.system()

If you want to execute curl itself, though, you can just invoke os.system():

import os
TEXT = ...
cmd = """curl -u 7898678:X -H 'Content-Type: application/json'""" \
  """-d '{"message":{"body":"%{t}"}}' http://sample.com/36576/speak.json""" % \
  {'t': TEXT}

仅限标准库的限制,您可以使用 PycURL 。注意,它不是非常Pythonic(它几乎只是一个薄的单板libcurl),我不知道它与Python 3的兼容性。

If you're willing to relax the standard-library-only restriction, you can use PycURL. Beware that it isn't very Pythonic (it's pretty much just a thin veneer over libcurl), and I'm not sure how compatible it is with Python 3.

这篇关于仅使用标准库将curl POST请求转换为Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆