问题
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())
回答1:
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"])
回答2:
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
})
}])
来源:https://stackoverflow.com/questions/17196764/reading-flask-session-with-angularjs