【发布时间】: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