本文共 1442 字,大约阅读时间需要 4 分钟。
Python 的 Flask 其实有点类似于 Ruby 的 Sinatra 。我另外一篇博客也写了用 Sinatra 搭建服务和使用请求服务示例:。都是用的最简单的例子,并不复杂。
服务端:
# server.pyfrom flask import Flask, requestapp = Flask(__name__) @app.route('/get-test', methods=['GET'])def testget(): if request.method == 'GET': return "get request success" @app.route('/post-test', methods=['POST'])def testpost(): if request.method == 'POST': temp = request.json.get('data') print(temp) return "post request success" if __name__ == '__main__': app.run(host="localhost", port=9979, threaded=True)
客户端:
# client.pyimport requests if __name__ == '__main__': # get 请求 url = "http://localhost:9979/get-test" r = requests.get(url) print(r.text) # post 请求 url = "http://localhost:9979/post-test" data = { "aaa": 1, "bbb": 2, } r = requests.post(url, json={"data": data}) print(r.text)
服务端运行输出:
[root@master python3_learning]# python3 server.py * Serving Flask app "server" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on http://localhost:9979/ (Press CTRL+C to quit)127.0.0.1 - - [02/Dec/2020 22:38:01] "GET /get-test HTTP/1.1" 200 -{'aaa': 1, 'bbb': 2}127.0.0.1 - - [02/Dec/2020 22:38:01] "POST /post-test HTTP/1.1" 200 -
客户端运行输出:
[root@master python3_learning]# python3 client.py get request successpost request success
转载地址:http://zdjqi.baihongyu.com/