Bottle POST方法-获取查询参数

问题描述 投票:1回答:2

我正在尝试将POST AJAX请求发送到Bottle服务器并读取query_string参数。这适用于GET方法,但适用于POST,bottle.request.query_string为空。

这是python 3.6.8。 0.12.17中的瓶子版本

我被卡住了,请指教。

瓶装服务器:

#!/usr/bin/env python3

import bottle
print(bottle.__version__)

class EnableCors(object):
    name = "enable_cors"
    api = 2

    def apply(self, fn, context):
        def _enable_cors(*args, **kwargs):
            bottle.response.headers["Access-Control-Allow-Origin"] = "*"
            bottle.response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, OPTIONS"
            bottle.response.headers["Access-Control-Allow-Headers"] = "Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token"

            if bottle.request.method != "OPTIONS":
                return fn(*args, **kwargs)

        return _enable_cors

application = bottle.app()
application.install(EnableCors())

@application.route("/api/params", method=['OPTIONS', 'POST'])
def Api_Params():
    print('bottle.request.query_string:', bottle.request.query_string)


bottle.run(host='0.0.0.0', port=8080, debug=True, reloader=True)

Test javscript客户端:

<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>

<body>
<script>

function test_post_param() {

    var data = {'e': 'E', 'f': 'F', 'g': {'aa':'AA', 'bb':'BB'}};

    $.ajax({
        url: 'http://127.0.0.1:8080/api/params',

        method: "POST",
        data: "key=a",
        // contentType: "text/plain",

        success: function (response, textStatus) {
            console.debug("test_post_param OK");
            console.debug(textStatus);
            console.debug(response);
        },
        error: function (response, textStatus) {
            console.debug("test_post_param ERR");
            console.debug(textStatus);
            console.debug(response);
        },
    })
}


window.onload = test_post_param;


</script>
</body>

</html>
python ajax post bottle
2个回答
3
投票

我将其放在所有API端点上。我将POST表单和查询编码合并为一个字典。

def merge_dicts(*args):
    result = {}
    for dictionary in args:
        result.update(dictionary)
    return result

payload = merge_dicts(dict(request.forms), dict(request.query.decode()))

所以您的代码将如下所示:

@application.route("/api/params", method=['OPTIONS', 'POST'])
def Api_Params():
    payload = merge_dicts(dict(request.forms), dict(request.query.decode()))
    print('bottle.request.query_string: {}'.format(payload))

0
投票

这是将数据作为JSON发送到我成功使用的POST路由的示例。

JQuery AJAX调用:

function test_post_param() {
    var data = {'e': 'E', 'f': 'F', 'g': {'aa':'AA', 'bb':'BB'}};

    $.ajax({
        url: 'http://127.0.0.1:8080/api/params',
        method: "POST",
        data: JSON.stringify({
              "key": "a"
          }),
        cache: false,
        contentType: "application/json",
        dataType: "json",
        success: function(data, status, xhr){
           // Your success code
        },
        error: function(xhr, status, error) {
            // Your error code
        }
    })
};

[瓶子路线:

@application.route("/api/params", method=['POST'])
def Api_Params():
    key = bottle.request.forms.get("key")
    print(key) # This should print 'a'

我更喜欢from bottle import route, get, post, template, static_file, request作为导入语句。这样(我认为)可以更简单地编写路线。

@post("/api/params")
def Api_Params():
    key = request.forms.get("key")
    print(key) # This should print 'a'
© www.soinside.com 2019 - 2024. All rights reserved.