Python Pyramid - Creating A Project Manually



The Cookiecutter utility uses pre-defined project templates to auto-generate the project and package structure. For complex projects, it saves a lot of manual effort in properly organizing various project components.

However, a Pyramid project can be built manually without having to use Cookiecutter. In this section, we shall see how a Pyramid project named Hello is built in following easy steps.

setup.py

Create a project directory within Pyramid virtual environment.

md hello
cd hello

And save the following script as setup.py

from setuptools import setup

requires = [
   'pyramid',
   'waitress',
]
setup(
   name='hello',
   install_requires=requires,
   entry_points={
      'paste.app_factory': [
         'main = hello:main'
      ],
   },
)

As mentioned earlier, this is a Setuptools setup file that defines requirements for installing dependencies for your package.

Run the following command to install the project and generate the 'egg' in the name hello.egg-info.

pip3 install -e.

development.ini

Pyramid uses PasteDeploy configuration file mainly to specify the main application object, and the server configuration. We are going to use the application object in the egg info of hello package, and the Waitress server, listening on port 5643 of the localhost. Hence, save the following snippet as development.ini file.

[app:main]
use = egg:hello

[server:main]
use = egg:waitress#main
listen = localhost:6543

__init__.py

Finally, the application code resides in this file which is also essential for the hello folder to be recognised as a package.

The code is a basic Hello World Pyramid application code having hello_world() view. The main() function registers this view with hello route having '/' URL pattern, and returns the application object given by make_wsgi_app() method of Configurator.

from pyramid.config import Configurator
from pyramid.response import Response
def hello_world(request):
   return Response('<body><h1>Hello World!</h1></body>')
def main(global_config, **settings):
   config = Configurator(settings=settings)
   config.add_route('hello', '/')
   config.add_view(hello_world, route_name='hello')
   return config.make_wsgi_app()

Finally, serve the application with the help of pserve command.

pserve development.ini --reload
Advertisements