【问题标题】:Alternative to requests.post function?替代 requests.post 功能?
【发布时间】:2016-03-21 23:03:05
【问题描述】:

我不能使用 python requests 包(说来话长,假设我已经用尽了使用该包的所有可能性)

是否有替代包可以提供以下代码的确切功能?

import requests
requests.post(URL, data=DATA, auth=(USERNAME, PASSWORD), headers=HEADER)

【问题讨论】:

  • 不能使用就不能安装?
  • 即使你不能安装它,requests 也是一个纯 python 模块,你可以下载它并解压到你的应用程序的目录并从那里导入它。不然看代码复制出来!
  • 不,它已安装。但这是一个大的 django 页面,不幸的是,其中一个应用程序被非常愚蠢地命名为 requests,因此 import requests 会导入该应用程序。我试过直接引用请求的文件路径,但运气不佳。也许我会继续尝试——正在寻找另一种方式。
  • 在我们的案例中,请求库依赖于 chardet 是一个法律问题,即许可证:GNU 库或较小的通用公共许可证 (LGPL) (LGPL)

标签: python python-2.7 python-requests


【解决方案1】:

另一种方式,httplib的使用

import httplib
import urllib
from base64 import b64encode

# your form
form_data = {'a':1 'b':2}
params = urllib.urlencode(form_data)

# build authorization
user_and_pass = b64encode(b"username:password").decode("ascii")

# headers
headers = {'Authorization': 'Basic %s' % user_and_pass}

# connection
conn = httplib.HTTPConnection("example.com")
conn.request('POST', '/v3/call_api', params, headers)

# get result
response = conn.getresponse()

print response.status, response.reason

data = response.read()

conn.close()

【讨论】:

    【解决方案2】:

    如果您唯一的问题是由于模块名称而导致导入,您始终可以通过完整路径导入或更改模块搜索路径并在导入后重置它。为了避免冲突,您可以使用import requests as requests2 或类似的东西。 有关第一个选项或有关搜索路径的文档,请参阅以下问题。

    How to import a module given the full path?

    https://docs.python.org/2/tutorial/modules.html#the-module-search-path

    【讨论】:

    • 我完全同意这通常是正确的路线;不幸的是,我花了大约一个小时尝试这个,然后才发布我的问题,但没有任何运气。我们的服务器设置现在有点时髦,这让事情变得复杂。
    【解决方案3】:

    来自urllib2.urlopen

    “当提供数据参数时,HTTP 请求将是 POST 而不是 GET。”

    类似的东西(我将使用一个图像示例,只是因为它太晦涩难懂):

    import urllib
    import urllib2
    
    import numpy as np
    import cv2
    
    image_to_send = np.zeros(512, np.uint8)
    buffer_image = \
        np.array(cv2.imencode('.png', image_to_send)[1]).tostring()
    post_data = \
        urllib.urlencode((('img_type','.png'),('img_data',buffer_image)))
    req = \
        urllib2.urlopen('http://www.yourdestination.com/imageupload/', data=post_data)
    

    如果你想要认证,你需要继承urllib.FancyURLopener,并覆盖prompt_user_passwd

    【讨论】:

      【解决方案4】:

      您可以尝试使用 python 请求的替代方法, https://github.com/juancarlospaco/faster-than-requests

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-07
        • 2020-09-03
        • 2021-06-16
        • 1970-01-01
        • 2022-01-24
        相关资源
        最近更新 更多