Updated "Introduction to Python Web Application Homebrew for Slow 3rd Year Web Engineers"

Updated the book

Updated Chapter "Allow multiple HTTP requests to be answered repeatedly" (https://zenn.dev/bigen1925/books/introduction-to-web-application-with-python/viewer/daemonize) ..

If you want to read more, please like the book or follow the author ;-)


The following is an excerpt of the contents of the book.


The problem that the web server can process the request only once

It's time to deal with this issue.

The web servers you have created so far will be terminated as soon as you process a single HTTP request.

Therefore, you have to restart the server every time you want to respond to repeated requests.

It may be troublesome to start the server every time you check the operation during development, but there is also a problem in displaying a general Web page normally.

External files cannot be referenced from HTML

For example, try changing the index.html created in the previous chapter as follows.

study/static/index.html

<!doctype html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>HenaServer</title>
  <link rel="stylesheet" href="index.css">
</head>
<body>
  <img alt="logo" src="logo.png ">
  <h1>Welcome to HenaServer!</h1>
</body>
</html>

https://github.com/bigen1925/introduction-to-web-application-with-python/blob/main/codes/chapter12/static/index.html

Line 6: <link rel =" stylesheet "href =" index.css "> Line 10: <img alt =" logo "src =" logo.png ">

Added.

Common external CSS file reading and image file reading.

Next, prepare a new file in the same directory that you are trying to read.

The contents of the CSS file are as follows.

study/static/index.css

h1 {
    color: red;
}

https://github.com/bigen1925/introduction-to-web-application-with-python/blob/main/codes/chapter12/static/index.css

The image file is here.

study/static/logo.png https://github.com/bigen1925/introduction-to-web-application-with-python/blob/main/codes/chapter12/static/logo.png

The image file can be anything, but in this book it is borrowed from "Irasutoya" ^ [https://www.irasutoya.com/]. You can use any image you like.


As you can see, if it is a normal web page, Chrome will display the logo image, and the text should be displayed in red with CSS applied.

Now, let's start the server and access http: //localhost:8080/index.html in Chrome.

This is not good. No image or CSS is loaded.


When the browser receives the response from the web server, it refers to the external file in the HTML of the response body (<img src =" ">, <script src =" ">, <link href =" "> Etc.), it will try to get the file contents again by resending the request.

However, our web server is unable to handle additional requests (in this case CSS and image requests) because it terminates the program immediately after processing the first request.

Let's take a closer look at that situation.

Chrome has a function called "Developer Tools" that allows you to see the communication results of HTTP requests in detail. We will use that to check the actual state of the request.

On the screen where you accessed http: //localhost:8080/index.html in Chrome earlier, press ctrl + shift + j. (Or right-click on the screen and select Verify to open the Console tab)

As shown in the figure, when I already get index.css and logo.png, I see an error log indicating that the connection with the web server failed. ** **

(Chrome is also designed to make it difficult to get the favicon image without any instructions, and that error is also displayed, but you do not need to worry about it in this book. .)

Next, open the Network tab of the developer tools, * start the server, and then * reload. (The network tab needs to be reloaded as it only displays information for subsequent communications after opening the developer tools)

You can see that Chrome is making a total of 4 communications to display this page. (The content may vary depending on the version and environment,)

Looking at the breakdown, the communication to get index.html was successful (status is 200), and index.css and logo.png failed communication (status``). You can see that isfailed`).

Allows you to handle recurring requests

It turned out that it is not only "just annoying" as it is, but it is not possible to display even one ordinary Web page using CSS, images, JS, etc.

Now let's improve our web server to solve these problems.

Source code

First, we will be able to respond to repeated requests by putting the process of establishing a connection and returning a response inside an infinite loop.

The source code is here.

study/WebServer.py https://github.com/bigen1925/introduction-to-web-application-with-python/blob/main/codes/chapter12/WebServer.py

Commentary

30th line

            while True:

The biggest change is that the entire process from "waiting for a connection from the client" to "terminating the connection" (lines 31-97) has been put into an infinite loop. (If you don't understand the notation of an infinite loop, check it with "python while true".)

It's just one line, but it completes the processing of one request, closes the connection, and then returns to the beginning of the loop and waits for the request again. When the processing of the next request is completed, it returns to the beginning of the loop and waits for the next request.

In other words, the program will continue to handle requests indefinitely until the person who started the program explicitly interrupts the program.

Lines 89-97

                except Exception:
                    #If an exception occurs while processing the request, an error log will be output to the console and
                    #continue processing
                    print("An error occurred while processing the request.")
                    traceback.print_exc()

                finally:
                    #TCP communication is closed regardless of whether an exception occurs or not.
                    client_socket.close()

By the way, I added exception handling.

If you do not handle the exception, the entire program will stop if an exception occurs in the middle of the loop, but by handling it as described above, only the processing of the request being handled at that time will be interrupted, but the program The whole thing will go to the next loop without stopping.

Also, close () of cient_socket is done in the finally clause, not at the end of the try clause. If you do it at the end of the try clause, the disconnection of the connection will be skipped if an exception occurs in the middle.

Try to move

Let's actually move it.

Start the server from the console as usual.


Continue with Book!

Chapter "Allow multiple HTTP requests to be answered repeatedly"

Recommended Posts

Updated "Introduction to Python Web Application Homebrew for Slow 3rd Year Web Engineers"
Updated "Introduction to Python Web Application Homebrew for Slow 3rd Year Web Engineers"
Updated "Introduction to Python Web Application Homebrew for Slow 3rd Year Web Engineers"
Updated "Introduction to Python Web Application Homebrew for Slow 3rd Year Web Engineers"
Updated "Introduction to Python Web Application Homebrew for Slow 3rd Year Web Engineers"
Updated "Introduction to Python Web Application Homebrew for Slow 3rd Year Web Engineers"
[Introduction to Udemy Python3 + Application] 43. for else statement
Introduction to Python For, While
[Introduction to Udemy Python3 + Application] 42. for statement, break statement, and continue statement
[Introduction to Udemy Python 3 + Application] 58. Lambda
[Introduction to Udemy Python 3 + Application] 31. Comments
[Introduction to Udemy Python 3 + Application] 57. Decorator
[Introduction to Udemy Python 3 + Application] 56. Closure
[Introduction to Udemy Python3 + Application] 59. Generator
[Introduction to Udemy Python 3 + Application] Summary
An introduction to Python for non-engineers
[Introduction to Udemy Python3 + Application] 18. List methods
[Introduction to Udemy Python3 + Application] 63. Generator comprehension
[Introduction to Udemy Python3 + Application] 25. Dictionary-type method
[Introduction to Udemy Python3 + Application] 33. if statement
[Introduction to Udemy Python3 + Application] 13. Character method
[Introduction to Udemy Python3 + Application] 55. In-function functions
[Introduction to Udemy Python3 + Application] 48. Function definition
[Introduction to Udemy Python 3 + Application] 10. Numerical values
[Introduction to Udemy Python3 + Application] 41. Input function
[Introduction to Udemy Python3 + Application] 17. List operation
[Introduction to Udemy Python3 + Application] 11. Character strings
[Introduction to Udemy Python3 + Application] 44. range function
[Introduction to Udemy Python3 + Application] 46. Zip function
[Introduction to Udemy Python3 + Application] 24. Dictionary type
[Python] Web application design for machine learning
An introduction to Python for machine learning
[Introduction to Udemy Python3 + Application] 8. Variable declaration
[Introduction to Udemy Python3 + Application] 29. Set method
[Introduction to Udemy Python3 + Application] 16. List type
[Introduction to Udemy Python3 + Application] 61. Dictionary comprehension
[Introduction to Udemy Python 3 + Application] 22. Tuple unpacking
An introduction to Python for C programmers
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
Take the free "Introduction to Python for Machine Learning" online until 4/27 application
Easy-to-understand explanation of Python web application (Django) even for beginners (4) [Routing settings / Introduction to MTV design patterns]
Updated to Python 2.7.9
[Introduction to Udemy Python 3 + Application] 26. Copy of dictionary
[Introduction to Udemy Python3 + Application] 23. How to use tuples
[Introduction to Udemy Python3 + Application] 60. List comprehension notation
[Introduction to Udemy Python 3 + Application] 19. Copy of list
[Introduction to Udemy Python 3 + Application] 38. When judging None
[Introduction to Udemy Python3 + Application] 62. Set comprehension notation
Steps to develop a web application in Python
[Introduction to Udemy Python3 + Application] 64. Namespace and Scope
[Introduction to Udemy Python3 + Application] 67. Command line arguments
Introduction to Programming (Python) TA Tendency for beginners
[Introduction to Udemy Python 3 + Application] 54. What is Docstrings?
[Introduction to Udemy Python3 + Application] 37. Techniques for determining that there is no value
[Introduction to Udemy Python3 + Application] 14. Character substitution 15.f-strings
Understand Python for Pepper development. -Introduction to Python Box-
[Introduction to Udemy Python3 + Application] 35. Comparison operators and logical operators
[Introduction to Udemy Python 3 + Application] 66. Creating your own exceptions
(Python) Try to develop a web application using Django
[Introduction to python] A high-speed introduction to Python for busy C ++ programmers
[Introduction to Udemy Python3 + Application] 53. Dictionary of keyword arguments