python - 如何获取登录用户的名称(Flask,SQLAlchemy)
问题描述
我想自动为登录会话中的作者命名。到目前为止,我可以登录用户,但是当他已经登录时,我无法找到在现场使用他的名字的方法。
所以我正在尝试创建某种方式,它将在他登录内存后存储用户名,然后烧瓶将使用此用户名来发布博客文章和评论或编辑个人资料。谢谢
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
username = Column(String(64))
password = Column(String(120))
email = Column(String(64))
def __init__(self, username, password, email):
self.username = username
self.password = password
self.email = email
Base.metadata.create_all(engine)
Base2 = declarative_base()
class Blogpost(Base2):
__tablename__ = 'blogpost'
id = Column(Integer, primary_key=True)
title = Column(String(50))
subtitle = Column(String(50))
author = Column(String(20))
date_posted = Column(DateTime)
content = Column(Text)
def __init__(self, title, subtitle, author, date_posted, content):
self.title = title
self.subtitle = subtitle
self.author = author
self.date_posted = date_posted
self.content = content
@app.route('/login', methods=['POST'])
def login():
POST_USERNAME = str(request.form['username'])
POST_PASSWORD = str(request.form['password'])
def check_password(hashed_password, user_password):
password, salt = hashed_password.split(':')
return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()
Session = sessionmaker(bind=engine)
s = Session()
user = s.query(User).filter_by(username=POST_USERNAME).first()
if check_password(user.password, POST_PASSWORD) == True:
session['logged_in'] = True
user_name = POST_USERNAME
else:
flash('wrong password!')
return index()
@app.route('/add')
def add():
return render_template('add.html')
@app.route('/addpost', methods=['POST'])
def addpost():
title = request.form['title']
subtitle = request.form['subtitle']
content = request.form['content']
Session = sessionmaker(bind=engine)
session = Session()
post = Blogpost(title=title, subtitle=subtitle, author=user_name, content=content, date_posted=datetime.now())
session.add(post)
session.commit()
解决方案
我鼓励您使用诸如烧瓶登录之类的扩展来进行用户管理,或者使用烧瓶安全来进行扩展功能,同时,您可以将用户存储在烧瓶会话中。
第一个导入会话(我将其称为 login_session 以将其与您的 sql-alchemy 会话区分开来)
from flask import session as login_session
然后,一旦用户登录,您就可以像这样存储用户详细信息
login_session['username'] = user.username #user here being the user object you have queried
并从会话访问用户名
username = login_session['username']
并且一旦用户注销,您就可以像这样从会话中删除用户详细信息
del login_session['username']
但正如其他人在评论中提到的那样,对于一个严肃的网络应用程序,您将需要考虑使用烧瓶扩展之一进行用户管理
推荐阅读
- docker - 将 OpenIAM 作为外部身份验证添加到 nginx
- python - 使用嵌套字典的点系统
- react-native - RN 这些文件都不存在:* aws-exports
- python - 从噪声数据中插入连续曲线
- c# - 如何在实体框架中异步删除一组记录?
- angular - 发生未处理的异常:在 Angular Universal 中找不到模块“is-unicode-supported”
- angular - 表单数组 Angular
- powershell - 在powershell中打印环境变量时如何不修剪线条?
- javascript - JSON数组中的嵌套对象仅返回第一项的值
- rust - Rust/Cargo 中的分组测试