English 中文(简体)
Creating A Project Manually
  • 时间:2024-12-22

Python Pyramid - Creating A Project Manually


Previous Page Next Page  

The Cookiecutter utipty 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 earper, this is a Setuptools setup file that defines requirements for instalpng 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 apppcation object, and the server configuration. We are going to use the apppcation object in the egg info of hello package, and the Waitress server, pstening 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
psten = localhost:6543

__init__.py

Finally, the apppcation 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 apppcation code having hello_world() view. The main() function registers this view with hello route having / URL pattern, and returns the apppcation 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 apppcation with the help of pserve command.


pserve development.ini --reload
Advertisements