金字塔项目结构

17 投票
2 回答
4567 浏览
提问于 2025-04-16 17:42

我正在用Pyramid开发一个比较大的项目。之前我用过Django,我很喜欢Django的项目结构和把功能封装成应用的方式。我想在Pyramid中也实现类似的结构。我知道Pyramid很灵活,可以做到这一点,但我需要一些帮助来实现松耦合的结构。我的项目结构应该像这样:

  Project/
         app1/
             models.py
             routes.py
             views.py
         app2/
             models.py
             routes.py
             views.py

有什么建议吗?

2 个回答

2

我实现了一个全局的 appIncluder 函数,这个函数在要包含的包的 init.py 文件中被导入为 includeme。

includeme(ApplicationIncluder)接收一个配置对象,这样就可以轻松使用 config.package 以及它的变量、方法和类(这些都在同一个 init.py 和子模块中)。

非常感谢这个想法!

代码如下:

项目:'foo',要部署的应用在 foo.foo.apps 目录下。

结构:

foo
|-foo
  |- __init__.py
  |- appincluder.py
  |-apps
    |-test
      |- __init__.py
      |- views.py
      |- templates
         |- test.jinja2

foo/foo/init.py:

config.include('foo.apps.test')

foo/foo/appincluder.py

def appIncluder(config):
    app    = config.package
    prefix = app.prefix
    routes = app.routes

    for route,url in routes.items():
        config.add_route(route,prefix + url)

    config.scan(app)

    log.info('app: %s included' % app.__name__)

foo/foo/apps/test/init.py

from foo.appincluder import appIncluder as includeme

prefix = '/test'

routes = {
    'test': '/home'
}

foo/foo/apps/test/views.py

from pyramid.view import view_config


@view_config(route_name='test', renderer='templates/test.jinja2')
def test(request):
    return {}

希望这对某些人有帮助。

28

Pyramid框架对你的应用程序结构没有固定的要求,所以无论你怎么划分你的应用,配置起来都差不多。不过,如果你把应用分成几个不同的包,你可以选择使用config.include()这个指令,把每个包都包含到你的主配置里。

举个例子:

# myapp/__init__.py (main config)
def main(global_config, **settings):
    config = Configurator(...)
    # basic setup of your app
    config.include('pyramid_tm')
    config.include('pyramid_jinja2')

    # add config for each of your subapps
    config.include('project.app1')
    config.include('project.app2')

    # make wsgi app
    return config.make_wsgi_app()

# myapp/app1/__init__.py (app1's config)
def includeme(config):
    config.add_route(...)
    config.scan()

# myapp/app2/__init__.py (app2's config)
def includeme(config):
    config.add_route(...)
    config.scan()

在每个子应用里,你可以定义视图、模型等等。

一般来说,你可能想在公共的设置中创建你的SQLAlchemy(或者其他数据库)的会话,因为你的不同应用很可能都是在使用同一个数据库引擎。

撰写回答