Convert a curl POST request to Python only using standard library

前端 未结 4 515
没有蜡笔的小新
没有蜡笔的小新 2020-12-28 16:02

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/jso         


        
4条回答
  •  春和景丽
    2020-12-28 17:01

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

    The standard library provides urllib and httplib for working with URLs:

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

    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}
    

    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.

提交回复
热议问题