【问题标题】:How to design and set up user and role tables to retrieve values from both?如何设计和设置用户和角色表以从两者中检索值?
【发布时间】:2019-11-27 08:03:16
【问题描述】:

在 Flask 中,有一个函数可以从会话 cookie 加载用户或在请求之前设置它,但是使用 SQL 确定该用户具有哪些角色/权限的正确方法是什么?

表格:

CREATE TABLE app_user (
  id SERIAL PRIMARY KEY,
  username VARCHAR (50) UNIQUE NOT NULL,
  password VARCHAR (500) NOT NULL
);

CREATE TABLE role (
  role_id SERIAL PRIMARY KEY,
  role_description VARCHAR (25)
);

INSERT INTO role (role_description) VALUES
  ('New'),
  ('Active'),
  ('Moderator');

CREATE TABLE user_role (
  app_user_id INTEGER NOT NULL,
  app_user_role_id INTEGER NOT NULL,
  FOREIGN KEY (app_user_id) REFERENCES app_user (id),
  FOREIGN KEY (app_user_role_id) REFERENCES role (role_id)
);

Flask,加载用户:

@bp.before_app_request
def load_logged_in_user():
    user_id = session.get('user_id')

    if user_id is None:
        g.user = None
    else:
        db = get_db().cursor()
        load_user = db.execute(
            'SELECT * FROM app_user WHERE id = %s', (user_id,)
            # SELECT u.id, username, app_user_role_id
            # WHERE u.id = %s', (user_id,)
            # FROM app_user u JOIN user_role r ON u.id = app_user_id
            # Don't know how to do this, or how it is usually done
            # As it stands now it doesn't make any sense, as I have 
            # been fiddling with it for too long.

        )
        load_user = db.fetchone()
        g.user = load_user

将所有内容都放在用户表中会更好吗?因为可能有很多信息并不总是需要,所以几个表会使其更快,还是只是需要更多的连接?

在大型应用程序中使用 ORM 或编写原始 SQL 是否正常?与使用 ORM 相比,编写原始 SQL 是否可以将性能提高三倍?

【问题讨论】:

    标签: python sql postgresql flask psycopg2


    【解决方案1】:

    要获取用户及其权限,您可以使用 join :

    select app_user.username, role.role_description
      from app_user
      join user_role
        on app_user.id = user_role.app_user_id
      join role
        on user_role.app_user_role_id = role.id
      where app_user.id = %s
    

    至于你的第二个问题,我当然会像你一样使用几个表,而不是一个,因为关系数据库就是这样工作的。

    如果您想使用唯一的表,您可能应该寻找面向文档的数据库,例如 mongoDB 或 ElasticSearch(对于小型项目,ES 可能是多余的)。

    https://www.mongodb.com

    https://www.elastic.co/products/elasticsearch

    编辑:为您的新问题

    使用 ORM 的优势在于它使编码部分更快、更容易和更安全。

    当然,有时会出现 ORM 无法正确优化的复杂请求。 我正在考虑 django 的 ORM,众所周知,在一些复杂请求的情况下它不会发光。 但是,对于这些特定情况,您始终可以手动编写自己的查询以获得更好的性能。

    关于这个话题有一篇有趣的文章:https://medium.com/@hansonkd/performance-problems-in-the-django-orm-1f62b3d04785

    【讨论】:

      猜你喜欢
      • 2018-09-30
      • 1970-01-01
      • 2012-03-08
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 2016-01-19
      • 1970-01-01
      相关资源
      最近更新 更多