Skip to content

Session 16: HTTP forms

Juan Gonzalez-Gomez edited this page Mar 23, 2020 · 20 revisions

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

Contents

Introduction

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

Our first form

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

Happy web server

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

Type of inputs

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:

Exercises

The only way of learning is practicing...

Exercise 1: Echo Server

  • Filename: Session-16/echo-server-EX01.py
  • Filename: Session-16/form-EX01.html
  • Filename: Session-16/Error.html
  • Description:

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

Exercise 2: Echo server with check button

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

END of the session

The session is finished. Make sure, during this week, that everything in this list is checked!

  • You have all the items of the session 15 checked!
  • Your working repo contains the Session-16 Folder with the following files:
    • form-server1.py
    • form-1.html
    • form-2.html
    • echo-server-EX01.py
    • form-EX01.html
    • Error.html
    • echo-server-EX02.py
    • form-EX02.html
  • All the previous files have been pushed to your remote Github repo

Author

Credits

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

License

Links

Clone this wiki locally