Python Pyramid - 建立專案



假設Pyramid虛擬環境已啟動並執行,並且Cookiecutter已安裝在其中。建立Cookiecutter專案最簡單的方法是使用預構建的入門模板,如下命令所示:

cookiecutter gh:Pylons/pyramid-cookiecutter-starter --checkout 2.0-branch

模板下載後,會詢問使用者專案名稱的選擇:

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**資料夾內,建立了以下檔案結構:

│ 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**資料夾包含內部**testproj**包子資料夾和測試包。內部**testproj**子資料夾是一個包,包含模型和指令碼、子包以及靜態和模板資料夾。

接下來,使用Alembic初始化和升級資料庫。

# Generate your first revision.
alembic -c development.ini revision --autogenerate -m "init"
# Upgrade to that revision.
alembic -c development.ini upgrade head

Alembic是一個輕量級的資料庫遷移工具,用於Python的SQLAlchemy資料庫工具包。外部專案資料夾現在將顯示一個**testproj.sqlite**資料庫。

development.ini檔案為資料庫提供預設資料。使用以下命令填充資料庫:

initialize_testproj_db development.ini

Cookiecutter實用程式還在tests包中生成測試套件。它們基於**PyTest**包。繼續看看測試是否透過。

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伺服器。Pyramid應用程式透過以下命令在localhost的6543埠上提供服務:

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

開啟瀏覽器並在其中訪問**https://:6543/**。將顯示新建立專案的首頁,如下所示:

Cookiecutter

除錯工具欄

您可以在首頁右上角找到一個較小的Pyramid徽標。單擊它以開啟一個新標籤頁和一個除錯工具欄,該工具欄提供有關專案的大量有用資訊。

例如,歷史記錄下的SQLAlchemy選項卡顯示SQLAlchemy查詢,顯示從**development.ini**中的預設資料建立的模型的結構。

Pyramid logo

全域性標題再次顯示諸如內省、路由等選項卡,如下所示。單擊“路由”選項卡以檢視在應用程式配置中定義的路由及其匹配模式。

Debug Toolbar
廣告