requests网络库使用
发送请求
requests.get()
requests.post()
requests.put()
requests.delete()
requests.head()
requests.options()
In [1]: import requests
In [2]: r = requests.get('https://github.com/timeline.json')
In [3]: r = requests.put("http://httpbin.org/put")
In [4]: r = requests.delete("http://httpbin.org/delete")
In [5]: r = requests.head("http://httpbin.org/get")
In [6]: r = requests.options("http://httpbin.org/get")
传递URL的值
你也许经常想为 URL 的查询字符串(query string)传递某种数据。如果你是手工构建 URL,那么数据会以键/值对的形式置于 URL 中,跟在一个问号的后面。例如, httpbin.org/get?key=val
。 Requests 允许你使用 params
关键字参数,以一个字符串字典来提供这些参数。举例来说,如果你想传递 key1=value1
和 key2=value2
到 httpbin.org/get
,那么你可以使用如下代码:
In [12]: payload = {'key1':'value1','key2':'value2'}
In [13]: r = requests.get('http://httpbin.org/get',params=payload)
In [14]: print(r.url)
http://httpbin.org/get?key2=value2&key1=value1
响应内容
In [40]: import requests
In [41]: r = requests.get('https://github.com/timeline.json')
In [42]: r.text
Out[42]: u'{"message":"Hello there, wayfaring stranger. If you\u2019re reading this then you probably didn\u2019t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.","documentation_url":"https://developer.github.com/v3/activity/events/#list-public-events"}'
设置编码格式
>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'
如果你改变了编码,每当你访问r.text
,Request 都将会使用 r.encoding
的新值。你可能希望在使用特殊逻辑计算出文本的编码的情况下来修改编码。比如 HTTP 和 XML 自身可以指定编码。这样的话,你应该使用 r.content
来找到编码,然后设置 r.encoding
为相应的编码。这样就能使用正确的编码解析 r.text
了。
二进制响应内容
你也能以字节的方式访问请求响应体,对于非文本请求:
>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...
Requests 会自动为你解码 gzip
和 deflate
传输编码的响应数据。
例如,以请求返回的二进制数据创建一张图片,你可以使用如下代码:
>>> from PIL import Image
>>> from io import BytesIO
>>> i = Image.open(BytesIO(r.content))
JSON响应内容
Requests 中也有一个内置的 JSON 解码器,助你处理 JSON 数据
In [62]: r.json()
Out[62]:
{u'documentation_url': u'https://developer.github.com/v3/activity/events/#list-public-events',
u'message': u'Hello there, wayfaring stranger. If you\u2019re reading this then you probably didn\u2019t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.'}
原始响应内容
想获取的原始套接字响应,那么你可以访问r.raw
。 如果你确实想这么干,那请你确保在初始请求中设置了 stream=True
。具体你可以这么做:
>>> r = requests.get('https://github.com/timeline.json', stream=True)
>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
但一般情况下,你应该以下面的模式将文本流保存到文件:
with open(filename, 'wb') as fd:
for chunk in r.iter_content(chunk_size):
fd.write(chunk)
使用 Response.iter_content
将会处理大量你直接使用 Response.raw
不得不处理的。 当流下载时,上面是优先推荐的获取内容方式。 Note that chunk_size can be freely adjusted to a number that may better fit your use cases.
定制请求头
如果你想为请求添加 HTTP 头部,只要简单地传递一个dict
给 headers
参数就可以了。
例如,在前一个示例中我们没有指定 content-type:
>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> r = requests.get(url, headers=headers)
注意
: 所有的 header 值必须是 string
、bytestring
或者 unicode
。尽管传递 unicode header 也是允许的,但不建议这样做
POST请求
发送POST请求,data参数以字典的形式传递
发送送一些编码为表单形式的数据,data
参数以字典的形式传入
In [1]: import requests
In [2]: mydata = {"wd":"linux",'name':'redhat'}
In [3]: r = requests.post('http://httpbin.org/post',data=mydat
...: a)
In [5]: print r.text
{
.......
"form": {
"name": "redhat",
"wd": "linux"
},
......
}
发送post请求,data参数通过元组形式传递
data
参数传入一个元组列表。在表单中多个元素使用同一 key
In [1]: import requests
In [2]: payload = (('key1','value1'),('key2','value2'))
In [3]: r = requests.post('http://httpbin.org/post',data=payload)
In [4]: print r.text
{
.......
"form": {
"key1": "value1",
"key2": "value2"
},
......
}
发送post请求,data参数通过string形式来传递
In [1]: import json
In [2]: import requests
In [4]: mydata = {'wd':'linux','name':'redhat'}
In [7]: r = requests.post('http://httpbin.org/post',data=json.
...: dumps(mydata))
In [8]: print r.text
{
"args": {},
"data": "{\"wd\": \"linux\", \"name\": \"redhat\"}",
"files": {},
"form": {}, #提交的表单是空
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "33",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.6.0 CPython/2.7.5 Linux/3.10.0-327.el7.x86_64"
},
"json": { # json代码中是传输的值
"name": "redhat",
"wd": "linux"
},
"origin": "122.112.217.181",
"url": "http://httpbin.org/post"
}
发送post请求,json参数通过dict形式来传递
In [5]: import requests
In [6]: payload = {'key1':'value1','key2':'value2'}
In [7]: r = requests.post('http://httpbin.org/post',json=payload)
In [8]: print r.text
{
"args": {},
"data": "{\"key2\": \"value2\", \"key1\": \"value1\"}",
"files": {},
"form": {},
.......
"json": {
"key1": "value1",
"key2": "value2"
},
"origin": "122.112.217.181",
"url": "http://httpbin.org/post"
}
POST一个多部分编码(Multipart-Encoded)的文件
Requests 使得上传多部分编码文件变得很简单:
>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}
你可以显式地设置文件名,文件类型和请求头:
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}
如果你想,你也可以发送作为文件来接收的字符串:
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "some,data,to,send\\nanother,row,to,send\\n"
},
...
}
如果你发送一个非常大的文件作为 multipart/form-data
请求,你可能希望将请求做成数据流。默认下 requests 不支持, 但有个第三方包requests-toolbelt
是支持的。你可以阅读 toolbelt 文档 来了解使用方法。
在一个请求中发送多文件参考 高级用法 一节。
警告
我们强烈建议你用二进制模式(binary mode)
打开文件。这是因为 Requests 可能会试图为你提供 Content-Length header
,在它这样做的时候,这个值会被设为文件的字节数(bytes)
。如果用文本模式(text mode)
打开文件,就可能会发生错误。
响应状态码
In [9]: r.status_code
Out[9]: 200
如果发送了一个错误请求(一个 4XX 客户端错误,或者 5XX 服务器错误响应),我们可以通过Response.raise_for_status()
来抛出异常:
>>> bad_r = requests.get('http://httpbin.org/status/404')
>>> bad_r.status_code
404
>>> bad_r.raise_for_status()
Traceback (most recent call last):
File "requests/models.py", line 832, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error
但是,由于我们的例子中 r 的 status_code
是 200 ,当我们调用 raise_for_status()
时,得到的是:
>>> r.raise_for_status()
None
响应头
In [15]: r.headers
Out[15]: {'content-length': '537', 'via': '1.1 vegur', 'x-powered-by': 'Flask', 'server': 'meinheld/0.6.1', 'connection': 'keep-alive', 'x-processed-time': '0.000684022903442', 'access-control-allow-credentials': 'true', 'date': 'Mon, 21 Aug 2017 14:14:20 GMT', 'access-control-allow-origin': '*', 'content-type': 'application/json'}
socket原生网络库使用
server1:原始socket API
#!/usr/bin/python
#coding=utf-8
import socket
s = socket.socket()
host = '127.0.0.1' #监听的地址。如果让所有人访问设置为0.0.0.0
port = 8080 #监听的端口
s.bind((host,port))
s.listen(20)
while True:
c,addr = s.accept()
print '连接地址:',addr
c.send("欢迎访问....")
c.close()
client1:
#!/usr/bin/python
#coding=utf-8
import socket
host = '122.112.217.181' #服务器的IP地址
port = 8080 #服务器监听的端口
s = socket.socket()
s.connect((host,port))
print s.recv(1024)
s.close()