In this tutorial we will talk about HTTP methods. HTTP methods are the standard way of sending information to and from a web server. To break it down, a website runs on a server or multiple servers and simple returns information to a client (web-browser). Information is exchanged between the client and the server using an HTTP protocol that has a few different methods. We will be discussing the post commonly used ones called POST & GET.
GET is the most commonly used HTTP method and it is typically used to retrieve information from a web server.
POST is commonly used to send information to web server. It is more often used when uploading a file, getting form data and sending sensitive data. POST is a secure way to send data to a web server.
Creating a Form
For this example will create a form and discuss how we can use the POST HTTP method to send the information in our form to our server.
Here is a new html file I created called "login.html".
We've specified the method of the form to be post. Which means that when the form is submitted we will POST data to the web server in the form of a request.
Note the name of the text input field, we will use this to get it's value from our python code.
What we're going to do is setup a login page that asks the user to type in their name. Once they hit the submit button they will be redirected to a page that displays the name they typed in.
We'll start by importing a new module called "request".
Next we'll setup the login page.
To specify that a page works with both POST and GET requests we need to add a method argument to the decorator.
Now from inside the function we'll check if we are receiving a GET or POST request. We'll then define the operation to perform based on the request. If we have received a POST request that means we submitted the form and should redirect to the appropriate page. Otherwise we should simply return and render the login page.
Now we'll setup the user page. This will simply display the users name in h1 tags. Just for example/testing purposes, we don't need anything fancy.
Now let's test out our site!
We'll head to the /login page and type our name.
And after hitting submit! We get a page with our name on it...