Try using the Python web framework Tornado Part 2

Introduction

I've been playing with Tornado recently, so I'll show you how to use it.

This time, I will use a template. I just tried using it, but I didn't explain much. Expect next time. If you have any questions or requests, we will answer them.

Execution environment

My execution environment is as follows, but I think that there is no problem if it is an environment where Python works.

Related article

What is a template engine?

The template engine is a mechanism that synthesizes a template (template) and input data to create a character string. This time I'll limit myself to the web template engine in Python. In this case, the template engine is a mechanism that partially embeds Python code inside an HTML template and finally generates HTML. If you want to know a little difficult thing, you can refer to the following Wikipedia article or search on Google.

Tornado template engine

Seeing is believing, so let's start with an example using a template engine. Last time Let's modify the index.html used. The directory structure is the same as that of Last time. It's a very boring example, but let's display the current time.

code

The changes from the last time are as follows.

<!DOCTYPE html>
<html>
  <head>
    <title>Hello, world</title>
    <link rel="stylesheet" href="{{ static_url("style.css") }}"/>
    {% from datetime import datetime %}
  </head>
  <body>
    <div id="container">
      <div id="main">
          <p>Hello, world</p>
          <p>{{datetime.now()}}</p>
      </div>
    </div>
  </body>
</html>

Execution example

You can get the current time by accessing it with a browser. helloworld.png

Commentary

In Python, the following code, which is familiar, is simply written directly in HTML by enclosing it in {% and%} (or {{and}}).

#Import datetime from datetime module
from datetime import datetime
# datetime.Get the current time with the now method
datetime.now()

It's late, but last time I used it a lot.

{{ static_url("style.css") }}

Was also a feature of the template engine.

It is replaced with the result of evaluating the character string enclosed in {% and%} (or {{and}}). It's easy. Tornado's template engine basically encloses Python code in {% and%} (or {{and}}) in an HTML file, and the evaluation result is embedded in the HTML.

You can also write control structures such as for, while, if, try-cxcept.

You can also define variables in the template.

I'll summarize it more properly later, but if you want to know more, see the Tornado manual tornado.template — Flexible output generation. Please give me.

Display the calculation result of the server program

From here, I will explain how to receive the calculation result of the server program (server.py). I will explain the post () method and get () method from the next time onward, so I will use it for the time being. Let's write a program that counts the number of characters that will be taken care of during job hunting.

Directory structure

$ tree --charset=x
.
|-- server.py
|-- static
|   `-- style.css
`-- templates
    |-- index.html
    `-- result.html

code

The result of the POST request issued by index.html is received by the post () method, and the variable len_body is passed to result.html and displayed. It looks like a boring example, but if you can do it so far, you should be able to write Web applications in the heyday of CGI because you can pass calculation results by Python.

server.py


#!/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")

    def post(self):
        body = self.get_argument('body')

        len_body = len(body)

        self.render("result.html",
                    len_body = len_body
                    )


application = tornado.web.Application([
    (r"/", MainHandler)
    ],
    template_path=os.path.join(os.getcwd(),  "templates"),
    static_path=os.path.join(os.getcwd(),  "static"),
)

if __name__ == "__main__":
    application.listen(8888)
    print("Server is up ...")
    tornado.ioloop.IOLoop.instance().start()

Delete the style attached to the p tag.

style.css


body {
  font-family:'Lucida Grande', 'Hiragino Kaku Gothic ProN', 'Hiragino Kakugo ProN W3', "MS Gothic", sans-serif;
  width: 80%;
  margin: 0 auto;
}

Display the screen for entering the character string for which you want to calculate the number of characters in index.html.

index.html


<!DOCTYPE html>
<html>
  <head>
    <title>Character count</title>
    <link rel="stylesheet" href="{{ static_url("style.css") }}"/>
  </head>
  <body>
    <div id="container">
      <div id="main">
        <form method="post" action="/">
          <textarea name="body" cols="40" rows="4"></textarea>
          <input type="submit">
        </form>
      </div>
    </div>
  </body>
</html>

Display the calculation result in result.html.

result.html


<!DOCTYPE html>
<html>
  <head>
    <title>Character count</title>
    <link rel="stylesheet" href="{{ static_url("style.css") }}"/>
  </head>
  <body>
    <div id="container">
      <div id="main">
          <p>{{len_body}}</p>
      </div>
    </div>
  </body>
</html>

Execution example

Certainly the number of characters could be counted. (The number of characters may vary depending on the environment.) helloworld.png helloworld.png

Next schedule

Extends the character count. If you feel like it, you may even write a similarity search by TF / IDF.

Recommended Posts

Try using the Python web framework Tornado Part 2
Try using the Python web framework Django (2) --Look at setting.py
Try using the web application framework Flask
Try using the Python web framework Django (1)-From installation to server startup
Try using the Python Cmd module
Try using the Wunderlist API in Python
Try using the Kraken API in Python
I tried the Python Tornado Testing Framework
Django python web framework
Introduction to Tornado (1): Python web framework started with Tornado
Try using the BitFlyer Ligntning API in Python
Python: Try using the UI on Pythonista 3 on iPad
Try using the collections module (ChainMap) of python3
Try using Tweepy [Python2.7]
Try using the DropBox Core API in Python
Explanation of the concept of regression analysis using python Part 2
Cut a part of the string using a Python slice
(Python) Try to develop a web application using Django
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
Explanation of the concept of regression analysis using Python Part 1
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 3 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 4 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 5 ~
[Python] Try using Tkinter's canvas
Try using Kubernetes Client -Python-
Try using SQLAlchemy + MySQL (Part 1)
Try using SQLAlchemy + MySQL (Part 2)
Web scraping using Selenium (Python)
Try using the PeeringDB 2.0 API
Python beginners publish web applications using machine learning [Part 1] Introduction
Try a similar search for Image Search using the Python SDK [Search]
[Part.2] Crawling with Python! Click the web page to move!
[CleanArchitecture with Python] Part2: Frameworks & Drivers Layer: Introducing the Web
Operate your browser using the Selenium Web Driver Python bindings
Try using Pillow on iPython (Part 1)
Try using Pleasant's API (python / FastAPI)
Try using Pillow on iPython (Part 3)
Extract the targz file using python
Try using Python argparse's action API
Install Python framework django using pip
Try using Leap Motion in Python
Try using Amazon DynamoDB from Python
Try to analyze online family mahjong using Python (PART 1: Take DATA)
Visualize your pocket money files with the Python web framework Dash
Try using FireBase Cloud Firestore in Python for the time being
Introducing the BOT framework Minette for Python
GUI creation in python using tkinter part 1
Try mathematical formulas using Σ with python
Behind the flyer: Using Docker with Python
Try using the $ 6 discount LiDAR (Camsense X1)
Try using the HL band in order
[Beginner] Python web scraping using Google Colaboratory
Try using the camera with Python's OpenCV
Try using Dialogflow (formerly API.AI) Python SDK #dialogflow
Web-WF Python Tornado Part 3 (Introduction to Openpyexcel)
Tweet using the Twitter API in Python
Try using Junos On-box Python # 2 Commit Script
Try cluster analysis using the K-means method
Development and deployment of REST API in Python using Falcon Web Framework
[Python] Try pydash of the Python version of lodash