Skip to content

Improve handling for POST parameters #15

Open
@chabala

Description

@chabala

I saw this example code for handling POST requests in another issue:

@web_app.route("/led_on", ["POST"])
def led_on(request):
    print("led on!")
    r = request.query_params["r"]
    g = request.query_params["g"]
    b = request.query_params["b"]
    status_light.fill((int(r), int(g), int(b)))
    return ("200 OK", [], [])

It looks pretty straightforward, but when I tried it, it doesn't work. query_params only has the parameters from the query string; the POST parameters are in the request body as one might expect.

My working code looks like this:

@web_app.route("/led_on", ["POST"])
def led_on(request):
    print("led on!")
    if request.method == "POST":
        post_params = request.__parse_query_params(request.body.getvalue())
        request.body.close()
        r = post_params.get('r')
        g = post_params.get('g')
        b = post_params.get('b')
        status_light.fill((int(r), int(g), int(b)))
    return ("200 OK", [], [])

I can reuse the __parse_query_params() logic, but it's a little less intuitive than the first example would suggest. Perhaps this could be improved? Should query_params contain request body parameters for POST requests? Maybe it should be a different collection, or only parse the request body on demand.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions