---恢复内容开始---

Request的五种请求方式

方法

说明

requests.request()

构造一个请求,支撑以下各方法的基础方法

requests.get()

获取HTML网页的主要方法,对应于HTTP的GET

requests.head()

获取HTML网页头信息的方法,对应于HTTP的HEAD

request.post()

向HTML网页提交POST请求的方法,对应于HTTP的POST

request.put()

向HTML网页提交PUT请求的方法,对应于HTTP的PUT

request.patch()

向HTML网页提交局部修改请求,对应于HTTP的PATCH

request.delete()

向HTML页面提交删除请求,对应于HTTP的DELETE

 

一:request.get():

源码:

 def get(url, params=None, **kwargs):
r"""Sends a GET request. :param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary, list of tuples or bytes to send
in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
""" kwargs.setdefault('allow_redirects', True)
return request('get', url, params=params, **kwargs)

requst.get()源码

参数解析及使用

 import requests
r=requests.request('post','http://www.oldboyedu.com',params={'k1':'python'})
print(r.url)
#https://www.oldboyedu.com/?k1=python

get参数使用

response对象的属性

属性 说明
r.status_code HTTP请求的返回状态,200表示连接成功,404表示失败
r.text HTTP响应内容的字符串形式,即,url对应的页面内容
r.encoding 从HTTP header中猜测的响应内容编码方式
r.apparent_encoding 从内容分析出的响应内容编码方式(备选编码方式)
r.content HTTP响应内容的二进制形式
r.json 返回json数据
r.request 返回请求方式
r.headers 返回请求头
r.cookies   返回cookie

理解Response的编码

属性 说明
r.encoding 从HTTP header中猜测的响应内容编码方式
r.apparent_encoding 从内容中分析出的响应内容编码方式(备选编码方式)

r.encoding:如果header中不存在charset,则认为编码为ISO-8859-1
r.apparent_encoding:根据网页内容分析出的编码方式。

理解Requests库的异常

异常 说明
requests.ConnectionError 网络连接错误异常,如DNS查询失败、拒绝连接等
requests.HTTPError HTTP错误异常
requests.URLRequired URL缺失异常
requests.TooMangRedirects 超过最大重定向次数,产生重定向异常
requests.ConnectTimeout 连接远程服务器超时异常
requests.Timeout 请求URL超时,产生超时异常
r.raise_for_status() 如果不是200,产生异常requests.HTTPError

更多参数

     :param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary, list of tuples or bytes to send
in the body of the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
``file-tuple`` can be a -tuple ``('filename', fileobj)``, -tuple ``('filename', fileobj, 'content_type')``
or a -tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
to add for the file.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How many seconds to wait for the server to send data
before giving up, as a float, or a :ref:`(connect timeout, read
timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use. Defaults to ``True``.
:param stream: (optional) if ``False``, the response content will be immediately downloaded.
:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.

request.request()的参数

参数运用

  • params
      # - 可以是字典
# - 可以是字符串
# - 可以是字节(ascii编码以内) # requests.request(method='get',
# url='http://127.0.0.1:8000/test/',
# params={'k1': 'v1', 'k2': '水电费'}) # requests.request(method='get',
# url='http://127.0.0.1:8000/test/',
# params="k1=v1&k2=水电费&k3=v3&k3=vv3") # requests.request(method='get',
# url='http://127.0.0.1:8000/test/',
# params=bytes("k1=v1&k2=k2&k3=v3&k3=vv3", encoding='utf8'))

params参数

  • json
     # 将json中对应的数据进行序列化成一个字符串,json.dumps(...)
# 然后发送到服务器端的body中,并且Content-Type是 {'Content-Type': 'application/json'}

json参数

  • headers
     # 发送请求头到服务器端
requests.request(method='POST',
url='http://127.0.0.1:8000/test/',
json={'k1': 'v1', 'k2': '水电费'},
headers={'Content-Type': 'application/x-www-form-urlencoded'}
)

header参数

  • cookies
     # 发送Cookie到服务器端
requests.request(method='POST',
url='http://127.0.0.1:8000/test/',
data={'k1': 'v1', 'k2': 'v2'},
cookies={'cook1': 'value1'},
)

cookies

  • files
     # 发送文件
# file_dict = {
# 'f1': open('readme', 'rb')
# }
# requests.request(method='POST',
# url='http://127.0.0.1:8000/test/',
# files=file_dict) # 发送文件,定制文件名
# file_dict = {
# 'f1': ('test.txt', open('readme', 'rb'))
# }
# requests.request(method='POST',
# url='http://127.0.0.1:8000/test/',
# files=file_dict) # 发送文件,定制文件名
# file_dict = {
# 'f1': ('test.txt', "hahsfaksfa9kasdjflaksdjf")
# }
# requests.request(method='POST',
# url='http://127.0.0.1:8000/test/',
# files=file_dict) # 发送文件,定制文件名
# file_dict = {
# 'f1': ('test.txt', "hahsfaksfa9kasdjflaksdjf", 'application/text', {'k1': ''})
# }
# requests.request(method='POST',
# url='http://127.0.0.1:8000/test/',
# files=file_dict)

files

  • auth
     from requests.auth import HTTPBasicAuth, HTTPDigestAuth

     ret = requests.get('https://api.github.com/user', auth=HTTPBasicAuth('wupeiqi', 'sdfasdfasdf'))
print(ret.text) # ret = requests.get('http://192.168.1.1',
# auth=HTTPBasicAuth('admin', 'admin'))
# ret.encoding = 'gbk'
# print(ret.text) # ret = requests.get('http://httpbin.org/digest-auth/auth/user/pass', auth=HTTPDigestAuth('user', 'pass'))
# print(ret)
#

auth参数

  • timeout
     # ret = requests.get('http://google.com/', timeout=)
# print(ret) # ret = requests.get('http://google.com/', timeout=(, ))
# print(ret)
pass
第一个时间为链接时间,第二个时间为服务器发送第一个数据的时间

tineout

  • allow-redirects:是否允许重定向
     # ret = requests.get('http://google.com/', timeout=)
# print(ret) # ret = requests.get('http://google.com/', timeout=(, ))
# print(ret)
pass

allow_redirects

  • proxies:设置代理
     # proxies = {
# "http": "61.172.249.96:80",
# "https": "http://61.185.219.126:3128",
# } # proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'} # ret = requests.get("http://www.proxy360.cn/Proxy", proxies=proxies)
# print(ret.headers) # from requests.auth import HTTPProxyAuth
#
# proxyDict = {
# 'http': '77.75.105.165',
# 'https': '77.75.105.165'
# }
# auth = HTTPProxyAuth('username', 'mypassword')
#
# r = requests.get("http://www.google.com", proxies=proxyDict, auth=auth)
# print(r.text)

proxies

  • stream:相当于下一点保存一点
     ret = requests.get('http://127.0.0.1:8000/test/', stream=True)
print(ret.content)
ret.close() # from contextlib import closing
# with closing(requests.get('http://httpbin.org/get', stream=True)) as r:
# # 在此处理响应。
# for i in r.iter_content():
# print(i)

stream

  • verify:指定是否进行https认证

requests.get('https://kennethreitz.org',verify=False)

  • cert是保存本地ssl证书路径的字段

requests.get('https://kennethreitz.org',cert=('/path/client.cert','/path/client.key'))

其中data参数中的数据型类型只能是字符串,列表,数字,文件,不可以再数据里提交字典

json参数中的数据类型可以试字符串,列表,数字,还有字典,可序列化对象

requests库的session对象能够帮我们跨请求保持某些参数,也会在同一个session实例发出的所有请求之间保持cookies

参考:

链接:https://www.jianshu.com/p/d78982126318

python Request模块的更多相关文章

  1. python request模块学习

    安装: pip install requests 使用: import requests HTTP请求:GET.POST.PUT.DELETE.HEAD.OPTIONS 1) get res = re ...

  2. python接口自动化测试(一)-request模块

    urllib.request模块是python3针对处理url的. 1. 首先导入: from urllib import request 2. 构造url,构造url的headers信息和传参[re ...

  3. python自动化测试学习笔记-6urllib模块&request模块

    python3的urllib 模块提供了获取页面的功能. urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capat ...

  4. Python之request模块-基础用法

    Request模块参考中文手册:https://requests.readthedocs.io/zh_CN/latest/ Request模块 1.查看pip已装包(模块)的安装信息(模块的路径.版本 ...

  5. python中的request模块

    本文转自:https://www.cnblogs.com/ydy11/p/8902631.html(版权归属原作者,因觉得写得非常好,故引用) python模块之request模块的理解 reques ...

  6. python模块之request模块的理解

    首先还是老生长谈,说说定义和作用,request模块是一个用于访问网络的模块,其实类似的模块还有很多,不在一一在这里解释.这么多的相似的模块为什么都说只有这个好用呢.因为他人性化.如果你学过urlli ...

  7. python flask的request模块以及在flask编程中遇到的坑

    一.首先来讲讲遇到的坑: 1.linux下package的打包引用: """ 路径结构如下: ./project ./bin ./api ""&quo ...

  8. python 各模块

    01 关于本书 02 代码约定 03 关于例子 04 如何联系我们 1 核心模块 11 介绍 111 内建函数和异常 112 操作系统接口模块 113 类型支持模块 114 正则表达式 115 语言支 ...

  9. python+request接口自动化框架

    python+request接口自动化框架搭建 1.数据准备2.用python获取Excel文件中测试用例数据3.通过requests测试接口4.根据接口返回的code值和Excel对比 但本章只讲整 ...

随机推荐

  1. Nginx与前端开发

    Nginx与Node.js "Nginx是一款轻量级的HTTP服务器,采用事件驱动的异步非阻塞处理方式框架,这让其具有极好的IO性能,时常用于服务端的反向代理和负载均衡." 作为前 ...

  2. linux 常用命令集锦

    喝断片儿了,我是谁?我在什么地方?我做过些什么事?查看当前用户 who am i查看当前路径 pwd查看历史记录 history 我忘了程序放哪了,就记得个名.更新系统数据库 updatedb查找文件 ...

  3. 解决php -v查看到版本与phpinfo()版本不一致问题

    安装p7后发现phpinfo的版本是7.2.12,而php -v查看的却是5.4.16 应该是php.ini的配置文件有问题. 查看文件,有两个 查看cli执行的文件是哪一个? 再查看phpinfo用 ...

  4. js重点--匿名函数

    推荐博客:https://www.cnblogs.com/pssp/p/5216668.html 函数是必须要有函数名的,不然没有办法找到它,使用它. 如果没有名字必须要有一个依附体,如:将这个匿名函 ...

  5. 重装系统windows10/8/7,绝对纯净版永久激活的详细步骤和固态硬盘找不到分区的原因

    简介:重装系统有两种: 一种是在线重装,可实现电脑双系统或多系统,也可单系统(重装在另外一个盘,再去格式化系统盘),这种方式比较麻烦,前提电脑能开机使用,但是一般能启动使用也没人去重装系统,但是不需要 ...

  6. Java基础--面向对象编程4(多态)

    1.多态的概念 多态是指程序中的同一引用类型,使用不同的实例而执行结果不同的. 同一个类型:一般指父类 不同的实例:不同的子类实例 执行结果不同:针对同一方法执行的结果不同 package cn.sx ...

  7. Vim-latex 插件 的安装

    ref:https://www.jianshu.com/p/ddd825064062 Vim-latex 插件 1. 安装 Vim-latex 插件是一个强大的Latex插件, 它的安装方法是: 将下 ...

  8. OAuth2

    OAuth2: 适合To C的应用场景, 比如我们开发一个app, 可以借用微信/微博用户认证开放接口, 达到免注册登陆, 企业内部系统没有必要引入. OAuth2的步骤较多, 角色也较多, 涉及到a ...

  9. SQL数字型注入代码审计

    数字型注入 SQL注入攻击,简称注入攻击,是发生于应用程序与数据库层的安全漏洞. 简而言之,是在输入的字符串之中注入sql指定,在设计不良的程序当中忽略了检查,那么这些注入进去的指令就会被数据库服务器 ...

  10. 一些C++的语法

    一.类的析构函数 类的析构函数是类的一种特殊的成员函数,它会在每次删除所创建的对象时执行. 析构函数的名称与类的名称是完全相同的,只是在前面加了个波浪号(~)作为前缀,它不会返回任何值,也不能带有任何 ...