环境

python2.7.18 64bit
windows系统

Flask 是 python 中非常流行的一个 web 框架

安装 pip install flask

参考: https://zhuanlan.zhihu.com/p/137655320

第一个案例

first.py

  1. #!/usr/bin/python
  2. # coding=utf-8
  3. # 导入包
  4. from flask import Flask
  5. from flask.app import Response
  6. # 创建 Flask 程序实例
  7. app = Flask(__name__)
  8. # 接口
  9. @app.route('/')
  10. def index():
  11. return {
  12. "msg": "success",
  13. "data": "welcome to use flask."
  14. }
  15. @app.route('/user/<u_id>')
  16. def user_info(u_id):
  17. return {
  18. "msg": "success",
  19. "data": {
  20. "id": u_id,
  21. "username": 'yuz',
  22. "age": 18
  23. }
  24. }
  25. @app.route('/bus/<station>')
  26. def bus_info(station):
  27. import bus
  28. info = bus.get_bus_info(station)
  29. return {
  30. "msg": "success",
  31. "data": info
  32. }
  33. @app.route('/report/<file_name>')
  34. def get_report(file_name):
  35. """根据文件名获取测试报告。"""
  36. import pathlib
  37. file_path = pathlib.Path(__file__).parent / 'output' / file_name
  38. f = open(file_path, encoding='utf-8')
  39. report = f.read()
  40. f.close()
  41. return Response(report)
  42. @app.route('/reports')
  43. def discover_reports():
  44. """查找所有的测试报告"""
  45. import pathlib
  46. report_dir = pathlib.Path(__file__).parent / 'output'
  47. reports = [f.name for f in report_dir.iterdir() if f.suffix == '.html']
  48. return reports
  49. # 启动服务,默认在端口 5000 上,可访问 http://localhost:5000
  50. app.run()

bus.py

  1. # coding=utf-8
  2. import random
  3. def get_bus_info(station):
  4. '''
  5. python中的f是format函数的缩写,用于格式化输出。
  6. format函数常见的用法是str.format(),其基本语法是通过{}和:来代替以前的%。
  7. '''
  8. print("-----"*20)
  9. info = []
  10. for random_bus in range(10):
  11. # bus_name = f"W{random.randint(1, 100)}"
  12. bus_name = "w{}".format(random.randint(1, 100))
  13. bus_arrival_time = random.randint(1, 30)
  14. # bus_info = f"{bus_name} 还有 {bus_arrival_time} 分钟到达 {station}"
  15. bus_info = "{bus_name} 还有 {bus_arrival_time} 分钟到达 {station}".format(bus_name=bus_name, station=station, bus_arrival_time = bus_arrival_time)
  16. info.append({bus_name: bus_info})
  17. return info
  18. if __name__ == "__main__":
  19. print(get_bus_info("xiaohui"))

demo_test.py (存在问题,需要看一下 pytest 的用法)

  1. #!/usr/bin/python
  2. # coding=utf-8
  3. import pytest
  4. from datetime import datetime
  5. def test_add():
  6. assert 1 == 2
  7. def gen_report_name():
  8. prefix = r'report-result-'
  9. ts = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
  10. return prefix + ts + '.html'
  11. if __name__ == '__main__':
  12. report_name = gen_report_name()
  13. # pytest.main([f'--html=output/{report_name}'])
  14. pytest.main(['--c=output/{report_name}'.format(report_name=report_name)])