这可以使用预处理器参数来完成create_api
。例如:
# replace the next line with your favorite way or reading config files
access_password = 'mysecretkey'
def check_credentials(**kwargs):
if flask.request.headers.get('X-Secret-Key','') != access_password:
raise flask_restless.ProcessingException(code=401) # Unauthorized
# create API
manager = flask_restless.APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(models.mymodel, methods=['GET', 'POST', 'DELETE'],
collection_name='myobjects',
preprocessors={
'POST': [check_credentials],
'DELETE_SINGLE': [check_credentials],
})
使用 Python 3.4、Flask 0.11.1、Flask-Restless 0.17.0 测试。Flask-Restless 的旧版本可能需要DELETE
代替DELETE_SINGLE
, 和不同的包名称。
如何使用 cURL 访问受密码保护的 API 部分的示例:
curl -X POST -d '{"data":"my JSON data, etc."}' \
-H "Content-Type: application/json" \
-H "X-Secret-Key: mysecretkey" \
http://localhost:5000/api/myobjects
这是一个简单的方案,但如果您的应用程序将来有可能变得更大,我建议您使用Flask-JWT。数据库后端不必大而复杂。这是您在极简实现中的起始案例(与硬编码密码一起使用的案例):
# Anonymous object is sufficient here, a full-blown solution would define a class User
admin_user = type('', (object,), {"id": 1, "username": "admin", "password": "mysecret"})()
def authenticate(username, password):
if username == admin_user.username and password == admin_user.password:
return admin_user
def identity(payload):
id = payload['identity']
if id == admin_user.id:
return admin_user
jwt = JWT(app, authenticate, identity)
@jwt_required()
def check_credentials(**kwargs):
pass
# create API as in the first example
使用 Python 3.4、Flask 0.11.1、Flask-Restless 0.17.0、Flask-JWT 0.3.2 测试。