前言
flask是什么?众所周知 java有 spring 全家桶和sparkjava,Python有Django和flask,Django属于大而全的框架,flask是一个轻量级的web服务框架,结构简单但功能强大,像一把尼泊尔军刀一样,非常适合我们在平时工作中开发一些简单的工具,如简单的自动化测试平台,今天一起来了解下flask在web服务中的应用。
本地搭建flask服务
设置路由
from flask import Flask
app = Flask(__name__)
@app.route("/login")
def flask_demo():
return "login successful"
if __name__ == '__main__':
app.run(debug=True)
控制台打印如下
* Serving Flask app 'flask_fx' (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: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 536-367-075
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [04/Dec/2021 17:01:33] "GET /testcase HTTP/1.1" 404 -
127.0.0.1 - - [04/Dec/2021 17:01:34] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [04/Dec/2021 17:01:52] "GET /LOGIN HTTP/1.1" 404 -
127.0.0.1 - - [04/Dec/2021 17:02:02] "GET /login HTTP/1.1" 200 -
* Detected change in 'E:\\code_software\\Python Charm\\Python Project\\flask_demo2\\flask_fx.py', reloading
* Restarting with stat
* Debugger is active!
* Debugger PIN: 536-367-075
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Detected change in 'E:\\code_software\\Python Charm\\Python Project\\flask_demo2\\flask_fx.py', reloading
* Restarting with stat
* Debugger is active!
* Debugger PIN: 536-367-075
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
其中 http://127.0.0.1:5000/ 为flask服务地址 浏览器访问flask服务,如下图
设置请求方法和参数
from flask import Flask, request
app = Flask(__name__)
@app.route("/login", methods=["get"])
def flask_demo():
user = request.args.get("user")
return f"login successful user={user}"
@app.route("/home", methods=["post"])
def flask_demo2():
user = request.json.get("user")
return {f"message": "login successful", "user": f"{user}"}
if __name__ == '__main__':
app.run(debug=True)
使用浏览器并带参数访问flask_demo接口 访问flask_demo2
def test_flask_fx():
url = "http://127.0.0.1:5000/home"
data = {
"user": "leo",
}
re = requests.post(url=url, json=data)
print(re.text)
assert re.status_code == 200
控制台信息:
PASSED [100%]{
"message": "login successful",
"user": "leo"
}
知识点一:methods 可以用来指定请求方法,但必须是列表 知识点二:requests.args来接收get请求的params参数,requests.form用来接收post的data参数,requests .json用来接收post请求体中的json数据
如何搭建一个restful接口的服务
非restful接口
@app.route("/testcase", methods=["get", "post", "put", "delete"])
def test_case():
if request.method == "get":
pass
elif request.method == "post":
pass
elif request.method == "put":
pass
elif request.method == "delete":
pass
if __name__ == '__main__':
app.run()
按照上面的剧情发展我们写的接口大概就会成为这样,但是如果通过判断method来进行业务逻辑的编写,会使得代码很耦合,违背了高内聚,低耦合的设计理念。那有没有一种方法可以直接编写get、post、delete、put接口呢,既符合接口设计规范,又不互相耦合,这里我们引入了flask的第三方库 flask_restful
安装flask_restful
pip install flask_restful
from flask_restful import Api, Resource
from flask import Flask
from logger_until import logger
app = Flask(__name__)
api = Api(app)
class TestCaseServer(Resource):
def get(self):
logger.info(" get method ")
return {"errcode": 0000, "message": " get method "}
def post(self):
logger.info(" post method ")
return {"errcode": 0000, "message": " post method "}
def delete(self):
logger.info(" delete method ")
return {"errcode": 0000, "message": " delete method "}
def put(self):
logger.info(" put method ")
return {"errcode": 0000, "message": " put method "}
api.add_resource(TestCaseServer, "/testcase")
if __name__ == '__main__':
app.run(debug=True)
上面就是按照restful规范定义的后台接口
下面为测试代码
import requests
class TestCase:
def setup_class(self):
self.url = "http://127.0.0.1:5000/testcase"
def teardown_class(self):
pass
def test_get(self):
re = requests.get(url=self.url)
print(re.text)
def test_post(self):
re = requests.post(url=self.url)
assert re.status_code == 200
def test_put(self):
re = requests.put(url=self.url)
assert re.status_code == 200
def test_delete(self):
re = requests.delete(url=self.url)
assert re.status_code == 200
接口框架已搭建成功,再需要根据业务规则与数据库或其他业务模块进行交互
下一节链接: flask与数据mysql进行交互.
|