Testing the Submit POST Button Using the Python Bottle

Let's say you have a form with several posts:

<form method="POST" action="/etc"> <input name="foo" type="submit" value="Foo!"> <input name="bar" type="submit" value="Bar!"> </form> 

Checking which submit button is pressed in PHP is simple:

 if (isset($_POST['foo'])) { return 'foo' } if (isset($_POST['bar'])) { return 'bar' } 

What is the Python.Bottle equivalent?

I tried:

 if (request.POST.get('foo')): return 'foo' if (request.POST.get('bar')): return 'bar' 

But this returns a KeyError, which means that "foo" and "bar" are not in the "POST dict" field.

I also tried adding a test field to the form and returning the value in this field when the form is submitted and works fine, so the form is submitted.

One thing that may be important: submit buttons on the form are dynamically generated.

EDIT: A possible problem was found. I use jQuery to publish and serialize form data, but obviously jQuery serializes the omits submit buttons from the output, which will definitely lead to what I see. Currently working on a workaround, but any help is still appreciated.

+4
source share
2 answers

The problem was that the jQuery serialization function ignores submit buttons.

I went around it by adding a class ( submitButton in the example) to all the corresponding submit buttons and adding the hidden input ( theHiddenInput ) to the form, and then adding the following handler:

 $('.submitButton').click(function() { this.form.theHiddenInput.value = this.name; }); 

The following code is the equivalent of my previous code:

 if (request.POST.get('theHiddenInput') == 'foo'): return 'foo' if (request.POST.get('theHiddenInput') == 'bar'): return 'bar' 

Perhaps this will help someone in the future.

+2
source

Can you add enctype="multipart/form-data" to your form?

 <form action="/etc" method="post" enctype="multipart/form-data"> <input name="foo" type="submit" value="Foo!"> <input name="bar" type="submit" value="Bar!"> </form> 

According to the bottle documentation :

BaseRequest.forms

Form values ​​parsed using url-encoded or multipart/form-data encoded POST or PUT body. The result is reconfigured as FormsDict . All keys and values ​​are strings. Downloading files is saved separately in files .

and

BaseRequest.POST

The values ​​of forms and files combined into one FormsDict . Values ​​are either strings (form values) or cgi.FieldStorage examples (file cgi.FieldStorage ).

+1
source

Source: https://habr.com/ru/post/1443385/


All Articles