10.使用flask实现mock server

乙醇 创建于 大约 1 年 之前

最后更新时间 2018-11-26

flask

flask是python实现的简单的web框架,与django互补。

flask教程

如何理解flask

  • 路由 -> /request/uri

  • handler -> 路由进来之后处理request并返回response的逻辑

最简单的例子

from flask import Flask
app = Flask(__name__)

@app.route("/") # 路由
def hello(): # handler
    return "Hello World!"

实现mocked smile task api

获取所有的任务

GET /api/tasks # get all tasks

查看一个任务的详情

GET /api/tastks/:task_id # get a task with task_id

完成一个任务

PUT /api/tastks/:task_id # complete a task

代码


from flask import Flask, jsonify, g
import copy
app = Flask(__name__)

@app.before_request
def set_up_data():
    g.data = [
        {'id': 1, 'title': 'task 1', 'desc': 'this is task 1'},
        {'id': 2, 'title': 'task 2', 'desc': 'this is task 2'},
        {'id': 3, 'title': 'task 3', 'desc': 'this is task 3'},
        {'id': 4, 'title': 'task 4', 'desc': 'this is task 4'},
        {'id': 5, 'title': 'task 5', 'desc': 'this is task 5'}
    ]

    g.task_does_not_exist = {"msg": "task does not exist"}

@app.route('/api/tasks')
def get_all_tasks():
    return jsonify(g.data)

@app.route('/api/tasks/<int:task_id>')
def get_task(task_id):
    if task_id > 0 and task_id <= len(g.data):
        return jsonify(g.data[task_id])
    else:
        return jsonify(g.task_does_not_exist)

@app.route('/api/tasks/<int:task_id>', methods=['PUT'])
def complete_task(task_id):
    if task_id > 0 and task_id <= len(g.data):
        tmp = copy.deepcopy(g.data[task_id])
        tmp['done'] = True
        return jsonify(tmp)
    else:
        return jsonify(g.task_does_not_exist)

运行

set FLASK_APP=smile_task_mock_server.py

flask run
* Serving Flask app "smile_task_mock_server"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

浏览器打开localhost:5000就好了

我要留言

  • 查看一个任务详情,想查看第一个的怎么查看,这样出来的显示的是第二个任务http://127.0.0.1:5000/api/tasks/1

    简单 创建于 2019-08-19 18:50:03

  • http://127.0.0.1:5000/api/tasks/5 发生 500 错误 {code} [2019-06-10 07:08:41,282] ERROR in app: Exception on /api/tasks/5 [GET] Traceback (most recent call last): File "c:\python27\lib\site-packages\flask\app.py", line 2311, in wsgi_app response = self.full_dispatch_request() File "c:\python27\lib\site-packages\flask\app.py", line 1834, in full_dispatch _request rv = self.handle_user_exception(e) File "c:\python27\lib\site-packages\flask\app.py", line 1737, in handle_user_e xception reraise(exc_type, exc_value, tb) File "c:\python27\lib\site-packages\flask\app.py", line 1832, in full_dispatch _request rv = self.dispatch_request() File "c:\python27\lib\site-packages\flask\app.py", line 1818, in dispatch_requ est return self.view_functions[rule.endpoint](**req.view_args) File "D:\pcode\mockserver.py", line 24, in get_task return jsonify(g.data[task_id]) IndexError: list index out of range 127.0.0.1 - - [10/Jun/2019 07:08:41] "GET /api/tasks/5 HTTP/1.1" 500 - {/code}

    charm 创建于 2019-06-10 07:13:40