python + flask轻量级框架
Posted Teacher涛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python + flask轻量级框架相关的知识,希望对你有一定的参考价值。
from flask import Flask,jsonify,make_response,abort,Response,request
from flask_restful import Api,Resource,reqparse
from flask_httpauth import HTTPBasicAuth
app = Flask(__name__)
api = Api(app=app)
auth = HTTPBasicAuth()
#认证通过
@auth.get_password
def get_password(username):
if username == "Admin":
return "admin"
#认证不通过的错误信息
@auth.error_handler
def authrized():
return make_response(jsonify({‘msg‘:‘您好,请认证‘}),401)
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({"error":"请求页面不存在!"}),404)
@app.errorhandler(405)
def not_found(error):
return make_response(jsonify({"error":"请求方式不对!"}),405)
books = [
{‘ID‘:1,‘author‘:‘Teacher‘,‘name‘:‘Python‘,‘done‘:True},
{‘ID‘:2,‘author‘:‘Teacher‘,‘name‘:‘Selenium‘,‘done‘:True},
{‘ID‘:3,‘author‘:‘Teacher‘,‘name‘:‘Appium‘,‘done‘:False},
]
#查看全部书籍
@app.route(‘/v1/api/books‘,methods=[‘GET‘])
@auth.login_required
def get_books():
return jsonify({‘data‘:books})
#添加部分书籍
@app.route(‘/v1/api/books‘,methods=[‘POST‘])
@auth.login_required
def create_books():
if not Response.json:
abort (404)
else:
book = {
‘ID‘:books[-1][‘ID‘]+1,
‘author‘:request.json.get(‘author‘),
‘name‘:request.json.get(‘name‘),
‘done‘:False
}
books.append(book)
return jsonify({‘msg‘:‘添加书籍成功‘})
#根据ID查询对应书籍
@app.route(‘/v1/api/book/<int:book_id>‘,methods=[‘GET‘])
@auth.login_required
def get_book(book_id):
book = list(filter(lambda t:t[‘ID‘]==book_id,books))
if len(book) == 0:
abort (404)
else:
return jsonify({‘status‘:1001,‘msg‘:‘ok‘,‘data‘:book})
#根据ID删除对应书籍
@app.route(‘/v1/api/book/<int:book_id>‘,methods=[‘DELETE‘])
@auth.login_required
def delete_book(book_id):
book = list(filter(lambda t:t[‘ID‘]==book_id,books))
print(book)
if len(book)==0:
abort (404)
else:
books.remove(book[0])
return jsonify({‘status‘:1002,‘msg‘:‘删除书籍成功‘,‘data‘:book})
#根据ID更新对应书籍
@app.route(‘/v1/api/book/<int:book_id>‘,methods=[‘PUT‘])
@auth.login_required
def put_book(book_id):
book = list(filter(lambda t:t[‘ID‘]==book_id,books))
# print(book)
if len(book)==0:
abort (404)
elif not Response.json:
abort (404)
elif ‘author‘ not in request.json and ‘name‘ not in request.json:
abort (404)
elif ‘done‘ not in request.json and type(request.json[‘done‘] is not bool):
abort (404)
else:
book[-1][‘author‘] = request.json.get(‘author‘,book[-1][‘author‘])
book[-1][‘name‘] = request.json.get(‘name‘,book[-1][‘name‘])
book[-1][‘done‘] = request.json.get(‘done‘,book[-1][‘done‘])
return jsonify({‘status‘:1003,‘msg‘:‘更新书籍成功‘,‘data‘:book})
@app.route("/index")
@auth.login_required
def index():
return jsonify({"status":0,"msg":"ok","data":{"name":"tea","age":22}})
class LoginView(Resource):
# def get(self):
# parser = reqparse.RequestParser()
# return jsonify({‘status‘:0,‘msg‘:‘ok‘,‘data‘:parser.parse_args()})
def post(self):
parser = reqparse.RequestParser()
parser.add_argument(‘username‘,type=str,help=‘账号不能为空‘,required=True)
parser.add_argument(‘password‘,type=str,help=‘密码不能为空‘,required=True)
parser.add_argument(‘age‘,type=int,help=‘年龄必须是整型‘)
return jsonify({‘status‘:0,‘msg‘:‘ok‘,‘data‘:parser.parse_args()})
# 添加路由
api.add_resource(LoginView,‘/login‘,endpoint=‘login‘)
# @app.route("/login",methods=[‘GET‘])
# def login():
# parser = reqparse.RequestParser()
# parser.add_argument(‘username‘,type=str,help=‘账号不能为空‘,required=True)
# parser.add_argument(‘password‘,type=str,help=‘密码不能为空‘,required=True)
# return jsonify({‘status‘:0,‘msg‘:‘ok‘,‘data‘:parser.parse_args()})
if __name__ == "__main__":
app.run(debug=True)
from flask import Flask,jsonify,make_response,abort,Response,request
from flask_restful import Api,Resource,reqparse
from flask_httpauth import HTTPBasicAuth
app = Flask(__name__)
api = Api(app=app)
auth = HTTPBasicAuth()
#认证通过
@auth.get_password
def get_password(username):
if username == "Admin":
return "admin"
#认证不通过的错误信息
@auth.error_handler
def authrized():
return make_response(jsonify({‘msg‘:‘您好,请认证‘}),401)
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({"error":"请求页面不存在!"}),404)
@app.errorhandler(405)
def not_found(error):
return make_response(jsonify({"error":"请求方式不对!"}),405)
books = [
{‘ID‘:1,‘author‘:‘Teacher‘,‘name‘:‘Python‘,‘done‘:True},
{‘ID‘:2,‘author‘:‘Teacher‘,‘name‘:‘Selenium‘,‘done‘:True},
{‘ID‘:3,‘author‘:‘Teacher‘,‘name‘:‘Appium‘,‘done‘:False},
]
class Books(Resource):
#鉴权认证(登录)
decorators = [auth.login_required]
#查看全部书籍
def get(self):
return jsonify({‘data‘:books})
#添加部分书籍
def post(self):
if not Response.json:
abort (404)
else:
book = {
‘ID‘:books[-1][‘ID‘]+1,
‘author‘:request.json.get(‘author‘),
‘name‘:request.json.get(‘name‘),
‘done‘:False
}
books.append(book)
return jsonify({‘msg‘:‘添加书籍成功‘})
class Book(Resource):
#鉴权认证(登录)
decorators = [auth.login_required]
#根据ID查询对应书籍
def get(self,book_id):
book = list(filter(lambda t:t[‘ID‘]==book_id,books))
if len(book) == 0:
abort (404)
else:
return jsonify({‘status‘:1001,‘msg‘:‘ok‘,‘data‘:book})
#根据ID删除对应书籍
def delete(self,book_id):
book = list(filter(lambda t:t[‘ID‘]==book_id,books))
if len(book)==0:
abort (404)
else:
books.remove(book[0])
return jsonify({‘status‘:1002,‘msg‘:‘删除书籍成功‘,‘data‘:book})
#根据ID更新对应书籍
def put(self,book_id):
book = list(filter(lambda t:t[‘ID‘]==book_id,books))
if len(book)==0:
abort (404)
elif not Response.json:
abort (404)
elif ‘author‘ not in request.json and ‘name‘ not in request.json:
abort (404)
elif ‘done‘ not in request.json and type(request.json[‘done‘] is not bool):
abort (404)
else:
book[-1][‘author‘] = request.json.get(‘author‘,book[-1][‘author‘])
book[-1][‘name‘] = request.json.get(‘name‘,book[-1][‘name‘])
book[-1][‘done‘] = request.json.get(‘done‘,book[-1][‘done‘])
return jsonify({‘status‘:1003,‘msg‘:‘更新书籍成功‘,‘data‘:book})
api.add_resource(Books,‘/v1/api/books‘)
api.add_resource(Book,‘/v1/api/book/<int:book_id>‘)
if __name__ == "__main__":
app.run(debug=True)
以上是关于python + flask轻量级框架的主要内容,如果未能解决你的问题,请参考以下文章
[ Flask ] 轻量级Python Web框架 学习笔记