python requests 高级用法

来源:互联网 发布:淘宝内部优惠券平台 编辑:程序博客网 时间:2024/04/23 19:35

http://my.oschina.net/HankCN/blog/123201

原创。


用法

 

本文档涵盖了一些requests更先的功能。

 

Session Objects话对

 

Session一定的参数。此外,还坚Session的所有cookie

 

让我们坚持在请求时使用

 

s = requests.Session()

 

s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')

r = s.get("http://httpbin.org/cookies")

 

print r.text

# '{"cookies": {"sessioncookie": "123456789"}}'

 

也可以用于提供默的数据的的方法。是通提供的数据会话对的属性:

 

s = requests.Session()

s.auth = ('user', 'pass')

s.headers.update({'x-test': 'true'})

 

# both 'x-test' and 'x-test2' are sent

s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

 

任何字典将被合并session级别置的值传递给请求方法。方法级别参数覆盖会参数

 

从一个字典参数中取值

 

如果你想在一个session中删除一个参数,那么你只需要设置它为none,他便自动被删去。

 

 

在一个session中的所有都包含直接提供。参Session API文档了解更多信息。

 

求和响应对

 

>>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')

 

查看

 

>>> r.headers

{'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':

'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':

'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',

'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',

'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,

must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':

'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,

MISS from cp1010.eqiad.wmnet:80'}

 

但是,如果我想要得到我的服报头,我只需访问请,然后标头

 

>>> r.request.headers

{'Accept-Encoding': 'identity, deflate, compress, gzip',

'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}

 

备请

 

当你API呼叫或会呼叫收到一个Response属性实际上是PreparedRequest使用。在某些情况下,求之前,你不妨做一些外的工作,身体或或任何其他真的)。简单配方如下:

 

from requests import Request, Session

 

s = Session()

prepped = Request('GET',  # or any other method, 'POST', 'PUT', etc.

                  url,

                  data=data

                  headers=headers

                  # ...

                  ).prepare()

# do something with prepped.body

# do something with prepped.headers

resp = s.send(prepped,

              stream=stream,

              verify=verify,

              proxies=proxies,

              cert=cert,

              timeout=timeout,

              # etc.

              )

print(resp.status_code)

 

既然你没有做什,你准立即修改的PreparedRequest。然后,您可以送您所要送的的其他参数。*Sesssion中。*

 

SSL证书验证

 

求可以验证SSL证书HTTPS,就像一个网络浏览检查主机的SSL证书,您可以使用校参数:

 

>>> requests.get('https://kennethreitz.com', verify=True)

requests.exceptions.SSLError: hostname 'kennethreitz.com' doesn't match either of '*.herokuapp.com', 'herokuapp.com'

 

我没有对这域的SSL,所以它的失好极了 Github然没有

 

>>> requests.get('https://github.com', verify=True)

<Response [200]>

 

您也可以通过验证一个私人证书CA_BUNDLE文件的路径。您可以REQUESTS_CA_BUNDLE

 

如果你验证设False也可以忽略验证SSL证书

 

>>> requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))

<Response [200]>

 

如果指定了错误的路径或无效的证书

 

>>> requests.get('https://kennethreitz.com', cert='/wrong_path/server.pem')

SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib

 

主体内容工作流程

 

情况下,当你提出一个机体的反是立即下。您可以重写此行,并推的身体,直到您访问Response.content,与流参数的属性:

 

tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'

r = requests.get(tarball_url, stream=True)

 

一点上已下的响应头接保持打,从而使我使内容条件:

 

if int(r.headers['content-length']) < TOO_LONG:

  content = r.content

  ...

 

您可以控制的使用的Response.iter_contentResponse.iter_lines方法的工作流程,或从基本的urllib3urllib3.HTTPResponseResponse.raw阅读

 

保持活

 

需要注意的是发布的连接会回到池会重用所有以读取的数据:

确保数据流false阅读Response的内容属性。

 

流上

 

支持它允大量的没有到内存流或文件流上,。要流和上只需你的身体提供了一个似文件的

 

with open('massive-body') as f:

    requests.post('http://some.url/streamed', data=f)

 

块编码请

 

还请支持分块传输编码传出和。要一个数据块编码,只是提供一个生成器(或任何没有的迭代器)您的BODY

 

def gen():

    yield 'hi'

    yield 'there'

 

requests.post('http://some.url/chunked', data=gen())

 

事件子:

 

有一个子,系,你可以用它来理申请过程中的部分或信号事件的

 

您可以指定一个子函数在求的基上,通一个{hook_namecallback_function}字典的钩请求参数

 

hooks=dict(response=print_url)

 

CALLBACK_FUNCTION将收到的数据第一个参数

 

>>> requests.get('http://httpbin.org', hooks=dict(response=print_url))

http://httpbin.org

<Response [200]>

 

自定身份验证

 

callback_function将收到一大的数据作第一个参数

 

from requests.auth import AuthBase

 

class PizzaAuth(AuthBase):

    """Attaches HTTP Pizza Authentication to the given Request object."""

    def __init__(self, username):

        # setup any auth-related data here

        self.username = username

 

    def __call__(self, r):

        # modify and return the request

        r.headers['X-Pizza'] = self.username

        return r

 

Then, we can make a request using our Pizza Auth:

 

>>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))

<Response [200]>

 

 

代理

 

import requests

 

proxies = {

  "http": "http://10.10.1.10:3128",

  "https": "http://10.10.1.10:1080",

}

 

requests.get("http://example.org", proxies=proxies)

 

可以配置代理服HTTP_PROXY and HTTPS_PROXY.

 

$ export HTTP_PROXY="http://10.10.1.10:3128"

$ export HTTPS_PROXY="http://10.10.1.10:1080"

$ python

>>> import requests

>>> requests.get("http://example.org")

 

To use HTTP Basic Auth with your proxy, use the http://user:password@host/ syntax:

 

proxies = {

    "http": "http://user:pass@10.10.1.10:3128/",

}

 

遵守:

 

要求是符合相RFC的合,不会造成困受到注,可能会一些看似常的行,可能那些不熟悉有关规

 

编码:

 

如果没有明确的字符集是在HTTPContent-Type中包含文本。在这种情况下RFC 2616指定默的字符集ISO-8859-1

 

HTTP动词

 

要求提供访问几乎是全方位的HTTP动词GETOPTIONSHEADPOSTPUTPATCHDELETE。下面提供了详细的例子,使用些不同的动词求中,使用GitHubAPI

 

>>> import requests

>>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')

 

 

因此,GitHub的返回JSON。我可以使用r.json的方法来解析Python

 

>>> commit_data = r.json()

>>> print commit_data.keys()

[u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']

>>> print commit_data[u'committer']

{u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}

>>> print commit_data[u'message']

makin' history

 

求可以很容易地使用各形式的认证,包很常的基本身份验证

 

>>> from requests.auth import HTTPBasicAuth

>>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')

>>> r = requests.post(url=url, data=body, auth=auth)

>>> r.status_code

201

>>> content = r.json()

>>> print content[u'body']

Sounds great! I'll get right on it.

 

原创。


用法

 

本文档涵盖了一些requests更先的功能。

 

Session Objects话对

 

Session一定的参数。此外,还坚Session的所有cookie

 

让我们坚持在请求时使用

 

s = requests.Session()

 

s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')

r = s.get("http://httpbin.org/cookies")

 

print r.text

# '{"cookies": {"sessioncookie": "123456789"}}'

 

也可以用于提供默的数据的的方法。是通提供的数据会话对的属性:

 

s = requests.Session()

s.auth = ('user', 'pass')

s.headers.update({'x-test': 'true'})

 

# both 'x-test' and 'x-test2' are sent

s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

 

任何字典将被合并session级别置的值传递给请求方法。方法级别参数覆盖会参数

 

从一个字典参数中取值

 

如果你想在一个session中删除一个参数,那么你只需要设置它为none,他便自动被删去。

 

 

在一个session中的所有都包含直接提供。参Session API文档了解更多信息。

 

求和响应对

 

>>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')

 

查看

 

>>> r.headers

{'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':

'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':

'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',

'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',

'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,

must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':

'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,

MISS from cp1010.eqiad.wmnet:80'}

 

但是,如果我想要得到我的服报头,我只需访问请,然后标头

 

>>> r.request.headers

{'Accept-Encoding': 'identity, deflate, compress, gzip',

'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}

 

备请

 

当你API呼叫或会呼叫收到一个Response属性实际上是PreparedRequest使用。在某些情况下,求之前,你不妨做一些外的工作,身体或或任何其他真的)。简单配方如下:

 

from requests import Request, Session

 

s = Session()

prepped = Request('GET',  # or any other method, 'POST', 'PUT', etc.

                  url,

                  data=data

                  headers=headers

                  # ...

                  ).prepare()

# do something with prepped.body

# do something with prepped.headers

resp = s.send(prepped,

              stream=stream,

              verify=verify,

              proxies=proxies,

              cert=cert,

              timeout=timeout,

              # etc.

              )

print(resp.status_code)

 

既然你没有做什,你准立即修改的PreparedRequest。然后,您可以送您所要送的的其他参数。*Sesssion中。*

 

SSL证书验证

 

求可以验证SSL证书HTTPS,就像一个网络浏览检查主机的SSL证书,您可以使用校参数:

 

>>> requests.get('https://kennethreitz.com', verify=True)

requests.exceptions.SSLError: hostname 'kennethreitz.com' doesn't match either of '*.herokuapp.com', 'herokuapp.com'

 

我没有对这域的SSL,所以它的失好极了 Github然没有

 

>>> requests.get('https://github.com', verify=True)

<Response [200]>

 

您也可以通过验证一个私人证书CA_BUNDLE文件的路径。您可以REQUESTS_CA_BUNDLE

 

如果你验证设False也可以忽略验证SSL证书

 

>>> requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))

<Response [200]>

 

如果指定了错误的路径或无效的证书

 

>>> requests.get('https://kennethreitz.com', cert='/wrong_path/server.pem')

SSLError: [Errno 336265225] _ssl.c:347: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib

 

主体内容工作流程

 

情况下,当你提出一个机体的反是立即下。您可以重写此行,并推的身体,直到您访问Response.content,与流参数的属性:

 

tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'

r = requests.get(tarball_url, stream=True)

 

一点上已下的响应头接保持打,从而使我使内容条件:

 

if int(r.headers['content-length']) < TOO_LONG:

  content = r.content

  ...

 

您可以控制的使用的Response.iter_contentResponse.iter_lines方法的工作流程,或从基本的urllib3urllib3.HTTPResponseResponse.raw阅读

 

保持活

 

需要注意的是发布的连接会回到池会重用所有以读取的数据:

确保数据流false阅读Response的内容属性。

 

流上

 

支持它允大量的没有到内存流或文件流上,。要流和上只需你的身体提供了一个似文件的

 

with open('massive-body') as f:

    requests.post('http://some.url/streamed', data=f)

 

块编码请

 

还请支持分块传输编码传出和。要一个数据块编码,只是提供一个生成器(或任何没有的迭代器)您的BODY

 

def gen():

    yield 'hi'

    yield 'there'

 

requests.post('http://some.url/chunked', data=gen())

 

事件子:

 

有一个子,系,你可以用它来理申请过程中的部分或信号事件的

 

您可以指定一个子函数在求的基上,通一个{hook_namecallback_function}字典的钩请求参数

 

hooks=dict(response=print_url)

 

CALLBACK_FUNCTION将收到的数据第一个参数

 

>>> requests.get('http://httpbin.org', hooks=dict(response=print_url))

http://httpbin.org

<Response [200]>

 

自定身份验证

 

callback_function将收到一大的数据作第一个参数

 

from requests.auth import AuthBase

 

class PizzaAuth(AuthBase):

    """Attaches HTTP Pizza Authentication to the given Request object."""

    def __init__(self, username):

        # setup any auth-related data here

        self.username = username

 

    def __call__(self, r):

        # modify and return the request

        r.headers['X-Pizza'] = self.username

        return r

 

Then, we can make a request using our Pizza Auth:

 

>>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))

<Response [200]>

 

 

代理

 

import requests

 

proxies = {

  "http": "http://10.10.1.10:3128",

  "https": "http://10.10.1.10:1080",

}

 

requests.get("http://example.org", proxies=proxies)

 

可以配置代理服HTTP_PROXY and HTTPS_PROXY.

 

$ export HTTP_PROXY="http://10.10.1.10:3128"

$ export HTTPS_PROXY="http://10.10.1.10:1080"

$ python

>>> import requests

>>> requests.get("http://example.org")

 

To use HTTP Basic Auth with your proxy, use the http://user:password@host/ syntax:

 

proxies = {

    "http": "http://user:pass@10.10.1.10:3128/",

}

 

遵守:

 

要求是符合相RFC的合,不会造成困受到注,可能会一些看似常的行,可能那些不熟悉有关规

 

编码:

 

如果没有明确的字符集是在HTTPContent-Type中包含文本。在这种情况下RFC 2616指定默的字符集ISO-8859-1

 

HTTP动词

 

要求提供访问几乎是全方位的HTTP动词GETOPTIONSHEADPOSTPUTPATCHDELETE。下面提供了详细的例子,使用些不同的动词求中,使用GitHubAPI

 

>>> import requests

>>> r = requests.get('https://api.github.com/repos/kennethreitz/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad')

 

 

因此,GitHub的返回JSON。我可以使用r.json的方法来解析Python

 

>>> commit_data = r.json()

>>> print commit_data.keys()

[u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']

>>> print commit_data[u'committer']

{u'date': u'2012-05-10T11:10:50-07:00', u'email': u'me@kennethreitz.com', u'name': u'Kenneth Reitz'}

>>> print commit_data[u'message']

makin' history

 

求可以很容易地使用各形式的认证,包很常的基本身份验证

 

>>> from requests.auth import HTTPBasicAuth

>>> auth = HTTPBasicAuth('fake@example.com', 'not_a_real_password')

>>> r = requests.post(url=url, data=body, auth=auth)

>>> r.status_code

201

>>> content = r.json()

>>> print content[u'body']

Sounds great! I'll get right on it.

 


0 0
原创粉丝点击