Python Pyramid 简明教程
Python Pyramid - Command Line Pyramid
Pyramid 库有一个 scripts 子包,它包含许多 Python 脚本,这些脚本可用于控制和检查 Pyramid 应用程序。这些模块既可以用作可导入模块,也可用于命令提示符。因此,它们通常被称为命令行脚本。
The Pyramid library has a scripts subpackage, and it contains a number of Python scripts that are made available to control and inspect a Pyramid application. These modules can be used both as an importable module as well as from command prompt. Hence, they are often called as command line scripts.
这些命令行脚本是-
These command line scripts are −
-
pserve − serves a web application that uses a PasteDeploy configuration file.
-
pviews − Displaying Matching Views for a Given URL.
-
pshell − The Interactive Shell.
-
proutes − Displaying All Application Routes.
-
ptweens − Displaying "Tweens".
-
prequest − Invoking a Request.
-
pdistreport − Showing All Installed Distributions and Their Versions.
所有这些命令行脚本都使用 PasteDeploy 配置文件 (development.ini)。
All these command line scripts use the PasteDeploy configuration file (development.ini).
pserve
这是最重要的脚本。在“development.ini”[app:main] 部分配置的 Pyramid 应用程序借助所选服务器(Waitress)和提到的主机和端口(localhost:6543)提供服务。
This is the most important script. The Pyramid application 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).
假设 Pyramid 项目 (testproj) 在 Pyramid 虚拟环境中创建在同名的文件夹中,以下命令开始侦听传入的浏览器请求-
Assuming that the Pyramid project (testproj) is created in the folder of the same name in the Pyramid virtual environment, the following command starts listening to incoming browser requests −
Env>..\scripts\pserve development.ini
pserve 模块(以及其他 Pyramid 命令行脚本)可以用作命令提示符中 Python 解释器的参数运行。
The pserve module (as also the other Pyramid command-line 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
为使 pserve 实用程序更灵活,可以使用以下命令行参数-
To make pserve utility more flexible, the following command line parameters can be used −
-
config_uri − The URI to the configuration file.
-
-n <name> − Load the named application (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.
应用程序提供于 http://localhost:6543 的情况下,访问将受到限制,以致于只有运行在同一机器上的浏览器才能访问。如果您允许网络上其他机器访问,请编辑“development.ini”文件,然后像下面所示替换 [server:main] 部分中的侦听值 −
The application 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 listen value in the [server:main] section as shown below −
[server:main]
use = egg:waitress#main
listen = *:6543
设置 *:6543 等于 0.0.0.0:6543 [::]:6543,结果,应用程序响应系统拥有的所有 IP 地址上的请求,而不仅仅是响应 localhost 的请求。
The setting *:6543 is equivalent to 0.0.0.0:6543 [::]:6543, as a result, the application responds to requests on all IP addresses possessed by your system, not just requests to localhost.
pserve 命令行中的 --reload 选项会在运行代码修改时自动重新加载应用程序。
The --reload option in the pserve command line causes the application to be reloaded automatically whenever the running code is modified.
使用 --reload option. 启动应用程序
Start the application 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
如果对项目的 .py 文件或 .ini 文件进行了任何更改,服务器会自动重启 −
If any change to the project’s .py files or .ini files is made, the server restart automatically −
testproj/development.ini changed; reloading ...
Gracefully killing the server.
Starting monitor for PID 36286.
Starting server in PID 36286.
Serving on http://localhost:6543
Serving on http://localhost:6543
pviews
pviews 命令行脚本用在命令终端窗口中,为给定 URL 匹配的路由和视图打印摘要。 pviews 命令接受两个参数。第一个参数是应用程序的“ini”文件和内置节的路径。格式应为 config_file#section_name (默认值为 main)。第二个参数是要测试匹配视图的 URL。
The pviews command line 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 application’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.
让我们在先前使用 Cookiecutter 构建的 testproj 项目中使用 development.ini 文件执行 pviews 命令。
Let us pviews command with the development.ini file in our testproj project built earlier with Cookiecutter.
Env>..\scripts\pviews 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
输出显示请求的 URL,其下方显示所有匹配的视图及其视图配置详细信息。此示例中只有一个视图匹配,因此只有一个视图部分。
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
pshell 脚本使得可以用 Python 提示符与金字塔应用程序的环境进行交互。此 shell 使用 PasteDeploy 配置文件(如 development.ini)作为命令行参数(类似于其他金字塔脚本),并打开 Python 交互式 shell。
The pshell script makes it possible to interact with the Pyramid application’s environment from Python prompt. This shell uses the PasteDeploy configuration file i.e. development.ini as a command line argument (like the other Pyramid scripts) and opens up Python interactive shell.
Env>..\scripts\pshell 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 application.
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`.
>>>
脚本将读取配置,并将其声明的对象作为 Python 对象用于交互。我们能够检查 Python 提示符中的其行为。
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>
将注册表设置从“development.ini”读入词典。我们可以使用 for 循环遍历其内容 −
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 : sqlite:///…\testproj/testproj.sqlite
retry.attempts : 3
tm.manager_hook : <function explicit_manager at 0x000001D9E64E4550>
甚至有可能借助模型中的 SQLAlchemy 模块与数据库进行交互。
It is even possible to interact with the database with the help of SQLAlchemy model declared in models.py.
当我们首次完成 cookiecutter 步骤时,应用程序数据库最初被初始化。我们在“testproj.sqlite”数据库中发现一个 models 表格,其中有一个记录。
The application database is initialized in the beginning when we first complete the cookiecutter steps. We find a models table in the "testproj.sqlite" database with one record in it.
现在我们按照以下内容从 Python 提示符访问此表格 −
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'
现在我们在 models 表中添加一行。首先声明一个 MyModel 类的对象,并将它添加到 dbsession 中。
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 使用在 pyramid_tm 包中声明的事务管理器对象 tm。要确认新记录已添加,请检索它。
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'
这也可以通过在 SQLite GUI 工具中实际查看数据库的 models 表来确认。
This can also be confirmed by actually looking at the models table of the database in a SQLite GUI tool.
prequest
prequest 实用工具可让你测试 URL 模式的响应,而无需实际启动服务器。命令需要配置文件和 URL 路径作为命令行参数。例如 −
The prequest utility 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 line arguments. For example −
Env>prequest development.ini /
该命令会生成我们之前看到的 Cookiecutter 主页的原始 HTML 响应。
The command produces the raw HTML response of the Cookiecutter homepage that we have seen earlier.
可以使用一些命令行开关。-d 选项显示服务器返回的状态和标题。要覆盖默认的 GET 请求方法,我们可以使用 -m 选项。
There are a couple of command line 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
此命令行 Pyramid 脚本显示所有已添加到你应用程序注册表中的路由。它只接受一个参数,即配置文件 (development.ini)
This command line Pyramid script displays all the routes added to your application’s registry. It accepts just one argument i.e. the configuration file (development.ini)
proutes 命令会显示 testproj 包的以下路由配置 −
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/