Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question about current_user._get_current_object() #348

Closed
shaoeChen opened this issue Apr 16, 2018 · 2 comments
Closed

Question about current_user._get_current_object() #348

shaoeChen opened this issue Apr 16, 2018 · 2 comments
Labels

Comments

@shaoeChen
Copy link

shaoeChen commented Apr 16, 2018

I try to understand Flask Web example 11-3 app/main/views.py

post=Post(body=form.body.data,
          author=current_user._get_current_object())

but I was thinking about something, why don't use current_user.id?
i try to create a View Function

@blog.route('/blog_post/c', methods=['GET', 'POST'])
@login_required
def post_blog_post():
    form = Form_Blog_Post()
    if form.validate_on_submit():
        print(current_user.id)
        print(current_user._get_current_object())
        print(current_user._get_current_object().id)

I got the following result

1
username:username, email:email@email.com
1

current_user implement through LocalProxy, while user login , then set the _request_ctx_stack.top.user= login user, i don't understand why we need use current_user._get_current_object() to got the user object.

    _request_ctx_stack.top.user = user
    user_logged_in.send(current_app._get_current_object(), user=_get_user())
    return True

i always thought current_app._get_current_object or current_user._current_object is used to the request not in the same context, like the example『sendmail.py』, it seem i am wrong.
i am sorry , my english is very poor, hope you can understand what i mean!

@miguelgrinberg
Copy link
Owner

miguelgrinberg commented Apr 16, 2018

You have two options. One is what I did:

post=Post(body=form.body.data,
          author=current_user._get_current_object())

the other is to use the user id:

post=Post(body=form.body.data,
          user_id=current_user.id)

Both are equivalent, but I prefer the former because it uses objects instead of IDs. The reason why you need to add _get_current_object() is that as you stated, current_user is not a User object, it is a proxy object. SQLAlchemy gets confused if you give it the proxy, so you have to retrieve the actual User object from inside the proxy.

@shaoeChen
Copy link
Author

Yes, I see.
Thanks for your direction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants