(機械翻訳)基本レイアウト

`` zodb`` cookiecutterによって生成されるスターターファイルは非常に基本的ですが、最も一般的な用語である `` traversal``(and:term: `ZODB`ベース) :app: `Pyramid`プロジェクト。

`` __init __。py``によるアプリケーション構成

ディスク上のディレクトリは `` __init __。py``ファイルを含むことで、Python:term: package`に変換することができます。たとえ空であっても、これはディレクトリをPythonパッケージとしてマークします。 ` __init __。py``はパッケージのディレクトリを示すマーカーとして、そしてアプリケーションの設定コードを格納するためのマーカーとして使われます。

`` development.ini``生成された設定ファイルを使って `` pserve``コマンドを使ってアプリケーションを実行すると、アプリケーションの設定は `` egg:tutorial``と記述されたsetuptools *エントリポイントを指しています。私たちのアプリケーションでは、アプリケーションの `` setup.py``ファイルがこう言っているので、このエントリポイントは `` __init __。py``という名前のファイル内の `` main``関数です。

``チュートリアル/ __ init __。py``を開きます。それはすでに以下を含んでいるはずです:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from pyramid.config import Configurator
from pyramid_zodbconn import get_connection
from .models import appmaker


def root_factory(request):
    conn = get_connection(request)
    return appmaker(conn.root())


def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    settings['tm.manager_hook'] = 'pyramid_tm.explicit_manager'
    with Configurator(settings=settings) as config:
        config.include('pyramid_chameleon')
        config.include('pyramid_tm')
        config.include('pyramid_retry')
        config.include('pyramid_zodbconn')
        config.set_root_factory(root_factory)
        config.add_static_view('static', 'static', cache_max_age=3600)
        config.scan()
        return config.make_wsgi_app()
  1. Lines 1-3. Perform some dependency imports.
  2. *ライン6-8 *。 Pyramidアプリケーションのための:term: `root factory`を定義してください。
  3. Line 11. __init__.py defines a function named main.
  4. Line 14. Use an explicit transaction manager for apps so that they do not implicitly create new transactions when touching the manager outside of the pyramid_tm lifecycle.
  5. Line 15. Construct a Configurator as a context manager with the settings keyword parsed by PasteDeploy.
  6. Line 16. Include support for the Chameleon template rendering bindings, allowing us to use the .pt templates.
  7. Line 17. Include support for pyramid_tm, allowing Pyramid requests to join the active transaction as provided by the transaction package.
  8. Line 18. Include support for pyramid_retry to retry a request when transient exceptions occur.
  9. Line 19. Include support for pyramid_zodbconn, providing integration between ZODB and a Pyramid application.
  10. Line 20. Set a root factory using our function named root_factory.
  11. ライン21 *。 :meth: `pyramid.config.Configurator.add_static_view`メソッドを使ってURLパスが` `/ static``で始まるリクエストに答える"スタティックビュー"を登録します。このステートメントは、CSSや画像ファイルなどの静的アセットを表示するビューを、この場合はhttp:// localhost:6543 / static / ``以下に登録します。最初の引数は"name " `` static``であり、ビューのURLパス接頭辞は `` / static``であることを示します。このタグの2つ目の引数は、相対パス:term: `asset specification`である" path "です。したがって、` `tutorial``パッケージ内の` `static``ディレクトリ内でサービスする必要があるリソースを見つけます。あるいは、cookiecutterはパスとして( tutorial:static`)*絶対*資産指定を使用することができました。
  12. Line 22. Perform a scan. A scan will find configuration decoration, such as view configuration decorators (e.g., @view_config) in the source code of the tutorial package and will take actions based on these decorators. We don't pass any arguments to scan(), which implies that the scan should take place in the current package (in this case, tutorial). The cookiecutter could have equivalently said config.scan('tutorial'), but it chose to omit the package name argument.
  13. Line 23. Use the pyramid.config.Configurator.make_wsgi_app() method to return a WSGI application.

`` models.py``を使ったリソースとモデル

:app: Pyramid`は:term: resource`という単語を使って階層的に配列されたオブジェクトを記述します。このツリーは:term: traversal`によって参照され、URLをコードにマップします。このアプリケーションでは、リソースツリーはサイト構造を表しますが、各リソースは:term: `ZODB`データベースに永続的に格納されているため、アプリケーションの:term: domain model`も表します。 `` models.py``ファイルは、 `` zodb`` cookiecutterが私たちのリソースオブジェクトを実装するクラスを置くところです。それぞれはドメインモデルオブジェクトです。

`` models.py``のソースは次のとおりです:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from persistent.mapping import PersistentMapping


class MyModel(PersistentMapping):
    __parent__ = __name__ = None


def appmaker(zodb_root):
    if 'app_root' not in zodb_root:
        app_root = MyModel()
        zodb_root['app_root'] = app_root
    return zodb_root['app_root']
  1. Lines 4-5. The MyModel resource class is implemented here. Instances of this class are capable of being persisted in ZODB because the class inherits from the persistent.mapping.PersistentMapping class. The __parent__ and __name__ are important parts of the traversal protocol. By default, set these to None to indicate that this is the root object.

  2. Lines 8-12. appmaker is used to return the application root object. It is called on every request to the Pyramid application. It also performs bootstrapping by creating an application root (inside the ZODB root object) if one does not already exist. It is used by the root_factory we've defined in our __init__.py.

    ブートストラップは、データベースに永続的なアプリケーションルートがあるかどうか最初に確認することによって行われます。そうでない場合は、インスタンスを作成して格納し、トランザクションをコミットします。次に、アプリケーションルートオブジェクトを返します。

`` views.py``によるビュー

私たちのcookiecutterはデフォルトで `` views.py``を生成しました。これは単一のビューを含み、 `` http:// localhost:6543 / ``というURLにアクセスしたときに表示されるページをレンダリングするために使用されます。

`` views.py``のソースは次のとおりです:

1
2
3
4
5
6
7
from pyramid.view import view_config
from .models import MyModel


@view_config(context=MyModel, renderer='templates/mytemplate.pt')
def my_view(request):
    return {'project': 'myproj'}

このモジュールのコンポーネントを理解しようとしましょう:

  1. Lines 1-2. Perform some dependency imports.

  2. Line 5. Use the pyramid.view.view_config() configuration decoration to perform a view configuration registration. This view configuration registration will be activated when the application is started. It will be activated by virtue of it being found as the result of a scan (when Line 14 of __init__.py is run).

    `` @ view_config``デコレータはいくつかのキーワード引数を受け取ります。ここでは、 `` context``と `` renderer``の2つのキーワード引数を使用します。

    `` context``引数は、 `` traversal``が `` tutorial.models.MyModel``:term: resource`を:term: context`にするときにのみ呼び出し可能な装飾ビューcallableを実行する必要があることを意味します。要求の英語では、 `` MyModel``がルートモデルであるため、URL `` / ``が訪れたときに、このビューを呼び出すことができます。

    `` renderer``引数は、 `` templates / mytemplate.pt``の `` asset specification``という名前です。この資産指定は、 `` tutorial``パッケージの `` templates``ディレクトリ内の `` mytemplate.pt``ファイルに存在するa:term: Chameleon`テンプレートを指しています。また、このパッケージの ` templates``ディレクトリを見ると、 `` mytemplate.pt``テンプレートファイルが表示され、生成されたプロジェクトのデフォルトのホームページをレンダリングします。この資産の仕様は* relative *(現在のview.pyのパッケージ)です。あるいは、絶対的な資産の仕様「tutorial:templates / mytemplate.pt」を使用することもできましたが、相対バージョンを使用することを選択しました。

    `` @ view_config``へのこの呼び出しは `` name``引数を渡さないので、それが装飾する `` my_view``関数は、コンテキストが ` MyModel`

  3. *ライン6-7 *。私たちは上記のステップで飾った:term: view callable`を my_view``と定義します。この呼び出し可能なビューは ` zodb`` cookiecutterによって生成され、 `` request``が与えられ、辞書を返す*関数*です。上記のステップでアセット仕様で指定された `` mytemplate.pt`:term: renderer`は、この辞書を私たちに代わって:term: response`に変換します。

    この関数は辞書 `` {'project': 'tutorial'} ``を返します。この辞書は、 "mytemplate.pt"の資産指定で指定されたテンプレートによって使用され、ページ上の特定の値を入力します。

`` development.ini``の設定

``チュートリアル :チュートリアル チュートリアル チュートリアル ではなく チュートリアル `development.ini``は以下のようになります:

###
# app configuration
# https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/environment.html
###

[app:main]
use = egg:tutorial

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

zodbconn.uri = file://%(here)s/Data.fs?connection_cache_size=20000

retry.attempts = 3

# By default, the toolbar only appears for clients from IP addresses
# '127.0.0.1' and '::1'.
# debugtoolbar.hosts = 127.0.0.1 ::1

###
# wsgi server configuration
###

[server:main]
use = egg:waitress#main
listen = localhost:6543

###
# logging configuration
# https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/logging.html
###

[loggers]
keys = root, tutorial

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = INFO
handlers = console

[logger_tutorial]
level = DEBUG
handlers =
qualname = tutorial

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s

私たちのWSGIアプリケーションを指定する `` [app:main] ``セクションが存在することに注意してください。 ZODBのデータベース設定は、このセクション内の `` zodbconn.uri``設定として指定されています。この値とこのセクション内の他の値は、サーバが `` pserve``で起動されたときに `` __init __。py``で定義した `` main``関数に `` **設定'`として渡されます。 。