环境
python2.7.18 64bit
windows系统
Flask 是 python 中非常流行的一个 web 框架
安装 pip install flask
参考: https://zhuanlan.zhihu.com/p/137655320
第一个案例
first.py
#!/usr/bin/python
# coding=utf-8
# 导入包
from flask import Flask
from flask.app import Response
# 创建 Flask 程序实例
app = Flask(__name__)
# 接口
@app.route('/')
def index():
return {
"msg": "success",
"data": "welcome to use flask."
}
@app.route('/user/<u_id>')
def user_info(u_id):
return {
"msg": "success",
"data": {
"id": u_id,
"username": 'yuz',
"age": 18
}
}
@app.route('/bus/<station>')
def bus_info(station):
import bus
info = bus.get_bus_info(station)
return {
"msg": "success",
"data": info
}
@app.route('/report/<file_name>')
def get_report(file_name):
"""根据文件名获取测试报告。"""
import pathlib
file_path = pathlib.Path(__file__).parent / 'output' / file_name
f = open(file_path, encoding='utf-8')
report = f.read()
f.close()
return Response(report)
@app.route('/reports')
def discover_reports():
"""查找所有的测试报告"""
import pathlib
report_dir = pathlib.Path(__file__).parent / 'output'
reports = [f.name for f in report_dir.iterdir() if f.suffix == '.html']
return reports
# 启动服务,默认在端口 5000 上,可访问 http://localhost:5000
app.run()
bus.py
# coding=utf-8
import random
def get_bus_info(station):
'''
python中的f是format函数的缩写,用于格式化输出。
format函数常见的用法是str.format(),其基本语法是通过{}和:来代替以前的%。
'''
print("-----"*20)
info = []
for random_bus in range(10):
# bus_name = f"W{random.randint(1, 100)}"
bus_name = "w{}".format(random.randint(1, 100))
bus_arrival_time = random.randint(1, 30)
# bus_info = f"{bus_name} 还有 {bus_arrival_time} 分钟到达 {station}"
bus_info = "{bus_name} 还有 {bus_arrival_time} 分钟到达 {station}".format(bus_name=bus_name, station=station, bus_arrival_time = bus_arrival_time)
info.append({bus_name: bus_info})
return info
if __name__ == "__main__":
print(get_bus_info("xiaohui"))
demo_test.py (存在问题,需要看一下 pytest 的用法)
#!/usr/bin/python
# coding=utf-8
import pytest
from datetime import datetime
def test_add():
assert 1 == 2
def gen_report_name():
prefix = r'report-result-'
ts = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
return prefix + ts + '.html'
if __name__ == '__main__':
report_name = gen_report_name()
# pytest.main([f'--html=output/{report_name}'])
pytest.main(['--c=output/{report_name}'.format(report_name=report_name)])