Python/Bottle:通过POST发送JSON对象

0 投票
1 回答
2713 浏览
提问于 2025-04-18 01:44

我遇到了一个问题,怎么也解决不了。如果有人能给点建议就太好了。

这个脚本本来是用来从数据库获取内存分配的信息,并把这些信息以格式化的JSON对象返回。脚本在我给它一个静态的JSON对象(也就是我想传递的信息)时运行得很好,但当我尝试通过POST请求传递信息时,它就不行了。

虽然我现在的代码是用request.json("")来获取传递的数据,但我也试过用request.POST.get("")。

我的HTML里有这个POST请求,是用D3的xhr post来实现的:

var stacks = [230323, 201100, 201108, 229390, 201106, 201114];
var stack_ids = {'stack_ids': stacks};
var my_request = d3.xhr('/pie_graph');
my_request.header("Content-Type", "application/json")
my_request.post(stack_ids, function(stuff){ 

stuff = JSON.parse(stuff);
var data1 = stuff['allocations'];
var data2 = stuff['allocated bytes'];
var data3 = stuff['frees'];
var data4 = stuff['freed bytes'];
...
...
}, "json");

而我的服务器脚本有这个路由:

@views.webapp.route('/pie_graph', method='POST')
def server_pie_graph_json():
    db = views.db
    config = views.config
    ret = {
        'allocations' :     [],
        'allocated bytes' : [],
        'frees' :           [],
        'freed bytes' :     [],
        'leaks' :           [],
        'leaked bytes' :    []
    }

    stack_ids = request.json['stack_ids']

    #for each unique stack trace
    for pos, stack_id in stack_ids:
        stack = db.stacks[stack_id]

        nallocs = format(stack.nallocs(db, config))
        nalloc_bytes = format(stack.nalloc_bytes(db, config))
        nfrees = format(stack.nfrees(db, config))
        nfree_bytes = format(stack.nfree_bytes(db, config))
        nleaks = format(stack.nallocs(db, config) - stack.nfrees(db, config))
        nleaked_bytes = format(stack.nalloc_bytes(db, config) - stack.nfree_bytes(db, config))

        # create a dictionary representing the stack
        ret['allocations'].append({'label' : stack_id, 'value' : nallocs})
        ret['allocated bytes'].append({'label' : stack_id, 'value' : nalloc_bytes}) 
        ret['frees'].append({'label' : stack_id, 'value' : nfrees})
        ret['freed bytes'].append({'label' : stack_id, 'value' : nfree_bytes})
        ret['leaks'].append({'label' : stack_id, 'value' : nleaks})
        ret['leaked bytes'].append({'label' : stack_id, 'value' : nfree_bytes})


    # return dictionary of allocation information
    return ret

大部分内容可以忽略,脚本在我给它一个满是数据的静态JSON对象时是可以工作的。

现在请求返回的是500内部服务器错误:JSONDecodeError('Expecting value: line 1 column 2 (char 1)',)。

有没有人能告诉我我哪里做错了?

另外,如果你需要我进一步解释什么,或者提供其他信息,我很乐意这样做。因为我已经在这个问题上纠结了很久,脑袋有点晕,可能漏掉了什么。

1 个回答

0

这是我用POST方法做的事情,它可以正常工作:

from bottle import *
@post('/')
def do_something():
    comment = request.forms.get('comment')
    sourcecode = request.forms.get('sourceCode')

源代码

function saveTheSourceCodeToServer(comment) {
  var path = saveLocation();
  var params = { 'sourceCode' : getTheSourceCode() , 'comment' : comment};
  post_to_url(path, params, 'post');
}

源代码,感谢 JavaScript的POST请求像表单提交一样

撰写回答