Джанго - Как вызвать модуль? - PullRequest
0 голосов
/ 29 ноября 2011

Я новичок в Python и Django.

Я создал файл с именем "utils.py" в этой структуре каталогов:

- MyProject
    - MyApp
        * __init__.py
        * forms.py
        * models.py
        * utils.py
        * views.py

"utils.py" имеетэто внутри:

import unicodedata # Para usar na strip_accents

# Para substituir occorrencias num dicionario
def _strtr(text, dic): 
    """ Replace in 'text' all occurences of any key in the given
    dictionary by its corresponding value.  Returns the new tring.""" 
    # http://code.activestate.com/recipes/81330/
    # Create a regular expression  from the dictionary keys
    import re
    regex = re.compile("(%s)" % "|".join(map(re.escape, dic.keys())))
    # For each match, look-up corresponding value in dictionary
    return regex.sub(lambda mo: str(dic[mo.string[mo.start():mo.end()]]), text)

# Para remover acentos de palavras acentuadas
def _strip_accents( text, encoding='ASCII'):
    return ''.join((c for c in unicodedata.normalize('NFD', unicode(text)) if unicodedata.category(c) != 'Mn') )


def elapsed_time (seconds):
    """
    Takes an amount of seconds and turns it into a human-readable amount of time.
    Site: http://mganesh.blogspot.com/2009/02/python-human-readable-time-span-give.html
    """
    suffixes=[' ano',' semana',' dia',' hora',' minuto', ' segundo']
    add_s=True
    separator=', '

    # the formatted time string to be returned
    time = []

    # the pieces of time to iterate over (days, hours, minutes, etc)
    # - the first piece in each tuple is the suffix (d, h, w)
    # - the second piece is the length in seconds (a day is 60s * 60m * 24h)
    parts = [(suffixes[0], 60 * 60 * 24 * 7 * 52),
      (suffixes[1], 60 * 60 * 24 * 7),
      (suffixes[2], 60 * 60 * 24),
      (suffixes[3], 60 * 60),
      (suffixes[4], 60),
      (suffixes[5], 1)]

    # for each time piece, grab the value and remaining seconds, and add it to
    # the time string
    for suffix, length in parts:
    value = seconds / length
    if value > 0:
        seconds = seconds % length
        time.append('%s%s' % (str(value),
                       (suffix, (suffix, suffix + 's')[value > 1])[add_s]))
    if seconds < 1:
        break

    return separator.join(time)

Как я могу вызвать функции внутри "utils.py" в моем "models.py"?Я пытался импортировать, как это, но это не работает ...

from MyProject.MyApp import *

Как я могу сделать эту работу?

С наилучшими пожеланиями,

Ответы [ 2 ]

1 голос
/ 29 ноября 2011

вам нужно изменить инструкцию по импорту на:

from MyProject.MyApp.utils import *
0 голосов
/ 29 ноября 2011

Одна из ваших проблем заключается в том, что:

- MyProject
    - MyApp
        * __init__.py
        * forms.py
        * models.py
        * utils.py
        * views.py

должно быть:

- MyProject
    - __init__.py 
    - MyApp
        * __init__.py
        * forms.py
        * models.py
        * utils.py
        * views.py

Обратите внимание на дополнительные __init__.py.

Второй - тот, на которого указал Дмитрий.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...