Web-HTTP 请求(requests)详解

fansichao 2021-10-23 16:16:35
Categories: Tags:

HTTP 请求 含义&区别

python 用 GET,POST,PUT,DELETE 方式向 HTTP 提交数据

浅谈 HTTP 中 Get 与 Post 的区别-表格对比
GET 和 POST 究竟有什么区别

Header 详解

Requests 模块使用

完整样例封装代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

import logging

import requests

def http_request(url, msg="", method="GET", is_logging=False, **kwargs):
u""" 执行需要的 HTTP 请求命令

功能:
整合了所有 HTTP 参数请求

:param str url: 链接
:param str msg: 信息
:param str method: 请求方式

get - params=data
post - data=data headers=headers
"""

# TODO GET params 不支持循环嵌套的数据. 例如{'properties': {'data_mark': '20191119064014'}}

try:
method_lis = ['GET', 'POST', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE', 'CONNECT']
method = method if method.upper() in method_lis else method_lis[0]
r = getattr(requests, method.lower(), None)(url, **kwargs)
try:
logging.info('>> %s \n[%s][URL]: %s' % (msg, method, urlparse.unquote(r.url)))
ret = r.json()
except Exception as e:
if is_logging:
logging.error(traceback.print_exc())
logging.error(r.status_code)
logging.error(r.reason)
ret = ""
return ret
except Exception as e:
logging.error(traceback.print_exc())
logging.error(e)
return ""