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

Updated the book

Chapter "You will be able to return" dynamically generated HTML "" The has been updated.

If you want to read more, please "like" or "follow me" in Book ;-)


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


"Static file delivery" and "Dynamic HTML generation"

By now, you can now "generate appropriate headers" (Date, Content-Type, etc.), "parallel processing", and return a response according to the HTTP rules. The part is pretty well organized.

This is almost the end of the step ** "We will prepare the minimum functions as a Web server (= HTTP server)" **.

As a next step, let's take a closer look at ** "What to return as a response body?" **.


The already implemented function of "returning the contents of an HTML file or image file as it is as a response body" is generally called ** "static file delivery" **.

With this feature, you can create, for example, RFC Web Page by IETF. All you have to do is write the content in an HTML file and save it.

However, it is still lacking in functionality to create a home page that you are familiar with.

For example, Professor Maebashi's homepage ^ [I am the author of "Introduction to Web Application Development from the Basics of Learning While Creating a Web Server" that gave me the opportunity to write this book. For more information, it's relatively simple like here] ^ [Sorry Maebashi-sensei. ] I can't even make a homepage yet.

What cannot be made is the so-called "access counter" part as shown below.

The number on the access counter increases as you load the page. How can you achieve this functionality on your current web server?

When the number on the access counter changes, it means that the content of the response body changes. The response body returned from the current web server is the same as the content of the HTML file, so if you want to change the content of the response body, you need to edit the HTML file.

In other words, if you want to provide this function, you need a function to automatically (or manually) edit and save the HTML file every time an HTTP request comes in. This seems too inefficient (although feasible) and annoying.

When that happens, ** "Isn't it easy to generate a different response body each time if you generate it as a Python string instead of getting the response body from a file?" ** It would be natural to think that.

This is called ** "Dynamic HTML Generation" ** (or ** "Dynamic Response Generation" **).

Columns: "Static" and "Dynamic"

The word "static" is quite annoying. Also, the antonym "dynamic" is just as annoying.

"Static" means "things that do not change" and "dynamic" means "things that change", but "** what is static ** for what" and "** what" On the other hand, you should always be aware of what is dynamic **.


For example, "static filedelivery" means "delivery of unchanged file ". What is this a file that doesn't change ** for what?

The HTML file itself can change at all times. Just edit the file with an editor. Even when viewed as a function of the web server, the response body will change if you edit the HTML file.

Some people describe "static file delivery" as "a Web service that" always "returns the same response," but this makes it inaccurate. If you edit the HTML file, the response will change.

The answer is "** Delivery of files whose contents do not change in response to requests". It may be easier to say "deliver a file that does not change its contents upon request".

So when you edit a file, the contents may change.

When I was a junior engineer "But if you edit the HTML file, the response will change, isn't it always the same?" I was confused.


In addition, when describing Javascript, it is sometimes described as "a programming language for providing dynamic content on the Web." "Dynamic content" in this description means "content that ** changes the delivered HTML ** with the passage of time or user interaction" ^ [To be exact, Javascript changes it. It's DOM, not HTML, but it's cute. ].

Once the HTML to be displayed on the browser is sent to the browser as a response, it is basically impossible to change it from the program on the server side. CSS etc. do change the display content of the content (make the text color red), but it does not change the content of the delivered HTML.

However, if you send the program to the browser along with the HTML, the browser can execute the program later to change the delivered HTML. That's Javascript.

If you simply understand "dynamic content" as "changing a web page," "Isn't CSS that changes the color of characters also providing dynamic content?" "Isn't the HTML form tag dynamic because the behavior of the page changes depending on whether or not the button is pressed?" It will be confusing. (I was confused.)


As you can see, the words "static" and "dynamic" are often used, but they are difficult to understand, so always be careful about what changes / does not change.

Create a page that displays the current time

I've given you a little roundabout explanation, but it may be quicker to see the source code for what you want to do.

Let's actually perform "dynamic HTML generation" and create a page whose result changes every time you request it.

To implement the access counter suddenly, you need something like a database that stores the number of past accesses, which is a little troublesome, so for the sake of simplicity, first access the path ** / now to display the current time. Let's create a page that only **.

(Implementing the access counter will be done a little later.)

Source code

Here is the source code that modified workerthread.py to add a page that displays the current time.

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

Commentary

Lines 42-59

            response_body: bytes
            response_line: str
            #path is/When now, generate HTML to display the current time
            if path == "/now":
                html = f"""\
                    <html>
                    <body>
                        <h1>Now: {datetime.now()}</h1>
                    </body>
                    </html>
                """
                response_body = textwrap.dedent(html).encode()

                #Generate response line
                response_line = "HTTP/1.1 200 OK\r\n"

            #If path is otherwise, generate a response from a static file
            else:
                # ...

This is the part I added.

What you are doing ** "If path is / now, generate HTML that displays the current time in python and use it as the response body "** about it.


Here are some supplements about the source code.

            response_body: bytes
            response_line: str

Since the place to substitute response_body and response_line is divided into multiple parts, I decided to make type annotations in advance.

The variable type annotation has the meaning of giving a hint to the editor etc. "This variable is supposed to assign a value of this type". If you write it like this, the editor will warn you in advance if you mistakenly say "substitute str here, substitute bytes here".

                html = f"""\
                    <html>
                    <body>
                        <h1>Now: {datetime.now()}</h1>
                    </body>
                    </html>
                """
                response_body = textwrap.dedent(html).encode()

I am using here document + dedent (). I just want to write ordinary html, but indentation and line breaks have meaning in python, so I am devising it. It's not that difficult, so check it out in "python here-documents", "python dedent", etc.

Try to move

Let's move it now.

After starting the server as usual, try accessing http: // localhost: 8080 / now in Chrome.

It's simple, but did you see a page like the one above?

If you see it, try reloading the page several times. Does the displayed content change each time?


This completes the dynamic HTML generation. It was easy.

Looking back again, the important point of what I did this time is ** "After starting the server, I haven't edited the source code or HTML file at all, but the browser shows different results every time." ** about it.

This is a function that could not be realized by simply outputting the contents of the file as a response body.

Create a page to display the contents of the HTTP request

Since it's a big deal, let's create another dynamic HTML page.

Next, let's add a page called / show_request that displays the contents of the sent HTTP request as it is in HTML.


Continue with Book!

Chapter "You will be able to return" dynamically generated HTML ""

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"
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
Easy-to-understand explanation of Python Web application (Django) even for beginners (5) [Introduction to DB operation with Django shell]
[Introduction to Udemy Python3 + Application] 63. Generator comprehension
[Introduction to Udemy Python3 + Application] 28. Collective type
[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] 21. Tuple type
[Introduction to Udemy Python3 + Application] 45. enumerate function
[Introduction to Udemy Python3 + Application] 41. Input function
[Introduction to Udemy Python3 + Application] 17. List operation
[Introduction to Udemy Python3 + Application] 65. Exception handling
[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
An introduction to self-made Python web applications for a sluggish third-year web engineer
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 Tornado (1): Python web framework started with Tornado
[Introduction to Udemy Python3 + Application] 40.while else statement
[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 Python3 Day 20] Chapter 9 Unraveling the Web (9.1-9.4)
[Introduction to Udemy Python3 + Application] 67. Command line arguments
[Introduction to Udemy Python3 + Application] 9. First, print with print