Метод Bottle POST - получение параметров запроса - PullRequest
1 голос
/ 24 октября 2019

Я пытаюсь отправить запрос POST AJAX на сервер Bottle и прочитать параметры query_string. Это работает с методом GET, но с POST бутылка.request.query_string пуста.

Это с питоном 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>

Ответы [ 2 ]

3 голосов
/ 25 октября 2019

Я поставил это на все мои конечные точки 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 голосов
/ 27 октября 2019

Вот пример отправки данных в виде JSON на маршрут POST, который я успешно использовал.

Вызов AQAX JQuery:

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'
...