【问题标题】:Simple URL GET/POST function in PythonPython 中的简单 URL GET/POST 函数
【发布时间】:2011-05-27 10:58:30
【问题描述】:

我似乎无法谷歌它,但我想要一个这样做的函数:

接受 3 个参数(或更多,随便):

  • 网址
  • 参数字典
  • POST 或 GET

将结果和响应代码返回给我。

有这样的sn-p吗?

【问题讨论】:

  • 问题不清楚——这是针对本地 URL 的,即。您正在编写服务器或远程 URL,即。你在写客户端?
  • 以后请使用更多的问题--描述性标题。

标签: python http


【解决方案1】:

请求

https://github.com/kennethreitz/requests/

以下是几种常用的使用方法:

import requests
url = 'https://...'
payload = {'key1': 'value1', 'key2': 'value2'}

# GET
r = requests.get(url)

# GET with params in URL
r = requests.get(url, params=payload)

# POST with form-encoded data
r = requests.post(url, data=payload)

# POST with JSON 
import json
r = requests.post(url, data=json.dumps(payload))

# Response, status etc
r.text
r.status_code

httplib2

https://github.com/jcgregorio/httplib2

>>> from httplib2 import Http
>>> from urllib import urlencode
>>> h = Http()
>>> data = dict(name="Joe", comment="A test comment")
>>> resp, content = h.request("http://bitworking.org/news/223/Meet-Ares", "POST", urlencode(data))
>>> resp
{'status': '200', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding,User-Agent',
 'server': 'Apache', 'connection': 'close', 'date': 'Tue, 31 Jul 2007 15:29:52 GMT', 
 'content-type': 'text/html'}

【讨论】:

  • 你也可以使用from httplib2 import Http as h
  • @3k 不,他正在实例化 Http 类,而不是给它起别名:h = Http(),而不是 h = Http
  • @ecstaticpeon 你说的很对,我一定很累了。谢谢指正!
  • 如果您在没有第三方库的情况下以本机方式执行此操作会很好。
【解决方案2】:

更简单:通过requests 模块。

import requests
get_response = requests.get(url='http://google.com')
post_data = {'username':'joeb', 'password':'foobar'}
# POST some form-encoded data:
post_response = requests.post(url='http://httpbin.org/post', data=post_data)

要发送非表单编码的数据,请将其序列化为字符串(示例取自documentation):

import json
post_response = requests.post(url='http://httpbin.org/post', data=json.dumps(post_data))
# If using requests v2.4.2 or later, pass the dict via the json parameter and it will be encoded directly:
post_response = requests.post(url='http://httpbin.org/post', json=post_data)

【讨论】:

  • 我必须将 post_data 包装在 json.dumps() 中才能为我工作:data=json.dumps(post_data)
  • @Matt,我认为这取决于您是要提交表单编码的数据(只需传入一个dict)还是非表单编码的数据(传入一串JSON数据) .我在这里参考文档:docs.python-requests.org/en/latest/user/quickstart/…
  • 有这个模块的windows版本吗?
  • @TheGoodUser 这个库(以及更多)是为 Windows 编译的,可以在这里找到:lfd.uci.edu/~gohlke/pythonlibs/#requests
【解决方案3】:

你可以用它来包装 urllib2:

def URLRequest(url, params, method="GET"):
    if method == "POST":
        return urllib2.Request(url, data=urllib.urlencode(params))
    else:
        return urllib2.Request(url + "?" + urllib.urlencode(params))

这将返回一个包含结果数据和响应代码的 Request 对象。

【讨论】:

  • 我更喜欢这个坚持标准库。
  • 应该是url + "?"而不是 url + '&'?
  • 这很好,但准确地说,Request 对象本身没有结果数据或响应代码 - 它需要通过像 urlopen 这样的方法“请求”。
  • @Bach 您是否有一个代码示例,该代码在此处使用 URLRequest 方法实现“请求”片段,例如 urlopen?我在任何地方都找不到。
  • @theJerm,我已经引用了它。尝试r = urllib2.urlopen(url),然后尝试r.readlines() 和/或r.getcode()。您也不妨考虑改用Requests
【解决方案4】:
import urllib

def fetch_thing(url, params, method):
    params = urllib.urlencode(params)
    if method=='POST':
        f = urllib.urlopen(url, params)
    else:
        f = urllib.urlopen(url+'?'+params)
    return (f.read(), f.code)


content, response_code = fetch_thing(
                              'http://google.com/', 
                              {'spam': 1, 'eggs': 2, 'bacon': 0}, 
                              'GET'
                         )

[更新]

其中一些答案是旧的。今天我会使用requests 模块,就像 robaple 的答案一样。

【讨论】:

    【解决方案5】:

    我知道你要求 GET 和 POST,但我会提供 CRUD,因为其他人可能需要这个以防万一:(这在 Python 3.7 中测试过)

    #!/usr/bin/env python3
    import http.client
    import json
    
    print("\n GET example")
    conn = http.client.HTTPSConnection("httpbin.org")
    conn.request("GET", "/get")
    response = conn.getresponse()
    data = response.read().decode('utf-8')
    print(response.status, response.reason)
    print(data)
    
    
    print("\n POST example")
    conn = http.client.HTTPSConnection('httpbin.org')
    headers = {'Content-type': 'application/json'}
    post_body = {'text': 'testing post'}
    json_data = json.dumps(post_body)
    conn.request('POST', '/post', json_data, headers)
    response = conn.getresponse()
    print(response.read().decode())
    print(response.status, response.reason)
    
    
    print("\n PUT example ")
    conn = http.client.HTTPSConnection('httpbin.org')
    headers = {'Content-type': 'application/json'}
    post_body ={'text': 'testing put'}
    json_data = json.dumps(post_body)
    conn.request('PUT', '/put', json_data, headers)
    response = conn.getresponse()
    print(response.read().decode(), response.reason)
    print(response.status, response.reason)
    
    
    print("\n delete example")
    conn = http.client.HTTPSConnection('httpbin.org')
    headers = {'Content-type': 'application/json'}
    post_body ={'text': 'testing delete'}
    json_data = json.dumps(post_body)
    conn.request('DELETE', '/delete', json_data, headers)
    response = conn.getresponse()
    print(response.read().decode(), response.reason)
    print(response.status, response.reason)
    

    【讨论】:

      猜你喜欢
      • 2013-05-01
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 2011-05-13
      • 2013-08-19
      • 1970-01-01
      • 2012-03-06
      相关资源
      最近更新 更多