Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 瓶后方法-获取查询参数_Python_Ajax_Post_Bottle - Fatal编程技术网

Python 瓶后方法-获取查询参数

Python 瓶后方法-获取查询参数,python,ajax,post,bottle,Python,Ajax,Post,Bottle,我试图向瓶子服务器发送POST AJAX请求,并读取查询字符串参数。 这适用于GET方法,但对于POST,瓶子.request.query\u字符串为空 这是在Python3.6.8中实现的。0.12.17中的瓶子版本 我卡住了,请告诉我 瓶子服务器: #!/usr/bin/env python3 import bottle print(bottle.__version__) class EnableCors(object): name = "enable_cors" api

我试图向瓶子服务器发送POST AJAX请求,并读取查询字符串参数。 这适用于GET方法,但对于POST,瓶子.request.query\u字符串为空

这是在Python3.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)
<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>
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'
测试脚本客户端:

#!/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)
<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>
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'

功能测试后参数(){
变量数据={'e':'e','f':'f','g':{'aa':'aa','bb':'bb'};
$.ajax({
网址:'http://127.0.0.1:8080/api/params',
方法:“张贴”,
数据:“key=a”,
//contentType:“文本/普通”,
成功:功能(响应、文本状态){
调试(“测试后参数正常”);
console.debug(textStatus);
调试(响应);
},
错误:函数(响应、文本状态){
调试(“测试后参数错误”);
console.debug(textStatus);
调试(响应);
},
})
}
window.onload=test\u post\u参数;

我把它放在我所有的API端点上。我将POST表单和查询编码合并到一个dict中

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))

我把它放在我所有的API端点上。我将POST表单和查询编码合并到一个dict中

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))

下面是一个将数据作为JSON发送到我已成功使用的POST路由的示例

JQuery AJAX调用:

#!/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)
<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>
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'
瓶子路径:

#!/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)
<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>
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'

我更喜欢从瓶子导入路径、get、post、模板、静态文件、请求中选择
,作为导入语句。这使得路线写得更简单(在我看来)


下面是一个将数据作为JSON发送到我已成功使用的POST路由的示例

JQuery AJAX调用:

#!/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)
<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>
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'
瓶子路径:

#!/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)
<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>
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'

我更喜欢从瓶子导入路径、get、post、模板、静态文件、请求中选择
,作为导入语句。这使得路线写得更简单(在我看来)