flask是什么?众所周知 java有 spring 全家桶和sparkjava,Python有Django和flask,Django属于大而全的框架,flask是一个轻量级的web服务框架,结构简单但功能强大,像一把尼泊尔军刀一样,非常适合我们在平时工作中开发一些简单的工具,如简单的自动化测试平台,今天一起来了解下flask在web服务中的应用。
# 导包flask
from flask import Flask
# 实例化一个Flask的对象
app = Flask(__name__)
# 调用app.route来指定接口的路由,/表示根目录
@app.route("/login")
def flask_demo(): # flask_demo为你的接口名称
return "login successful" # 接口的返回值
if __name__ == '__main__':
app.run(debug=True) # 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服务,如下图
# 导包flask
from flask import Flask, request
# 实例化一个Flask的对象
app = Flask(__name__)
# 调用app.route来指定接口的路由,/表示根目录
# methods指定访问接口的请求的方法,必须传入列表,否则报错
@app.route("/login", methods=["get"])
def flask_demo(): # flask_demo为你的接口名称
user = request.args.get("user")
return f"login successful user={user}" # 接口的返回值
@app.route("/home", methods=["post"])
def flask_demo2(): # flask_demo为你的接口名称
user = request.json.get("user") # 接受post请求的json数据
return {f"message": "login successful", "user": f"{user}"} # 接口的返回值
if __name__ == '__main__':
app.run(debug=True) # 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接口
@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 # 导入flask_restful的两个重要的方法
from flask import Flask
from logger_until import logger
app = Flask(__name__) # 实例化Flask对象
api = Api(app) # 将Flask的对象实例塞进Api中,将flask和flask_restful进行绑定
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 "}
# 将继承了resource的接口定义类添加到api中,并定义接口的路由地址
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)
# assert re.status_code == 200
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进行交互.