Flask 搭建服务和使用 POST 和 GET 请求服务示例(简单但实用)

Python 的 Flask 其实有点类似于 Ruby 的 Sinatra 。我另外一篇博客也写了用 Sinatra 搭建服务和使用请求服务示例:https://blog.csdn.net/TomorrowAndTuture/article/details/110499973。都是用的最简单的例子,并不复杂。 

服务端:

# server.py

from flask import Flask, request
app = 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.py

import 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 success
post request success

 

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值