gpt4 book ai didi

python - flask 不停地限制RESTful API访问

转载 作者:行者123 更新时间:2023-12-03 17:02:27 25 4
gpt4 key购买 nike

我只希望登录用户访问我的RESTfull API。我一直在搜索,找不到任何告诉我该怎么做的资料。很奇怪,因为我认为保护数据非常普遍。

我正在将Flask项目与Flask-loginflask-Restless一起使用。我通过SQL-alchemy类对数据进行增删改密,以访问我的MySQL数据库。我创建如下的RESTfull API:

api_manager = APIManager(app, flask_sqlalchemy_db=db)
api_manager.create_api(Items, methods=['GET', 'POST', 'DELETE', 'PUT'])


对于未登录的用户,我应该如何限制对RESTfull api的访问,或者不能使用flask-restless来做到这一点?如果没有,我应该/应该怎样使用?

我正在尝试一些技巧,因此欢迎您提出任何建议!

提前致谢



经过更多的玩耍之后,我找到了解决方案。可能不是最好的方法,但是不需要太多代码就可以解决问题:

@app.before_request
def before_request():
if ('/api/' in str(request.url_rule)) && (not current_user.is_authenticated()):
return redirect('/login')


这是正确的方法吗?对于每个可能的HTTP请求,添加Preprosessors是很多代码。 https://flask-restless.readthedocs.org/en/latest/customizing.html#request-preprocessors-and-postprocessors

最佳答案

看来您可以通过customizing Flask-Restless实现所需的功能。您可以使用预处理器来拦截您的API请求。

这是一个片段。请注意,这是未经测试的代码段。

def auth_func(*args, **kw):
if not current_user.is_authenticated():
raise ProcessingException(description='Not authenticated!', code=401)

api_manager = APIManager(app, flask_sqlalchemy_db=db)
api_manager.create_api(Items, methods=['GET', 'POST', 'DELETE', 'PUT'], preprocessors=dict(POST=[auth_func]))


同样,您可以将预处理器注册到您的 APIManager,以对所有API启用它。

api_manager = APIManager(app, flask_sqlalchemy_db=db, preprocessors=dict(POST=[auth_func]))
api_manager.create_api(Items, methods=['GET', 'POST', 'DELETE', 'PUT'])

关于python - flask 不停地限制RESTful API访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33192660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com