简体   繁体   English

flask 宁静 api 动态端点有限制

[英]flask restful api dynamic endpoints with restrictions

So i am relatively new to flask only a couple weeks.所以我对 flask 比较陌生,只有几个星期。 To learn flask more I have set myself an objective on building my own api.为了进一步了解 flask,我为自己设定了一个目标,即构建自己的 api。

use case of the API: API 的用例:

  1. authenticated users should be able to hit the endpoint经过身份验证的用户应该能够访问端点
    www.mydomain.com/api/ and do the below activities (only to their www.mydomain.com/api/并进行以下活动(仅限他们的
    tasks)任务)

    • increase count (POST/PUT)增加计数(POST/PUT)
    • decrease count (DELETE)减少计数(删除)
    • reset count重置计数
  2. non authenticated users should be able to go to www.mydomain.com/api/john and view John's metrics.未经身份验证的用户应该能够 go 到www.mydomain.com/api/john并查看 John 的指标。 I expect there to be many users each with their own metrics我希望有很多用户都有自己的指标

Current state:当前 state:

I can perform, post, get, put and delete operations (no authentication setup yet...)我可以执行、发布、获取、放置和删除操作(尚未设置身份验证...)

My question:我的问题:

Is there a way to restrict users based on their userid.有没有办法根据用户 ID 限制用户。 by this I mean john only has access to perform requests against www.mydomain.com/api/john .我的意思是 john 只能访问对www.mydomain.com/api/john执行请求。

There are several ways of handling this and it's all going to be about what your requirements are.有几种方法可以处理这个问题,这一切都取决于您的要求。

You can build your own (which is typically what I do), or you can use Role-based authorization which Flask-User supports.您可以构建自己的(这通常是我所做的),或者您可以使用Flask-User支持的基于角色的授权。

You can read more on how this works here .您可以在 此处阅读有关其工作原理的更多信息。

Make sure you view their example app to get an idea of how to put it all together.确保查看他们的示例应用程序以了解如何将它们组合在一起。

If you have your own custom permissions, which will be based on user id.如果您有自己的自定义权限,这将基于用户 ID。 Then you can follow the same concept, but handle it based on user id vs roles.然后您可以遵循相同的概念,但根据用户 ID 与角色进行处理。 Perhaps even store the permission levels in the user object (is_admin, is_general_user, etc.) such as something like this (pseudo code):甚至可能将权限级别存储在用户 object(is_admin、is_general_user 等)中,例如这样的(伪代码):

class User:
   is_admin = false
   is_read_only = false

   def __init__(**kwargs):
       # handle kwargs to set permissions

Then you can access your User variables after defining the user in some inherited base factory or something (pseudo code):然后您可以在某些继承的基础工厂或其他东西(伪代码)中定义用户后访问您的User变量:

u = User(**my_permissions)

if(u.is_admin):
    # do something

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM