使用flask实现mock server

358

实现mocked smile task api

获取所有的任务

GET /api/tasks

查看一个任务的详情

GET /api/tasks/:task_id

完成一个任务

PUT /api/tasks/:task_id

具体实现

from flask import Flask, jsonify, g
import copy

app = Flask(__name__)

@app.before_request
def set_up_data():
	#g:global,专门保存用户数据,在一次请求中,全局可以调用
	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():
	#使用jsonify返回json响应数据,Content-Type显示为application/json
	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-1])
	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-1])
		tmp['done'] = True
		return jsonify(tmp)
	else:
		return jsonify(g.task_does_not_exist)

运行结果:

image.png

image.png

image.png

练习 实现登录校验

如果用户名不存在,打印用户名不存在;如果用户名存在,匹配密码成功则登录成功,不成功打印密码有误。

from flask import Flask, g, request,jsonify

app = Flask(__name__)

@app.before_request
def set_up_data():
	g.data = [
		{'username': 'Ly', 'password':'123456'},
		{'username': 'Wkk', 'password':'5201314'},
		{'username': 'user01', 'password':'111111'},
		{'username': 'user02', 'password':'222222'},
	]

	g.username_not_exist = {"msg": "Username not exist, please check your input!"}

@app.route('/')
def hello_world():
	return 'index'

@app.route('/login/', methods=['GET', 'POST'])
def login():
	if request.method == 'GET':
		return 'hello'
	else:
		#args是用来提取url中的参数
		username = request.args.get('username')
		password = request.args.get('password')
		for i in range(len(g.data)):
			if username == g.data[i]['username']:
				if password == g.data[i]['password']:
					return "Login Success"
				else:
					return "Wrong Password!"
		return jsonify(g.username_not_exist)

if __name__ == '__main__':
    # 设置运行的ip和端口
	app.run(debug = True, host='127.0.0.1', port=8081)

运行结果: image.png

image.png

image.png

image.png