- Python 3
- CherryPy
- Jinja 2
- JSON database
$ python3 index.py
[03/Nov/2021:09:50:51] ENGINE Listening for SIGTERM.
[03/Nov/2021:09:50:51] ENGINE Listening for SIGHUP.
[03/Nov/2021:09:50:51] ENGINE Listening for SIGUSR1.
[03/Nov/2021:09:50:51] ENGINE Bus STARTING
CherryPy Checker:
The Application mounted at '' has an empty config.
[03/Nov/2021:09:50:51] ENGINE Started monitor thread 'Autoreloader'.
[03/Nov/2021:09:50:51] ENGINE Serving on http://127.0.0.1:8080
[03/Nov/2021:09:50:51] ENGINE Bus STARTEDCherryPy engine is then serving on http://127.0.0.1:8080.
from json import load
import os
import cherrypy
from jinja2 import Environment, FileSystemLoaderCherryPy is an object-oriented web application framework using the Python programming language. It is designed for rapid development of web applications by wrapping the HTTP protocol but stays at a low level and does not offer much more than what is defined in RFC 7231.—Wikipedia: CherryPy
Instances of [the
Environment] class are used to store the configuration and global objects, and are used to load templates from the file system or other locations.
[FileSystemLoader class] Loads templates from the file system. This [builtin] loader can find templates in folders on the file system and is the preferred way to load them.
The loader takes the path to the templates as string...:—jinja2.FileSystemLoader, builtin-loaders
loader=FileSystemLoader(f'{WORKING_DIR}/templates')[json.load deserializes] ...to a Python object using [a] conversion table.—json.load
Class methods called by CherryPy in response to client requests are said to be exposed, which helps describe the @cherrypy.expose() decorator used to modify the index(self) class method.
The Index() class has two class methods:
class Index():
@cherrypy.expose()
def index(self):
template = e.get_template(f'index.html')
return template.render(station_data=self.station_data())
def station_data(self):
with open(f'{WORKING_DIR}/json/stations.json') as json_file:
return load(json_file)The class method index(self) returns the rendered Jinja template, including the deserialized JSON data returned by the station_data() class method.
CherryPy's quickstart() method takes Index() and starts the app if it is ran as a standalone:
if __name__ == '__main__':
cherrypy.quickstart(Index())loop.index was used to enumerate the station list.
Below are a couple of examples of how each successive 3-digit loop.index value could be padded with zeros using format() method:
{{ '%03d' % loop.index }}
{{ '{:03}'.format(loop.index) }}
portend module can be use to find a different
>>> from portend import find_available_local_port
>>> find_available_local_port()
53851Then change the if block:
if __name__ == '__main__':
cherrypy.config.update({'server.socket_port': 53851})
cherrypy.quickstart(Index())