SqlAlchemy current db user

Question:

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?

Asked By: Blinxen

||

Answers:

You can use literal_column:

session.query(literal_column("current_user"))

or

connection.execute(select([literal_column("current_user")]))
Answered By: univerio

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.

Answered By: Blinxen

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.

Answered By: IAmBotmaker

In some use cases, one might also rely on the connection string:

current_user = session.bind.url.username
Answered By: mati.o
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.