-
Notifications
You must be signed in to change notification settings - Fork 7
Session 16: HTTP forms

- Time: 2h
- Date: Tuesday, March-24th-2020
-
Goals:
- Learn how to send information form the Client to the server
- Design our first HTML forms
- Introduction
- Our first form
- Happy Server
- Type of inputs
- TODO
- Exercises
- End of the session
- Author
- Credits
- License
The clients can request resources from a web server, but also submit data to them. For sending information from the client to the server we use the html forms
All the examples of this session should be stored in the Session-16 Folder
Let's create our first simple form: Just a text box with a submit button. We will use it to send a text message to our echo server. This is the HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>FORM 1</title>
</head>
<body>
<form action="echo" method="get">
Message to send to the server: <br>
<input type="text" name="msg">
<input type="submit" value="SEND">
</form>
</body>
</html>Write the HTML in the form-1.html file
If you open it in the browser you will see:

We have created two inputs. Each input is define with the <input> html tag. With the attribute type we define how is the input. The first one is a text input. The second one is a button for submitting the information
The text input has been named as msg. Also notice the action attribute on the form tag. Their value is "echo". This means that when the submit button is pressed, the client will emit a request message for the /echo resource
This is the request line generated by the client when the submit button is pressed, and we have typed the string "Testing..." into the text box

Let's write a web server that always response with the same page, regardless of what the client has requested (a happy server!). We want to test what happens when the submit button is pressed
- Create a new python file: form-server1.py, with the following code:
import http.server
import socketserver
import termcolor
from pathlib import Path
# Define the Server's port
PORT = 8080
# -- This is for preventing the error: "Port already in use"
socketserver.TCPServer.allow_reuse_address = True
# Class with our Handler. It is a called derived from BaseHTTPRequestHandler
# It means that our class inheritates all his methods and properties
class TestHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
"""This method is called whenever the client invokes the GET method
in the HTTP protocol request"""
# Print the request line
termcolor.cprint(self.requestline, 'green')
# Open the form1.html file
# Read the index from the file
contents = Path('form-1.html').read_text()
# Generating the response message
self.send_response(200) # -- Status line: OK!
# Define the content-type header:
self.send_header('Content-Type', 'text/html')
self.send_header('Content-Length', len(str.encode(contents)))
# The header is finished
self.end_headers()
# Send the response message
self.wfile.write(str.encode(contents))
return
# ------------------------
# - Server MAIN program
# ------------------------
# -- Set the new handler
Handler = TestHandler
# -- Open the socket server
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("Serving at PORT", PORT)
# -- Main loop: Attend the client. Whenever there is a new
# -- clint, the handler is called
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("")
print("Stoped by the user")
httpd.server_close()- Run the server and try with the Browser

In the server's console notice the two request that have been generated by the client:

The first one is for requesting the main page (/):
GET / HTTP/1.1
The second one is for submitting the information from the client
GET /echo?msg=abcdefg HTTP/1.1
There are many different type of inputs elements you can use in your forms. In this HTML example you can see some of them:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>FORM 2</title>
</head>
<body>
<h3>Example of different input elements</h3>
<form action="myserver" method="get">
Text input <input type="text" name="msg">
<br><br>
Check button:
<input type="checkbox" name="chk">
<br><br>
Radio buttons:
<input type="radio" name="base" value="A" checked> A
<input type="radio" name="base" value="C"> C
<input type="radio" name="base" value="T"> T
<input type="radio" name="base" value="G"> G
<br><br>
Options: <br>
Choose operation:
<select name="operation">
<option value="count">Count</option>
<option value="perc">Percentage</option>
</select>
<br>
<input type="submit"/>
</form>
</body>
</html>Save it in the form-2.html file and test it in the Brower. This how it should look:

In this animated gif you can see how it works:

The only way of learning is practicing...
Develop an Echo Server with forms. When you ask the server for the main page (/ resource) it should return a form with a text input and a submit button. When a text message is sent to the echo server, it will generate a response html page that contains the user message. With a link in the bottom it should be possible to return to the main form. The message will be processed though the echo action
If the requested resource is different form / or /echo, the server will return an error page, with a link in the bottom for returning to the form

Modify the echo server for including a check button. When it is checked, the echo should be converted into capital letters

All the exercises and experiments performed during this session should be stored in the Session-14 folder
- Filename: Session-14/webserver-EX01.py
- Description: Program a server, based on webserver4.py that only has a main page (/ resource). If the client request this resource, the server sends the content: "Welcome to my server". But if any other resource is requested, the server should display and error message: "Resource not available"
This is what you should see when the main page is requested:

and this is what is shown when any other page different than the main page is requested:

- Filename: Session-14/webserver-EX02.py
- Description: Modify the previous server so that the main page returned is the index.hmtl from a file. Notice that now there are two ways for reaching the main page: localhost:8080 and localhost:8080/index.html. Both URLs should return the index.html HTML file. If a different resource than the main page is request, the Error.html page should be return (this file was proposed as an exercise in Practice 4)
In this animation you can see how it should behave:

- Filename: Session-14/webserver-EX03.py
- Description: Modify the previous server so that any resource requested from the server is treated as a file. For example, the URL: localhost:8080/myfile.html means that the server will open the the file myfile.html and send it to the client. If the requested file is not available on the server, the Error.html page is sent. Use the Path object from the pathlib python module for opening the files. You will have to catch the FileNotFoundError exemption for knowing if the requested file exist or not
This is an example of how the server should behave:

The session is finished. Make sure, during this week, that everything in this list is checked!
- You have all the items of the session 13 checked!
- Your working repo contains the Session-14 Folder with the following files:
- webserver1.py
- webserver2.py
- webserver3.py
- webserver4.py
- webserver-EX01.py
- webserver-EX02.py
- webserver-EX03.py
- blue.html
- Error.html
- green.html
- index.html
- pink.html
- All the previous files have been pushed to your remote Github repo
- Juan González-Gómez (Obijuan)

- Alvaro del Castillo. He designed and created the original content of this subject. Thanks a lot :-)

S0: Introduction
S1: Tools I
S2: Tools II
S3: Practicing with the tools
S8: Client-Server-1
S9: Client-Server-2
S10: Client-server-3
S11: Client-server-4
S12: HTTP protocol-1
S13: HTTP protocol-2
S14: HTTP module
S15: HTTP module
S16: HTML forms
S17: HTML forms