首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python requests.Session()的JavaScript替代方案

Python requests.Session()的JavaScript替代方案
EN

Stack Overflow用户
提问于 2018-01-08 22:12:13
回答 1查看 1.5K关注 0票数 2

我最近为一个聊天机器人开发了一个Python API,并使用一个快速的python脚本做了一个演示:

代码语言:javascript
复制
s = request.Session()

user_response = None
while True:
    chat_response = s.get(url='http://localhost:5000/chat', json={'user_input': user_response}).json()
    if chat_response['is_end']:
        break
    if 'text' in response_json:
        print '\t' + response_json['text']
    user_response = raw_input()

当调用聊天路由时,我设置了一个唯一的会话密钥

代码语言:javascript
复制
if 'session_id' not in session:
    session['session_id'] = chat_utils.id_generator()

这在命令行上工作得很好,会话id用于跟踪服务器上的对话。但是,我正在尝试在JavaScript前端实现这一点。有没有等同于这条线的

代码语言:javascript
复制
s = request.Session()

目前,我无法存储会话信息,因此使用不同的生成密钥重复了最初的问题(见下文)。

这是使用BotUI生成的

对API的调用使用以下代码:

代码语言:javascript
复制
function chat(){
  botui.action.text({
    delay: 1000,
    action: {
      placeholder: 'User response here'
    }
  }).then(function (res) {
    sendxhr(res, textResponse)
  });
}

function sendxhr(user_input, formatter){

  var xhr = new XMLHttpRequest();

  xhr.open('GET', 'http://localhost:5000/chat');
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.setRequestHeader("user_input", user_input);

  xhr.onload = function () {
    var res = JSON.parse(xhr.responseText)
    console.log(res)
    formatter(res.text)
  }

  xhr.send();
}

API调用可以工作,但因为每次聊天路由启动新会话时都没有会话。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-12 15:56:07

这个问题的解决方案是为html提供服务。我没有在本地打开html,而是添加了一个路由来服务静态html。

代码语言:javascript
复制
@app.route("/")
def index():
    return render_template('index.html')

javascript被加载到html中,一切都运行得很好。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48152056

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档