#coding:utf-8
from flask import Flask,jsonify,abort,make_response
from flask import request
#初始化app
app = Flask(__name__)
#用户名和密码
users = [
{
'id':1,
'username':"huahua",
'password':123456
},
{
'id':2,
'username':"sunliqin",
'password':5426241
}
]
'''
get 方法的使用
'''
#获取所有用户
@app.route('/api/users',methods=['GET'])
def get_users():
return jsonify({'users':users})
#获取某一个用户
@app.route('/api/users/',methods=['GET'])
def get_oneuser(user_id):
user = filter(lambda a:a['id']==user_id,users)
if len(user) == 0:
abort(404)
return jsonify({'user':user[0]})
#发生错误的时候
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error':'not be found'}), 404)
'''
post方法的使用,意思是创建一个资源 注意in的用法可以直接在集合set list dict truple 中进行判断
我们可以采用两种方式来提交数据,一种是表单提交使用request.form,另一种方法是使用json格式数据来提交使用request.json形式
'''
# @app.route('/api/users',methods=['POST'])
# def create_user():
# if not request.json or not 'username' in request.json :
# abort(400)
#
# user = {
# 'id':users[-1]['id'] + 1,
# 'username':request.json['username'],
# 'password':request.json['password']
# }
# print type(request.json)
# users.append(user)
# return jsonify({'user':user}), 201
@app.route('/api/users',methods=['POST'])
def create_user():
if not request.form or not 'username' in request.form :
abort(400)
user = {
'id':users[-1]['id'] + 1,
'username':request.form['username'],
'password':request.form['password']
}
print type(request.form)
users.append(user)
return jsonify({'user':user}), 201
'''
put更新用户数据
'''
@app.route('/api/users/',methods=['PUT'])
def update_user(user_id):
user = filter(lambda a:a['id'] == user_id, users)
if len(user) == 0:
abort(404)
if not request.json:
abort(400)
user[0]['username'] = request.json.get('username',user[0]['username'])
user[0]['password'] = request.json.get('password',user[0]['password'])
return jsonify({'user':user[0]})
'''
delete 删除用户数据
'''
@app.route('/api/users/',methods=['DELETE'])
def delete_user(user_id):
user = filter(lambda a: a['id'] == user_id, users)
if len(user) == 0:
abort(404)
if not request.json:
abort(400)
users.remove(user[0])
return jsonify({'result':True})
if __name__ == '__main__':
app.run(debug=True)