假設(shè)一個Pyramid虛擬環(huán)境已經(jīng)建立并運(yùn)行,并且Cookiecutter已經(jīng)安裝在其中。創(chuàng)建Cookiecutter項(xiàng)目的最簡單的方法是使用一個預(yù)先建立的啟動模板,按照下面的命令 —
cookiecutter gh:Pylons/pyramid-cookiecutter-starter --checkout 2.0-branch
模板被下載后,用戶被要求選擇項(xiàng)目的名稱。
project_name [Pyramid Scaffold]: testproj
repo_name [testproj]:
然后選擇模板語言。
選擇 template_language –
1 - jinja2
2 - chameleon
3 - mako
Choose from 1, 2, 3 [1]: 1
由于我們對jinja2很熟悉,所以給1作為選擇。接下來,使用SQLALchemy作為后端。
Select backend:
1 - none
2 - sqlalchemy
3 - zodb
Choose from 1, 2, 3 [1]: 2
在 testproj 文件夾內(nèi),創(chuàng)建了以下文件結(jié)構(gòu)
│ development.ini
│ MANIFEST.in
│ production.ini
│ pytest.ini
│ README.txt
│ setup.py
│ testing.ini
│
├───testproj
│ │ pshell.py
│ │ routes.py
│ │ __init__.py
│ │
│ ├───alembic
│ │ │ env.py
│ │ │ script.py.mako
│ │ │
│ │ └───versions
│ │ README.txt
│ │
│ ├───models
│ │ meta.py
│ │ mymodel.py
│ │ __init__.py
│ │
│ ├───scripts
│ │ initialize_db.py
│ │ __init__.py
│ │
│ ├───static
│ │ pyramid-16x16.png
│ │ pyramid.png
│ │ theme.css
│ │
│ ├───templates
│ │ 404.jinja2
│ │ layout.jinja2
│ │ mytemplate.jinja2
│ │
│ └───views
│ default.py
│ notfound.py
│ __init__.py
│
└───tests
conftest.py
test_functional.py
test_views.py
__init__.py
外部 testproj 文件夾有一個內(nèi)部 testproj 包的子文件夾和測試包。內(nèi)部 testproj 子文件夾是一個有模型和腳本、子包、靜態(tài)以及模板文件夾的包。
接下來,使用Alembic初始化和升級數(shù)據(jù)庫。
# Generate your first revision.
alembic -c development.ini revision --autogenerate -m "init"
# Upgrade to that revision.
alembic -c development.ini upgrade head
Alembic是一個輕量級的數(shù)據(jù)庫遷移工具,與SQLAlchemy數(shù)據(jù)庫工具包(Python)一起使用?,F(xiàn)在外部項(xiàng)目文件夾將顯示一個 testproj.sqlite 數(shù)據(jù)庫。
development.ini文件為數(shù)據(jù)庫提供了一個默認(rèn)的數(shù)據(jù)。用下面的命令來填充數(shù)據(jù)庫。
initialize_testproj_db development.ini
Cookiecutter工具也在測試包中生成了測試套件。它們是基于 PyTest 包的。繼續(xù),看看測試是否通過。
Pytest
================ test session starts ======================
platform win32 -- Python 3.10.1, pytest-7.1.2, pluggy-1.0.0
rootdir: F:\pyram-env\testproj, configfile: pytest.ini, testpaths: testproj, tests
plugins: cov-3.0.0
collected 5 items
tests\test_functional.py .. [ 40%]
tests\test_views.py ... [100%]
=============== 5 passed, 20 warnings in 6.66s ===============
Cookiecutter使用Waitress服務(wù)器。Pyramid應(yīng)用程序通過以下命令在localhost的6543端口提供服務(wù):
pserve development.ini
Starting server in PID 67700.
2022-06-19 23:43:51,308 INFO [waitress:485][MainThread] Serving on http://[::1]:6543
2022-06-19 23:43:51,308 INFO [waitress:485][MainThread] Serving on http://127.0.0.1:6543
打開瀏覽器并在其中訪問 http://localhost:6543/ 。The homepage of the newly created project will be displayed as follows ?
調(diào)試工具條
你可以在主頁的右上方找到一個較小的Pyramid標(biāo)志。點(diǎn)擊它可以打開一個新的標(biāo)簽和一個調(diào)試工具欄,提供很多關(guān)于項(xiàng)目的有用信息。
例如,歷史標(biāo)題下的SQLAlchemy標(biāo)簽顯示了SQLAlchemy查詢,顯示了從 development.ini 中默認(rèn)數(shù)據(jù)創(chuàng)建的模型結(jié)構(gòu) 。
全局標(biāo)題又顯示了諸如自省、路由等標(biāo)簽,如下圖所示。點(diǎn)擊 “Routes “標(biāo)簽,可以看到應(yīng)用程序配置中定義的路由和它們的匹配模式。
更多建議: