金字塔项目结构

17

我正在使用Pyramid开发一个相当大的项目。之前我用的是Django,我非常喜欢它构建项目的方式和将功能封装到应用程序中的方法。我希望能够用Pyramid实现同样的结构。我知道Pyramid非常灵活,可以做到这一点,但我需要一些帮助来实现松散耦合的相同结构。项目结构应该看起来像:

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

有什么建议吗?

2个回答

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(或其他数据库)会话,因为您的不同应用程序很可能都在使用相同的引擎。

2
我已经实现了一个名为global appIncluder的函数,并在要包含的软件包的init.py中导入它作为includeme。
includeme(ApplicationIncluder)接收config对象,因此很容易使用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 {}

我希望能对某些人有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接