Flask-restful 基本认证
Flask-restful basic Authentication
我是 Flask 的新手,我的学业需要一些帮助。
我正在尝试使用 flask-restful 构建一个简单的 ToDo 列表系统。
我当前的代码如下所示:
class ToDoList(Resource):
'''TODO LIST'''
operation = ['delete']
decorators = [auth.login_required, advertise('operation')]
def post(self):
"""remove all item in the TODO list"""
operation = request.args.get('op')
if operation == 'delete':
collection2.delete_many({})
return {'Success': 'OK'}, 200
return {'Error':'Illegal Operation'}, 400
def get(self):
"""return a list of the TODO name"""
list_1 = collection2.find()
list_2 = []
for each in list_1:
list_2.append(JSONEncoder().encode(each))
return {'list':list_2}, 200
它有效,但我只希望 post
方法需要身份验证,而 get
方法不需要身份验证,这样任何人都可以在不登录的情况下获取列表。我正在使用 flask-restful 我不知道如何为每个函数单独提供装饰器。
来自 Flask-RESTful 文档 [1]:
Alternatively, you can specify a dictionary of iterables that map to HTTP methods and the decorators will only apply to matching requests.
def cache(f):
@wraps(f)
def cacher(*args, **kwargs):
# caching stuff
return cacher
class MyResource(restful.Resource):
method_decorators = {'get': [cache]}
def get(self, *args, **kwargs):
return something_interesting(*args, **kwargs)
def post(self, *args, **kwargs):
return create_something(*args, **kwargs)
你的情况是:
method_decorators = {'post': [auth.login_required]}
我使用 flaskrestplus 进行基本身份验证。所有必需的授权都作为授权字典提供。然后将它们传递给 API。
也可以使用
在方法级别应用授权
@api.doc(security='basicAuth')
验证逻辑(可以是 ldap 验证或 db 验证)可以写在一个名为 requires_Auth 的装饰器中。使用
调用此装饰器
decorators = [requires_Auth]
完整代码
from flask import Flask, request
from flask_restplus import Api, Resource
from functools import wraps
def requires_Auth(f):
@wraps(f)
def decorator(*args, **kwargs):
auth = request.authorization
if auth:
print "inside decorator", auth.username,auth.password
return f(*args, **kwargs)
else:
return "Login required!!!!",401
return decorator
authorizations = {
'basicAuth': {
'type': 'basic',
'in': 'header',
'name': 'Authorization'
}
}
api = Api(app, version='1.0',
authorizations=authorizations
)
ns = api.namespace('/', description='Authentication API')
@ns.route('/withDecorator')
class HelloWorldWithDecorator(Resource):
decorators = [requires_Auth]
@api.doc(security='basicAuth')
def get(self):
return {'hello': 'world'}
api.add_namespace(ns)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5001)
我是 Flask 的新手,我的学业需要一些帮助。
我正在尝试使用 flask-restful 构建一个简单的 ToDo 列表系统。
我当前的代码如下所示:
class ToDoList(Resource):
'''TODO LIST'''
operation = ['delete']
decorators = [auth.login_required, advertise('operation')]
def post(self):
"""remove all item in the TODO list"""
operation = request.args.get('op')
if operation == 'delete':
collection2.delete_many({})
return {'Success': 'OK'}, 200
return {'Error':'Illegal Operation'}, 400
def get(self):
"""return a list of the TODO name"""
list_1 = collection2.find()
list_2 = []
for each in list_1:
list_2.append(JSONEncoder().encode(each))
return {'list':list_2}, 200
它有效,但我只希望 post
方法需要身份验证,而 get
方法不需要身份验证,这样任何人都可以在不登录的情况下获取列表。我正在使用 flask-restful 我不知道如何为每个函数单独提供装饰器。
来自 Flask-RESTful 文档 [1]:
Alternatively, you can specify a dictionary of iterables that map to HTTP methods and the decorators will only apply to matching requests.
def cache(f):
@wraps(f)
def cacher(*args, **kwargs):
# caching stuff
return cacher
class MyResource(restful.Resource):
method_decorators = {'get': [cache]}
def get(self, *args, **kwargs):
return something_interesting(*args, **kwargs)
def post(self, *args, **kwargs):
return create_something(*args, **kwargs)
你的情况是:
method_decorators = {'post': [auth.login_required]}
我使用 flaskrestplus 进行基本身份验证。所有必需的授权都作为授权字典提供。然后将它们传递给 API。 也可以使用
在方法级别应用授权@api.doc(security='basicAuth')
验证逻辑(可以是 ldap 验证或 db 验证)可以写在一个名为 requires_Auth 的装饰器中。使用
调用此装饰器decorators = [requires_Auth]
完整代码
from flask import Flask, request
from flask_restplus import Api, Resource
from functools import wraps
def requires_Auth(f):
@wraps(f)
def decorator(*args, **kwargs):
auth = request.authorization
if auth:
print "inside decorator", auth.username,auth.password
return f(*args, **kwargs)
else:
return "Login required!!!!",401
return decorator
authorizations = {
'basicAuth': {
'type': 'basic',
'in': 'header',
'name': 'Authorization'
}
}
api = Api(app, version='1.0',
authorizations=authorizations
)
ns = api.namespace('/', description='Authentication API')
@ns.route('/withDecorator')
class HelloWorldWithDecorator(Resource):
decorators = [requires_Auth]
@api.doc(security='basicAuth')
def get(self):
return {'hello': 'world'}
api.add_namespace(ns)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5001)