【问题标题】:Bottle POST method - getting query parametersBottle POST 方法 - 获取查询参数
【发布时间】:2020-02-20 22:06:15
【问题描述】:

我正在尝试向 Bottle 服务器发送 POST AJAX 请求并读取 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)

测试 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


    【解决方案1】:

    我把它放在我所有的 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))
    

    【讨论】:

      【解决方案2】:

      这是一个将数据作为 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'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-11
        • 1970-01-01
        • 1970-01-01
        • 2019-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多