I'm integrating the Facebook SDK for JavaScript into my Python Flask web application. I want the ability to access a logged in user's Facebook id server-side.
My current approach is to build a form containing a hidden input which stores the id and submit it when the user logs in:
<script>
function sendToBackEnd(){
FB.getLoginStatus(function(response){
if (response.status == 'connected'){
$form = $('<form>', {'action': '/process_form', 'method': 'POST'}).appendTO('body');
FB.api('/me', function(response){
$('<input>', {'class': 'hidden', 'name': 'FB_id', 'value': response.id}).appendTo($form);
});
}
});
}
</script>
<div class="fb-login-button" onlogin="sendToBackEnd"></div>
Then store that id in the flask session
object:
@app.route('/process', methods=['GET', 'POST'])
def process():
session['FB_id'] = request.form['FB_id']
print("User's Facebook id now accessible across all routes server-side!")
return redirect(url_for('index'))
Is there a better approach here or is submitting a hidden form the only way to pass this data from client to server-side?
Just a thought... I noticed there's a parameter in the FB.init() method called cookie
which is a described as, "Inidcates whether a cookie is created for the session. If enabled, it can be accessed by server-side code." I'm pretty sure the flask session object can't be modified client-side (rightfully so), but maybe this separate cookie can be assessed server-side in my python code?
You can set the user's fb_id as a session cookie and access it server-side. This can be done by fb_id = request.cookies.get('COOKIE_NAME')
Decided to use a GET or POST request to the Flask app after I login / logout. Creating the form was totally unnecessary and overly complicated.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.