简体   繁体   English

从ajax调用维护python flask会话

[英]Maintaining python flask sessions from an ajax call

I am using flask sessions in my program to maintain all dynamic information .I have hosted my service on local host. 我在程序中使用flask会话维护所有动态信息。我已将服务托管在本地主机上。

from flask import Flask,make_response,render_template, request, jsonify,json,jsonify,send_from_directory,session
from flask.ext.cors import CORS, cross_origin
import requests


app = Flask(__name__)
app.secret_key='test'  
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'


@app.route('/getAnswer')    
@cross_origin() 
def getAnswer():
    userQuery = request.args.get("query") 


    session['username']="testuser"
    session['userid']="Utkj3YC"
    reply=askquestion(userQuery,session)
    print "giving response : ",str(reply)
    answer=str(reply)

    return jsonify(response=answer,id="1",status="suc",dialog="initial")

if __name__ == '__main__':
    app.run(host='0.0.0.0',processes=True,debug=True,port=8000)

This is my flask service and this works fine when i am testing the same from postman restclient. 这是我的烧瓶服务,当我从邮递员restclient测试相同功能时,它可以正常工作。 The postman requests are maintaining the same session variables. 邮递员请求保持相同的会话变量。

在此处输入图片说明

The problem is when i integrated this service with my UI. 问题是当我将此服务与UI集成在一起时。 the ajax request every time resets the flask session variable because of which i am unable to maintain the session. Ajax请求每次都会重置flask会话变量,因此我无法维护该会话。 My ajax call is as follows 我的ajax电话如下

$.ajax({
        url: "http://127.0.0.1:8000/getAnswer",
        method: 'GET',

        data: { query: query,dialog:dialog },
        success: function(data) { 


         var $chatBox = $('#botReplyDiv').clone().prop('id',"botdiv"+data.id);
         var $loading = $('.loader');
         $chatBox.css("display", "block");
         var ul  = document.createElement('ul');
         console.log(data.response);
         var resp=data.response;
         var li=document.createElement('li');
         li.appendChild(document.createTextNode(data.response));

         ul.appendChild(li);

         }
         });

I also tried adding this in the ajax request. 我也尝试将其添加到ajax请求中。

xhrFields: {
  withCredentials: true
  }

But the problem still persists. 但是问题仍然存在。 every time a new session is created in flask. 每次在flask中创建一个新会话时。 But the same code when i do with POSTMAN ,it is persisting the same session. 但是当我使用POSTMAN时,相同的代码将保持相同的会话。 What is the change that i have to do to make the ajax call retain the same session in every request ? 为了使ajax调用在每个请求中保留相同的会话,我必须做什么更改?

The problem was i was using http://locahost:8000/getAnswer in my client side code. 问题是我在客户端代码中使用了http:// locahost:8000 / getAnswer I changed it ti http://127.0.0.1:8000/getAnswer and it is working fine now. 我将其更改为http://127.0.0.1:8000/getAnswer ,现在可以正常使用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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