Python Pyramid - 包結構



Cookiecutter 工具會在父專案資料夾內自動建立一個同名的包資料夾。該包資料夾包含以下檔案和子資料夾。

__init__.py

一個資料夾需要__init__.py檔案才能被視為 Python 包。testproj 包也包含此檔案,它實際上聲明瞭 Pyramid WSGI 應用專案,以便 development.ini 使用它作為入口點。

應用程式物件由main()函式返回。它透過包含執行 cookiecutter 時選擇的模板庫,包括routes模組,並透過掃描現有包將檢視新增到配置器來配置應用程式登錄檔。以下 Python 程式碼是自動生成的__init__.py檔案。

from pyramid.config import Configurator
def main(global_config, **settings):
   """ This function returns a Pyramid WSGI application.
   """
   with Configurator(settings=settings) as config:
      config.include('pyramid_jinja2')
      config.include('.routes')
      config.include('.models')
      config.scan()
   return config.make_wsgi_app()

routes.py

Cookiecutter 工具會自動生成一個 Python 指令碼,其中包含一個名為includeme()的函式。它添加了一個靜態路由和一個指向 '/' URL 模式的首頁路由。

def includeme(config):
   config.add_static_view('static', 'static', cache_max_age=3600)
   config.add_route('home', '/')

這些路由由上面解釋的__init__.py檔案中的main()函式新增到應用程式配置中。

檢視包

專案包(在本例中為testproj包)包含此檢視子包 - 一個包含空白__init__.py的資料夾,一個名為 default.py 的 Python 模組,其中包含名為my_view()的檢視函式的定義。它將專案的名稱作為上下文傳送到預構建的模板mytemplate.jinja2

from pyramid.view import view_config
from pyramid.response import Response
from sqlalchemy.exc import SQLAlchemyError
from .. import models

@view_config(route_name='home', renderer='testproj:templates/mytemplate.jinja2')
def my_view(request):
   try:
      query = request.dbsession.query(models.MyModel)
      one = query.filter(models.MyModel.name == 'one').one()
   except SQLAlchemyError:
      return Response(db_err_msg, content_type='text/plain', status=500)
   return {'one': one, 'project': 'testproj'}
   
db_err_msg = """\
Pyramid is having a problem using your SQL database.
....
"""

default.py指令碼還匯入models子包中mymodel的定義。此檢視包還在 notfound.py 檔案中定義了一個notfound檢視。

from pyramid.view import notfound_view_config
@notfound_view_config(renderer='testproj:templates/404.jinja2')
def notfound_view(request):
   request.response.status = 404
   return {}

靜態資料夾

testproj包資料夾下的此資料夾包含 Pyramid 徽標檔案和主頁的 theme.CSS。

模板資料夾

我們知道 Web 模板需要儲存在模板資料夾中。此子資料夾包含 jinja2 模板。這裡我們有一個名為layout.jinja2的基本模板,它被mytemplate.jinja2繼承,由my_view()檢視函式呈現。

{% extends "layout.jinja2" %}

{% block content %}
<div class="content">
   <h1><span class="font-semi-bold">Pyramid</span> <span class="smaller">Starter project</span></h1>
   <p class="lead">Welcome to <span class="font-normal">{{project}}</span>, a Pyramid application generated by<br><span class="font-normal">Cookiecutter</span>.</p>
</div>
{% endblock content %}

模型包

tesptproj包資料夾下的此子包包含mymodel.py,其中包含名為MyModel的 SQLAlchemy 模型的定義。

from sqlalchemy import (
   Column,
   Index,
   Integer,
   Text,
)

from .meta import Base
class MyModel(Base):
   __tablename__ = 'models'
   id = Column(Integer, primary_key=True)
   name = Column(Text)
   value = Column(Integer)
Index('my_index', MyModel.name, unique=True, mysql_length=255)

meta.py聲明瞭 SQLAlchemy 中宣告性基類的一個物件。

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import MetaData

NAMING_CONVENTION = {
   "ix": "ix_%(column_0_label)s",
   "uq": "uq_%(table_name)s_%(column_0_name)s",
   "ck": "ck_%(table_name)s_%(constraint_name)s",
   "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
   "pk": "pk_%(table_name)s"
}
metadata = MetaData(naming_convention=NAMING_CONVENTION)
Base = declarative_base(metadata=metadata)
廣告