【问题标题】:How to implement MVC like this in Python?如何在 Python 中实现这样的 MVC?
【发布时间】:2012-10-29 09:38:21
【问题描述】:

例如,我有一个名为 rule1.conf 的配置文件,如下所示:

[Basis]
user = "sunhf"
time = "2012-12-31"

[Bowtie]
path = "/usr/bin/bowtie"
index = "/mnt/Storage/sync/hg19"

还有一个这样的models.py(使用名为magic.py..的包):

from magic import Section
class Conf:
    __confname__ = None
    basis = Section(["user", "time"])
    bowtie = Section(["path", "index"])

最后是这样的viewer.py:

from models import Conf as my_conf
my_conf.__confname__ = "rule1.conf"  // bind to the config file, I have no ideas how to do this
print my_conf.basis.user    // output: `sunhf`
print my_conf.bowtie.index  // output: `/mnt/Storage/sync/hg19`

当我在命令行中运行viewer.py 时:

$ python viewer.py
sunhf
/mnt/Storage/sync/hg19

有人对如何实现magic.py 有任何想法吗? 谢谢!

【问题讨论】:

  • 让我感到奇怪的是,您希望使用类本身而不是 viewer.py 中的实例。您不应该有一个 Conf.__init__(confname) 让您使用特定配置文件创建配置实例吗?
  • @vicvicvic 在 SQLAlchemy 中,我记得 models.py 中的类仅用于声明,无需创建它们的实例:packages.python.org/Flask-SQLAlchemy/models.html
  • @vicvicvic 在我看来,Conf 类将只有一个实例(单例),我是否可以直接在 viewer.py 中使用 Conf 类而不是使用它的实例?
  • 我不同意您对 SQLAlchemy 工作原理的理解。您必须创建模型类的实例,例如当你使用它们时,你会做u = User("Firegun", "fire@gun.com")。单例是指您只有一个类的一个实例,但在这里您将类本身用作实例。

标签: python model-view-controller sqlalchemy metaprogramming metaclass


【解决方案1】:

我把我的解决方案放在这里:

https://github.com/hanfeisun/meta_model

使用

python  test.py

查看结果

【讨论】:

    猜你喜欢
    • 2011-01-09
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    相关资源
    最近更新 更多