Reputation: 864
I am trying to get the current user of the db I have. But I couldn't find a way to do that and there are no questions on stackoverflow similar to this. In postgresql there is a method current_user
. For example I coudl just say SELECT current_user
and I would get a table with the current user's name. Is there something similar in Sqlalchemy?
Upvotes: 3
Views: 4892
Reputation: 1768
In some use cases, one might also rely on the connection string:
current_user = session.bind.url.username
Upvotes: 0
Reputation: 352
If you use flask-login
module of Flask you could just import a function current_user
with from flask_login import current_user
.
Then you could just get it from the database and db model (for instance Sqlite/SqlAlchemy) if you save it in a database:
u_id = current_user.id
u_email = current_user.email
u_name = current_user.name
etc.
Upvotes: 1
Reputation: 864
So I found another way to get the current db user in sqlalchemy. I can just say func.current_user()
and I will get the current db user. To use func
I had to make an import. The import looks like this from sqlalchemy.sql import func
. I also found out that I could just say:
curr_usr = self.session.query("current_user")
for usr in curr_usr:
user = usr[0]
There I also get the db user. I wrote usr[0]
because curr_usr
return a list with two items. I don't know why it does that but it just does and the first item of that list is the name of the db user.
Upvotes: 1
Reputation: 20518
You can use literal_column
:
session.query(literal_column("current_user"))
or
connection.execute(select([literal_column("current_user")]))
Upvotes: 5