本教程展示了如何在Python中发送GET和POST请求。在示例中,我们使用了request
、urllib3
和socket
模块。我们还展示了如何在Flask中处理GET或POST请求。
HTTP
超文本传输协议(HTTP)是分布式协作超媒体信息系统的应用协议。HTTP是万维网数据通信的基础。
在示例中,我们使用免费提供的HTTP请求和响应服务httpbin.org
和一个微型HTML页面webcode.me
用于测试。
HTTP获取
HTTPGET方法请求指定资源的表示。
GET请求:
- 应该只用于请求资源
- 参数显示在URL中
- 可以缓存
- 保留在浏览器历史中
- 可以添加书签
- 在处理敏感数据时绝不能使用
- 有长度限制
HTTP发送
HTTPPOST方法向服务器发送数据。它通常在上传文件或提交完整的网络表单时使用。
POST请求:
- 应该用于创建资源
- 参数不显示在URL中
- 从不缓存
- 不保留在浏览器中history
- 不能加书签
- 处理敏感数据时可以使用
- 没有长度限制
Pythonurllib3
urllib3模块是一个功能强大、对Python友好的HTTP客户端。
$ pip install urllib3
我们使用pip安装urllib3模块。
Python请求
Requests是一个简单而优雅的PythonHTTP库。它提供了通过HTTP访问Web资源的方法。它是根据ApacheLicense2.0发布的。它是最流行的Python包之一。
$ pip install requests
我们安装了request
模块。
Python烧瓶
Flask是最流行的Python微型Web框架。大多数功能都可以作为扩展使用,包括验证、表单处理、对象关系映射器或身份验证。Flask基于WerkzeugWSGItoolkit和Jinja2模板引擎。
$ pip install Flask
我们安装Flask。
使用urllib3的PythonGET请求
GET请求是使用request
方法创建的,该方法接收'GET'
值作为其第一个参数。
#!/usr/bin/python import urllib3 http = urllib3.PoolManager() url = 'http://webcode.me' resp = http.request('GET', url) print(resp.data.decode('utf-8'))
GET请求被发送到webcode.me。
$ ./get_req.py <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My html page</title> </head> <body> <p> Today is a beautiful day. We go swimming and fishing. </p> <p> Hello there. How are you? </p> </body> </html>
使用urllib3的PythonPOST请求
POST请求是使用request
方法创建的,该方法接收'POST'
值作为其第一个参数。
#!/usr/bin/python import urllib3 import certifi http = urllib3.PoolManager(ca_certs=certifi.where()) url = 'https://httpbin.org/post' req = http.request('POST', url, fields={'name': 'John Doe', 'occupation': 'gardener'}) print(req.data.decode('utf-8'))
POST请求被发送到httpbin.org/post。
$ ./post_req.py { "args": {}, "data": "", "files": {}, "form": { "name": "John Doe", "occupation": "gardener" }, "headers": { "Accept-Encoding": "identity", "Content-Length": "230", "Content-Type": "multipart/form-data; boundary=510415c9b680823ee5512359fa1b3d22", "Host": "httpbin.org", "X-Amzn-Trace-Id": "Root=1-5f159c14-fc386023685d681205723862" }, ... "url": "https://httpbin.org/post" }
带有请求的PythonGET请求
使用get
方法生成GET请求。
#!/usr/bin/python import requests as req resp = req.get("http://webcode.me") print(resp.text)
GET请求被发送到webcode.me。
带有请求的PythonPOST请求
使用post
方法生成POST请求。
#!/usr/bin/python import requests as req data = {'name': 'Peter'} resp = req.post("https://httpbin.org/post", data) print(resp.text)
POST请求被发送到httpbin.org/post。
Python在Flask中处理GET请求
以下示例展示了如何在Flask应用程序中处理GET请求。
#!/usr/bin/python from flask import Flask, request app = Flask(__name__) @app.route('/') def index(): return 'Home page' @app.route('/greet', methods=['GET']) def greet(): name = request.args.get('name', 'Guest') msg = f'Hello {name}' return msg, 200, {'Content-Type': 'text/plain; charset=utf-8'}
应用程序创建消息并将其发送到客户端。它使用名称查询参数中的值。
@app.route('/greet', methods=['GET']) def greet(): ...
greet
函数映射到/greet
路径和GET类型请求。
$ export FLASK_APP=app.py $ flask run
我们运行应用程序。
$ curl -i localhost:5000/greet?name=Lucia HTTP/1.0 200 OK Content-Type: text/plain; charset=utf-8 Content-Length: 11 Server: Werkzeug/1.0.0 Python/3.8.3 Date: Mon, 20 Jul 2020 13:37:38 GMT Hello Lucia
我们使用curl
工具向应用程序创建GET请求。使用-i
选项,我们还包括响应标头。
Python在Flask中处理POST请求
以下示例展示了如何在Flask中处理POST请求。
#!/usr/bin/python from flask import Flask, make_response app = Flask(__name__) @app.route('/') def hello(): return 'Home page' @app.route('/users/<name>', methods=['POST']) def create_user(name): msg = f'user {name} created' return make_response(msg, 201)
要处理POST请求,我们在methods
参数中指定方法名称。
$ export FLASK_APP=app.py $ flask run
我们运行应用程序。
$ curl -X POST localhost:5000/users/Peter/ user Peter created
一个POST请求被创建。
列出所有Python教程。