Skip to main content
 首页 » 编程设计

python之如何使用 CherryPy 组织多应用服务器

2024年11月01日7leader

我正在使用 CherryPy 开发多个网络服务。其中一些必须使用相同的代码部分,所以我想避免代码重复。

我希望 CherryPy WebServer 为所有应用程序提供服务,安装在不同的 url 上。

这就是我组织文件层次结构的方式(当然是简化版):

apps/ 
    server.py  -- runs the WSGI Server 
    app1/ 
        api/ 
        lib/ 
        ext/ 
        app.py  -- provides a function get_wsgi_app(name, config) 
    app2/ 
        api/ 
        lib/ 
        ext/ 
        app.py 
    common/  -- All common classes and modules 

将 server.py 视为入口点。它导入每个 app.py 并从中获取一个 WSGI 应用程序。然后安装它们以供使用。

我希望能够从 common/中导入一些类,但不会多次更改 sys.path。所以我认为我可以在 ext 中导入所需的模块。当我在应用程序中需要它们时,我只需要像这样导入:

from ext.share_module import class 

1 - 你认为文件层次结构好吗?

2 - 我希望每个应用独立于服务器和其他应用。因此,对于导入,我希望能够简单地认为 app1/是根文件夹而不是 apps/。但是因为 server.py 是入口点,我不能像我想要的那样导入模块。

3 - 任何建议、考虑或意见? :)

请您参考如下方法:

好的,这是我最终得到的解决方案。 这几乎与问题中的相同。

apps/ 
    server.py  -- runs the WSGI Server 
    app1/ 
        api/  -- contains the business logic 
        controller/  -- makes the interface between HTTP and the API 
        lib/ 
        model/ 
        app.py  -- provides a function get_wsgi_app(name, config, app_instance_name) 
        url.py  -- like django, makes a binding between urls and controller 
    app2/ 
        -- same as app1 
    common/  -- All common classes and modules. Folders are the same that apps.  
        api/ 
        controller/ 
        lib/    
        model/ 
configs/ 
    app1.cfg 
    app2.cfg  
    server.cfg 

它是如何工作的:

server.py 是入口点。他的作用是启动 WSGI 服务器并挂载 WSGI 应用程序。 app.py 实例化应用程序并加载它的配置。 (您可以有多个 app1 实例)

urls.py 包含应用程序的 URL。

当我需要导入模块时,我只使用从应用程序文件夹开始的绝对导入。

例如:

from app1.api.my_module import API 
from common.api.login_api import LoginAPI 
 
class Foo(): 
    ... 

我从未尝试过使用相对导入,因为我更喜欢它是显式的,尤其是在文件夹通常命名相同的情况下。