【问题标题】:Python REST ConsumptionPython REST 消费
【发布时间】:2026-01-14 02:00:01
【问题描述】:

我开始扩展我的 Python 知识并尝试使用(例如,使用带有 XML 有效负载的 http POST 请求从数据库更新和接收数据)REST API。我很清楚如何使用 REST API,但我有点不确定要使用哪些库来专门针对 Python。

urllib 是要走的路吗? requests 模块? django(我完全天真)?

这不是一个充满意见的主观答案,而是一个简单的介绍和一个关于如何将urllib(或其他)与REST API结合使用的正确方向。

如何使用 Python 使用 REST 服务?

【问题讨论】:

  • *.com/questions/4355997/… 有帮助吗?
  • @PaulRooney 不是特别是因为我仍然不确定如何使用库来使用它。
  • “消费”是什么意思?你能更具体地了解你正在尝试做什么吗?您应该可以使用requests.getrequests.post 等。
  • 你需要什么?进行 http 调用并处理响应或其他什么?

标签: python django python-2.7 python-3.x urllib


【解决方案1】:

有很多 Python 库可以用来进行 REST 调用,其中最著名的是 Requests。

GET 调用示例

import requests

def consumeGETRequestSync():
 params = {'test1':'param1','test2':'param2'}
 url = 'http://httpbin.org/get'
 headers = {"Accept": "application/json"}
 # call get service with headers and params
 response = requests.get(url, headers = headers,data = params)
 print "code:"+ str(response.status_code)
 print "******************"
 print "headers:"+ str(response.headers)
 print "******************"
 print "content:"+ str(response.text)

consumeGETRequestSync()

POST 调用示例

import requests


def consumePOSTRequestSync():
 params = {'test1':'param1','test2':'param2'}
 url = 'http://httpbin.org/post'
 headers = {"Accept": "application/json"}
 # call post service with headers and params
 response = requests.post(url,headers= headers,data = params)
 print "code:"+ str(response.status_code)
 print "******************"
 print "headers:"+ str(response.headers)
 print "******************"
 print "content:"+ str(response.text)

# call 
consumePOSTRequestSync()

您可以查看此链接http://stackandqueue.com/?p=75了解更多详情

【讨论】:

    【解决方案2】:

    您好,我假设通过声明 REST Consumption,您的意思是使用 REST api 作为客户端(执行 GET 请求或 PUSH)

    这可能是我个人的偏好,但我总是使用 requests 库来进行我的 http 调用

    收到回复后,根据结果的类型,我将使用内置的json librarybeautifulsoup 解析它

    使用返回 JSON 结果的 REST API 非常棒,因为可以轻松地将 json 解码(加载)到 python 字典中。 (python 字典的结构与 json 相同)

    我将为您举一个带有 JSON 响应的 GET 请求的示例,因为它更容易,但您也可以轻松找到 POST 请求的示例

    import requests 
    import json 
    
    dest = 'https://github.com/timeline.json' 
    ## make the get request and store response
    res = requests.get(dest)
    ## you might want to check if respond code is correct by accessing attribute status_code 
    
    
    ## Get the body of the respond as text 
    body = res.text 
    ## load json string ( text ) into dictionary 
    res_dict = json.loads(body) 
    
    ## json is now a dict
    assert 'messages' in res_dict
    assert 'documentation_url' in res_dict 
    

    【讨论】:

      【解决方案3】:

      urllib2 和 requests 都可以完成这项工作。如果它只是一个 Web 服务 API,只需进行 http 调用。

      requests 模块是 JSON 响应的更好选择,因为 urllib2 没有 requests 具有的本机 JSON 序列化程序。对于 XML 响应,您必须使用外部 XML 解析器(例如 minidom)。关于进行 http 调用,requests 和 urllib2 并没有什么不同。这里有一个比较(What are the differences between the urllib, urllib2, and requests module?),但实际上它们是可以互换的。

      Django 是一个 Web 服务框架,处于一个完全不同的级别。 Django 应用程序既可以是 REST API 的服务提供者,也可以是客户端,但 Django 本身并没有自带。您仍然必须使用其他工具构建功能。您可以使用 django-rest-framework 构建您自己的 REST API 或以与请求相同的方式调用 3rd-party。

      【讨论】:

        【解决方案4】:

        对于 REST 客户端,我也会推荐请求,我只是对 biobirdman 的回答发表评论,但没有足够的代表。

        如果您使用的是 json,则无需导入 json 模块,您可以直接发送 dict 对象并将 json 响应解析回 dict,如下所示:例如。

        import requests
        
        uri = 'https://myendpoint/get_details_from_id'
        json_body={'id' : '123', 'attribute' : 'first_name'}
        
        resp = requests.post(uri,
                             json=json_body)
        
        response_as_dict=resp.json()
        

        希望对您有所帮助。

        【讨论】:

          最近更新 更多