博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Flask 搭建服务和使用 POST 和 GET 请求服务示例(简单但实用)
阅读量:4227 次
发布时间:2019-05-26

本文共 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/

你可能感兴趣的文章
Python基础(三)
查看>>
Python入门NLP(二)
查看>>
四行Python代码,你也能从图片上识别文字!
查看>>
内网映射外网工具-ngrok
查看>>
Python带你朗读网页
查看>>
关于python,这些知识点你学会了吗?
查看>>
利用selenium爬取《西虹市首富影评》
查看>>
Python验证码识别
查看>>
机器学习、NLP和Python教程分享
查看>>
AWS Serverless培训分享
查看>>
python生成二维码
查看>>
在ubuntu上搭建文件服务器
查看>>
ServiceFabric: 在Windows上创建容器应用并部署到ServiceFabric中
查看>>
paramiko——一个专门为Linux设计的模块
查看>>
一个有趣的python项目---一个好玩的网站
查看>>
git常用命令总结
查看>>
Protobuf了解一下?
查看>>
超越Selenium的存在---Pyppeteer
查看>>
复仇者联盟4:终局之战剧透
查看>>
Msgpack有没有兴趣了解一下?
查看>>