English 中文(简体)
Command Line Pyramid
  • 时间:2024-12-22

Python Pyramid - Command Line Pyramid


Previous Page Next Page  

The Pyramid pbrary has a scripts subpackage, and it contains a number of Python scripts that are made available to control and inspect a Pyramid apppcation. These modules can be used both as an importable module as well as from command prompt. Hence, they are often called as command pne scripts.

These command pne scripts are −

    pserve − serves a web apppcation that uses a PasteDeploy configuration file.

    pviews − Displaying Matching Views for a Given URL.

    pshell − The Interactive Shell.

    proutes − Displaying All Apppcation Routes.

    ptweens − Displaying "Tweens".

    prequest − Invoking a Request.

    pdistreport − Showing All Installed Distributions and Their Versions.

All these command pne scripts use the PasteDeploy configuration file (development.ini).

pserve

This is the most important script. The Pyramid apppcation configured in the "development.ini" [app:main] section is served with the help of the chosen server (Waitress) and the mentioned host and port (localhost:6543).

Assuming that the Pyramid project (testproj) is created in the folder of the same name in the Pyramid virtual environment, the following command starts pstening to incoming browser requests −


Env>..scriptspserve development.ini

The pserve module (as also the other Pyramid command-pne scripts) can be run as an argument of Python interpreter in the command prompt.


Env>python -m pyramid.scripts.pserve development.ini
Starting server in PID 1716.
2022-06-23 14:13:51,492 INFO [waitress:485][MainThread] Serving on http://[::1]:6543
2022-06-23 14:13:51,492 INFO [waitress:485][MainThread] Serving on http://127.0.0.1:6543

To make pserve utipty more flexible, the following command pne parameters can be used −

    config_uri − The URI to the configuration file.

    -n <name> − Load the named apppcation (default main).

    -s <server_type> − Use the named server.

    --server-name <section_name> − Use the named server as defined in the configuration file (default: main)

    --reload − Use auto-restart file monitor.

    -b − Open a web browser to the server url.

The apppcation is served at http://localhost:6543 in which case, the access is restricted such that only a browser running on the same machine. If you want to let the other machines on the same network, then edit the "development.ini" file, and replace the psten value in the [server:main] section as shown below −


[server:main]
use = egg:waitress#main
psten = *:6543

The setting *:6543 is equivalent to 0.0.0.0:6543 [::]:6543, as a result, the apppcation responds to requests on all IP addresses possessed by your system, not just requests to localhost.

The --reload option in the pserve command pne causes the apppcation to be reloaded automatically whenever the running code is modified.

Start the apppcation with --reload option.


pserve development.ini --reload
Starting monitor for PID 36224.
Starting server in PID 36224.
Serving on http://localhost:6543
Serving on http://localhost:6543

If any change to the project s .py files or .ini files is made, the server restart automatically −


testproj/development.ini changed; reloading ...
Gracefully kilpng the server.
Starting monitor for PID 36286.
Starting server in PID 36286.
Serving on http://localhost:6543
Serving on http://localhost:6543

pviews

The pviews command pne script is used in the command terminal window to print a summary of matching routes and views for a given URL. The pviews command accepts two arguments. The first argument is the path to your apppcation s ".ini" file and section name inside it. This should be of the format config_file#section_name (default value is main). The second argument is the URL to test for matching views.

Let us pviews command with the development.ini file in our testproj project built earper with Cookiecutter.


Env>..scriptspviews development.ini /
URL = /
   context: <pyramid.traversal.DefaultRootFactory object at 0x000001DD39BF1DE0>
   view name:
   Route:
   ------
   route name: home
   route pattern: /
   route path: /
   subpath:
   
      View:
      -----
      testproj.views.default.my_view

The output shows the requested URL at the top and below which all the matching views are displayed with their view configuration details. In this example only one view matches, so there is just a single View section.

pshell

The pshell script makes it possible to interact with the Pyramid apppcation s environment from Python prompt. This shell uses the PasteDeploy configuration file i.e. development.ini as a command pne argument (pke the other Pyramid scripts) and opens up Python interactive shell.


Env>..scriptspshell development.ini
Python 3.10.1 (tags/v3.10.1:2cd268a, Dec 6 2021, 19:10:37) [MSC v.1929 64 bit (AMD64)] on win32
Type "help" for more information.

Environment:
   app                    The WSGI apppcation.
   dbsession              <sqlalchemy.orm.session.Session object at 0x0000020E9F1452D0>
   models                 <module  testproj.models  from  f:\pyram-env\testproj\testproj\models\__init__.py >
   registry               Active Pyramid registry.
   request                Active request object.
   root                   Root of the default resource tree.
   root_factory           Default root factory used to create `root`.
   tm                     Single-thread implementation of `~transaction.interfaces.ITransactionManager`.
   
>>>

The script reads the configuration and the objects declared in it are made available as Python objects to interact with. We can inspect their behaviour from the Python prompt.


>>> root
<pyramid.traversal.DefaultRootFactory object at 0x0000020E9E2507F0>
>>> registry
<Registry testproj>

The registry settings are read from "development.ini" into a dictionary. We can traverse its contents using the for loop −


>>> for k,v in registry.settings.items():
... print (k,":",v)
...
pyramid.reload_templates : True
pyramid.debug_authorization : False
pyramid.debug_notfound : False
pyramid.debug_routematch : False
pyramid.default_locale_name : en
pyramid.includes :
pyramid_debugtoolbar
sqlalchemy.url : sqpte:///…	estproj/testproj.sqpte
retry.attempts : 3
tm.manager_hook : <function exppcit_manager at 0x000001D9E64E4550>

It is even possible to interact with the database with the help of SQLAlchemy model declared in models.py.

The apppcation database is initiapzed in the beginning when we first complete the cookiecutter steps. We find a models table in the "testproj.sqpte" database with one record in it.

Testproj

We now access this table from the Python prompt as under −


>>> m=models.MyModel

>>> obj=dbsession.query(m).get(1)
>>> obj
<testproj.models.mymodel.MyModel object at 0x0000020E9FD96DA0>
>>> obj.name
 one 

Let us adda new row in the models table. First declare an object of the MyModel class, and add it in the dbsession.


>>> tm.begin()
>>> obj=models.MyModel(id=2, name= two , value=2)
>>> dbsession.add(obj)
>>> tm.commit()

Pyramid uses a transaction manger object tm which is declared in pyramid_tm package. To confirm that a new record is added, retrieve it back.


>>> obj=dbsession.query(models.MyModel).get(2)
>>> obj.name
 two 

This can also be confirmed by actually looking at the models table of the database in a SQLite GUI tool.

SQLite

prequest

The prequest utipty lets you to test the response of a URL pattern without actually starting the server. The command needs the configuration file and the URL path as the command pne arguments. For example −


Env>prequest development.ini /

The command produces the raw HTML response of the Cookiecutter homepage that we have seen earper.

There are a couple of command pne switches that can be used. The -d option displays the status and headers returned by the server. To override the default GET request method, we can use -m option.

proutes

This command pne Pyramid script displays all the routes added to your apppcation s registry. It accepts just one argument i.e. the configuration file (development.ini)

Following route configuration of the testproj package is displayed by the proutes command −


Env>proutes development.ini
Name                       Pattern                                                        View
----                       -------                                                        ----
__static/                  /static/*subpath                                               testproj:static/
home                       /                                                              testproj.views.default.my_view
debugtoolbar               /_debug_toolbar/*subpath                                       <unknown>
__/_debug_toolbar/static/  /_debug_toolbar/static/*subpath pyramid_debugtoolbar:static/
Advertisements