Let's make a web framework with Python! (2)

Let's load the template and display it!

It's not very elegant to write a program for each page to be displayed and write HTML code in it. So, I would like to make it until the template is read and displayed.

Get the project root!

When creating a framework, I want to divide it into class files for each function. At that time, when creating and operating the class autoload, set it to some extent in the configuration file. There is also a method of writing in an ini file, but since I want to operate the created project at the deployment destination without editing, specify the project root directory and specify the location of the setting file based on it. So, first, describe the implementation for specifying the project root directory.

The directory structure this time is as follows. +PROJECR_ROOT ++app | +app | + templates (template file storage location) | + index.tpl (template file) ++public | + index.py (program body) | +uwsgi.ini | +uwsgi.pid |+uwsgi.log +templates + index.tpl (template file) You can get the directory one level above the public directory, that is, the project root directory by writing as follows.

index.py (excerpt)


    project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    logger.info('project_root:' + project_root)

Now you can get the route directory of your project.

Load the template file!

Now that the project root directory has been identified, we will specify the location of the configuration file and template file from this point. The full path of the file will be decided later, including the name of the controller, but for the time being, PROJEC_ROOT / app / templates / index.tpl is read. In the Framework created this time, the loaded template is saved in an array, read line by line, interpreted and displayed, so in order to improve the visibility of the program source, the View creation method and the file reading method are separated. The file read method reads the file and returns the result as a list type to the View creation method, the View creation method concatenates it to an array string and returns it to the application method, and returns View from application to uwsgi. The code is below.

index.py


# index.py
# coding:utf-8
import logging
import datetime
import uuid
import os, sys

handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger = logging.getLogger()
logger.addHandler(handler)
logger.setLevel(logging.INFO)
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

def main():
    # log
    logger.info('test-log-dayo')

def application(env, start_response):
    main()
    logger.info('project_root:' + project_root)
    start_response('200 OK', [('Content-type', 'text/html')])
    str = createView('index.tpl')
    return [str.encode("utf-8")]

def createView(file_name):
    arr = readTemplate(project_root + '/app/templates/' + file_name)
    str = ""

    for line in arr:
        str = str + line

    return str

def readTemplate(file_name):
    f = open(file_name, 'r')
    arr = []
    for line in f:
        arr.append(line)
    
    f.close()
    return arr

With this, if the contents of the template are displayed like "Hello World !!!" on the browser, it is successful.

Recommended Posts

Let's make a web framework with Python! (1)
Let's make a web framework with Python! (2)
Let's make a GUI with python.
Let's make a graph with python! !!
Let's make a shiritori game with Python
Let's make a voice slowly with Python
Let's make a Twitter Bot with Python!
Make a fortune with Python
Let's replace UWSC with Python (5) Let's make a Robot
Let's make a web chat using WebSocket with AWS serverless (Python)!
[Let's play with Python] Make a household account book
Let's make a simple game with Python 3 and iPhone
[Super easy] Let's make a LINE BOT with Python.
Let's make a breakout with wxPython
Let's make a supercomputer with xCAT
If you want to make a discord bot with python, let's use a framework
Install Python as a Framework with pyenv
Let's create a free group with Python
Let's make a simple language with PLY 1
[Python] A quick web application with Bottle!
[Python] Let's make matplotlib compatible with Japanese
Run a Python web application with Docker
Let's make a tic-tac-toe AI with Pylearn 2
Let's make a combination calculation in Python
If you know Python, you can make a web application with Django
Let's make a WEB application for phone book with flask Part 1
Let's make a WEB application for phone book with flask Part 2
Let's make a WEB application for phone book with flask Part 3
Let's make a WEB application for phone book with flask Part 4
Django python web framework
Make a Twitter trend bot with heroku + Python
Introduction to Tornado (1): Python web framework started with Tornado
Try to make a "cryptanalysis" cipher with Python
[Python] Make a simple maze game with Pyxel
Launch a web server with Python and Flask
Try to make a dihedral group with Python
Let's do web scraping with Python (weather forecast)
Let's make a module for Python using SWIG
Let's do web scraping with Python (stock price)
Extract data from a web page with Python
[Ev3dev] Let's make a remote control program by Python with RPyC protocol
[Streamlit] I hate JavaScript, so I make a web application only with Python
Implement a simple application with Python full scratch without using a web framework.
Make one repeating string with a Python regular expression.
Let's make a Discord Bot.
Web scraping with python + JupyterLab
Let's make an A to B conversion web application with Flask! From scratch ...
Try to make a command standby tool with python
[Practice] Make a Watson app with Python! # 2 [Translation function]
[Practice] Make a Watson app with Python! # 1 [Language discrimination]
Let's make Othello with wxPython
Make a breakpoint on the c layer with python
Launch a Python web application with Nginx + Gunicorn with Docker
Make Puyo Puyo AI with Python
Web API with Python + Falcon
Let's make dice with tkinter
Make a bookmarklet in Python
Let's make dependency management with pip a little easier
[For play] Let's make Yubaba a LINE Bot (Python)
Let's write python with cinema4d.
Make a CSV formatting tool with Python Pandas PyInstaller