【问题标题】:Parsing json request in flask 0.9在烧瓶 0.9 中解析 json 请求
【发布时间】:2013-06-14 06:37:25
【问题描述】:

(对于任何后端开发,我都是一个完整的初学者,所以如果任何术语使用错误,我深表歉意)

我有一些控制画布游戏的 javascript,并且我有一个可以解决游戏的序言规划器。我现在正在尝试连接两者并设置了一个烧瓶服务器,它可以成功调用 prolog,获取正确的计划并将其发送回 javascript。我真的很难从 javascript 中获得正确的输入。

Javascript:

var state = {
  state : "[stone(s1),active(s1), stone(s2), in(app2,s2), unlocked(app2)]"
}

stone2.on('click',function(){
  $.ajax({
    type: 'POST',
    contentType: 'application/json',
    data: state,
    dataType: 'json',
    url:'http://localhost:5000/next_move',
    success:function(data, textStatus, jqXHR){
      console.log(data);
      alert(JSON.stringify(state)); //making sure I sent the right thing
    }
  });
});

烧瓶服务器

//variables I use in the query at the moment
state = "[stone(s1),active(s1), stone(s2), in(app2,s2), unlocked(app2)]"
goal = "[in(app1,s1),in(app1,s2)]"
@app.route('/next_move', methods=['POST'])
def get_next_step():
  own_state = request.json
  r = own_state['state']
  output = subprocess.check_output(['sicstus','-l','luger.pl','--goal','go('+state+','+goal+').']) 
  //I would like to use the string I got from my browser here
  stripped = output.split('\n')
  return jsonify({"plan": stripped})
  //the correct plan is returned

我已经看到有关此的其他问题,实际上我发布的尝试来自 flask request.json order,但我不断收到 400(错误请求)。我猜从那以后烧瓶变了?我知道它正确发送了 json,因为如果我不尝试触摸它,我会在浏览器中收到成功消息,所以纯粹是我无法访问它的字段或找到任何示例。

【问题讨论】:

    标签: json flask sicstus-prolog


    【解决方案1】:

    您通过 POST 发送的不是 JSON。这只是一个set of key value 对,因此您应该直接发送它。并使用request.form 将其取出。

    在你的情况下,我也不会使用 jQuery 的 $.ajax 而是使用 $.post

    代码如下:

    stone2.on('click',function(){
    $.post('http://localhost:5000/next_move',
           state,
           function(data) {
             console.log(data);
             alert(JSON.stringify(state));
           }
    );
    
    @app.route('/next_move', methods=['POST'])
    def get_next_step():
      own_state = request.form
      r = own_state['state']
      print r
      return jsonify({"plan": "something"})
    

    【讨论】:

    • 谢谢!像魅力一样工作!
    猜你喜欢
    • 2014-07-23
    • 1970-01-01
    • 2016-04-21
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 2018-08-22
    • 2021-07-31
    相关资源
    最近更新 更多