简体   繁体   中英

reading flask.session with angularjs

Is there a way to access something in session set with flask.session from angular.js on the client side? I am trying to pass data and store to session in the same call from flask and be able to read it from angular later on in the flow.

I am not using the templating system. For the pages, I am only serving up the index file and then using Angular to do the rest. This is my call for the index file:

@app.route("/")
def index():
    return make_response(open('templates/index.html').read())

If you need access to it in your template, remember that templates have access to session by default in Flask.

<script>
var someConfigurationObject = {
    someKey: "{{session["somevalue"]}}",
    other: "keys",
    "go": "here"
};
</script>

If you are sending data back and forth via ajax calls you can simply include it in your response:

return jsonify(data=your_data, session_info=session["special_key"])

Make a service on Angular to read from your server.

app.factory('Session', ['$http', function ($http) {
  return {
    getSessionData: function (callback) {
      $http.get('/_session?key=x').success( function (res) {
       callback(res)
      })  
    } 
  }   
}])

Return the value from Flask:

@app.route('/_session')
def get_from_session():
    key = request.params['key']
    return session.get(key)

Use it in the Controller:

app.controller(MainCtrl, ['$scope', 'Session', function ($scope, Session) {
  $scope.x = null
  Session.get( function (res) {
    $scope.x = res
  })
}])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM