V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
y
V2EX  ›  Python

求助: 怎么把这个 curl 命令用 python requests 搞定?

  •  
  •   y · 2013-05-20 01:39:32 +08:00 · 16465 次点击
    这是一个创建于 3991 天前的主题,其中的信息可能已经有所发展或是发生改变。
    命令如下:

    curl -X POST -d '{ "method" : "test", "params" : [ { "detail" : "Hello_world"} ] }' http://example.com

    在 bash 里面执行是能得到想要的结果的。但希望在 python 里面搞。

    其中 data 的部分是 { "method" : "test", "params" : [ { "detail" : "Hello_world"} ] }

    我不太清楚怎么用 python requests 处理 [ { "detail" : "Hello_world"} ] 这个部分。

    现在的做法是 os.system 写到一个文件里,再把文件里的内容读出来,囧。
    5 条回复    2017-07-15 01:37:46 +08:00
    mengzhuo
        1
    mengzhuo  
       2013-05-20 01:55:19 +08:00
    确实囧得很
    json模块不行吗?
    Jet
        2
    Jet  
       2013-05-20 04:22:13 +08:00
    import httplib
    import json

    p = { "method" : "test", "params" : [ { "detail" : "Hello_world"} ] }
    headers = {"Content-type":"application/x-www-form-urlencoded","Accept":"text/plain"}
    conn = httplib.HTTPConnection("127.0.0.1", 8081)
    conn.request("POST","", json.dumps(p), headers)

    不知道理解是否正确。
    hit9
        3
    hit9  
       2013-05-20 09:12:08 +08:00
    In [1]: import requests

    In [2]: data = {
    ...: 'method': 'test',
    ...: 'params': [
    ...: {'detail':'hello world'}
    ...: ]
    ...: }

    In [3]: requests.post("http://example.com",data=data)
    Out[3]: <Response [200]>
    zhengjian
        5
    zhengjian  
       2017-07-15 01:37:46 +08:00   ❤️ 1
    推荐一个网站: https://curl.trillworks.com/
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3437 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 11:19 · PVG 19:19 · LAX 04:19 · JFK 07:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.