开发者

Python instances/Django

Say I want to print all my installed apps their version info on server startup.. I have this setup:

Project
    /app-one
        __init__.py
        otherstuff
    /app-two
        __init__.py
        otherstuff
    /__init__.py
    /admin.py
    /urls.py
    /settings.py

main init file

import settings

if settings.DEBUG:
     for app in settings.INSTALLED_APPS:
         try:
             import app
             print getattr(app, '__version__', None)
         except Exception:
             pass

app init file(s)

__version_info__ = ('0', '0', '1')
__version__ = '.'.join(__version_info__)

I get into the pass statement.. I suppose this is because the w开发者_Go百科ay instances work in Python, but how would I fix it?

this works though:

import app
getattr(app, '__version__', None)

This fixed it:

import settings

if settings.DEBUG:
    for app in settings.INSTALLED_APPS:
        app = __import__(app)
        print getattr(app, '__version__', None)


app in your loop is not a module but a string. To load module by name you have to use django.utils.importlib.import_module function:

from django.conf import settings
from django.utils.importlib import import_module

for app in settings.INSTALLED_APPS:
    app_module = import_module(app)
    print getattr(app_module, '__version__', None)


Here's the thing - settings.INSTALLED_APPS is a tuple of strings. The import statement cannot do anything with that. To do this, you need to use the __import__() function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜