How to use template engine in pyramid 1 file application

How to use template engine in pyramid 1 file application

With pyramid, you can create an application from one file as shown in Example of hello world in official document. However, in most cases, there are many patterns of creating a project (pcreate) and starting it from a configuration file (pserve development.ini).

On the other hand, when I find it awkward to create a project, I also want to do it if I can do it with a one-file application. However, there are few examples of one-file applications in the official documentation. It stops at the example of returning a Response object without using the template engine, and there is no description beyond that.

A note on how to use the template engine (e.g. mako, jinja2, chameleon) in a one-file application.

hello world

Quoted from the official documentation. Creating Your First Pyramid Application — The Pyramid Web Framework v1.5.1

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response


def hello_world(request):
    return Response('Hello %(name)s!' % request.matchdict)

if __name__ == '__main__':
    config = Configurator()
    config.add_route('hello', '/hello/{name}')
    config.add_view(hello_world, route_name='hello')
    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 8080, app)
    server.serve_forever()

I want to change the following part.

--Returning a Response object instead of a template engine --For example, I want to use mako. --You need to restart the application to change the html part to the screen

How to use the template engine

Include modules for each template engine

For mako, you need to specify the location of the template's top-level directory.

Perform the settings written in the configuration file with a single file application

If you have created a project, write the application settings in the configuration file (e.g. development.ini). For example, the template engine settings mentioned earlier are written as follows.

mako.directories = appname:templates

I want to set this "mako.directories" even in a single file application. In such a case, pass the dictionary as an argument to the constructor of pyramid.config.Configurator.

In fact, when you create a project, the main function has an argument called settings, which is passed to the constructor.

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    config = Configurator(settings=settings)
    config.include('pyramid_chameleon')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.scan()
    return config.make_wsgi_app()

The .ini file becomes just a dictionary after it is passed, so you can give it a dictionary. The shape is as follows.

if __name__ == '__main__':
    #Make the same hierarchy as the source code of the application the top level hierarchy of the template
    here = os.path.abspath(os.path.dirname(__file__))
    settings = {"mako.directories": [here]}
    config = Configurator()

After that, you can create a one-file application using the template engine by doing the following in the same way as when creating from the project. (Since the template part is divided in the first place, it may not be called a one-file application)

--Register with add_view instead of view_config --treat files ending in ".html" with add_mako_renderer as mako templates

An example of combining these is as follows.

onefile.py

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
import os.path


def hello_world(request):
    return {"name": request.matchdict["name"]}


if __name__ == '__main__':
    here = os.path.dirname(os.path.abspath(__file__))
    settings = {"mako.directories": here,
                "pyramid.reload_all": True}
    config = Configurator(settings=settings)

    config.include("pyramid_mako")
    config.add_mako_renderer(".html")

    config.add_route('hello', '/hello/{name}')
    config.add_view(hello_world, route_name='hello', renderer="hello.html")

    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 8080, app)
    server.serve_forever()

hello.html

Hello ${name}!

For the following, set "pyramid.reload_templates" to True.

--You need to restart the application to change the html part to the screen

Recommended Posts

How to use template engine in pyramid 1 file application
Use jinja2 template in excel file
How to use classes in Theano
How to use SQLite in Python
How to use Mysql in python
How to use ChemSpider in Python
How to use PubChem in Python
[Introduction to Udemy Python 3 + Application] 36. How to use In and Not
How to use calculated columns in CASTable
[Introduction to Python] How to use class in Python?
How to use Google Test in C
How to use Anaconda interpreter in PyCharm
How to use __slots__ in Python class
How to use regular expressions in Python
How to use Map in Android ViewPager
How to use is and == in Python
How to use the C library in Python
[Introduction to Udemy Python3 + Application] 23. How to use tuples
How to use Python Image Library in python3 series
Summary of how to use MNIST in Python
How to use tkinter with python in pyenv
How to read a file in a different directory
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
How to use virtualenv
How to use image-match
How to use shogun
How to use Pandas 2
How to use Virtualenv
How to use numpy.vectorize
How to use pytest_report_header
How to use partial
How to use Bio.Phylo
How to use SymPy
How to use x-means
How to use WikiExtractor.py
How to use IPython
How to use virtualenv
How to use Matplotlib
How to use iptables
How to use numpy
How to use TokyoTechFes2015
How to use venv
How to use dictionary {}
How to use Pyenv
How to use list []
How to use python-kabusapi
How to use OptParse
How to use return
How to use dotenv
How to use pyenv-virtualenv
How to use Go.mod
How to use imutils
How to use import
[For beginners] How to use say command in python!
A memorandum on how to use keras.preprocessing.image in Keras
How to use bootstrap in Django generic class view
How to use the exists clause in Django's queryset
How to use variables in systemd Unit definition files
[Introduction to Udemy Python3 + Application] 27. How to use the dictionary