【问题标题】:How do you add an attribute to a django app python module?如何向 django app python 模块添加属性?
【发布时间】:2018-08-01 05:05:18
【问题描述】:

给定一个名为 mattermost 的 django 应用程序,它有一个名为 Channel 的模型,我们可以做这样的事情。

import mattermost
for channel in Channel.objects.all():
    print(channel)

我希望能够做这样的事情

import mattermost
mattermost.channels.list

我尝试在与 mattermost/init.py 相同的文件夹中添加带有 def list(): 函数的 channels.py。

我收到以下错误。

In [7]: reload(mattermost)
Out[7]: <module 'mattermost' from '/home/csmu/mipgen-django/mattermost/__init__.py'>

In [8]: mattermost.channels.list
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-d4715777f4f1> in <module>()
----> 1 mattermost.channels.list

AttributeError: module 'mattermost' has no attribute 'channels'

如何为 django app python 模块添加属性?

channels.py的内容:

import mattermost

def list():
    for channel in mattermost.models.Channel.objects.all():
        print(channel)

【问题讨论】:

    标签: python django


    【解决方案1】:

    试试 from mattermost import channels print(channels.list())

    这导致:

        In [1]: import mattermost
    
        In [2]: mattermost.channels.list()
        ---------------------------------------------------------------------------
        AttributeError                            Traceback (most recent call last)
        <ipython-input-2-249466f32547> in <module>()
        ----> 1 mattermost.channels.list()
    
        AttributeError: module 'mattermost' has no attribute 'channels'
    
        In [3]: from mattermost import channels
    
        In [4]: mattermost.channels.list()
        list.stub
    
        In [5]: 
    

    很接近。

    【讨论】:

    • 关于如何自动执行from mattermost import channels的任何想法?
    【解决方案2】:

    我发现您可以通过将以下内容添加到 mattermost/__init__py 来做到这一点

    #!/usr/bin/env python
    import os, pkgutil
    __all__ = list(module for _, module, _ in 
    pkgutil.iter_modules([os.path.dirname(__file__)]))
    

    那么下面的工作

    import mattermost
    from mattermost import *
    mattermost.channels.list()
    

    为每个最重要的通道产生输出。

    【讨论】:

      猜你喜欢
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-16
      • 1970-01-01
      • 2017-07-22
      • 2021-06-19
      相关资源
      最近更新 更多