저는 Python과 Django를 처음 사용합니다.Django - 모듈 호출 방법?
나는이 디렉토리 구조에 "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)
가 어떻게이 함수를 호출 할 수 있습니다 :
- MyProject
- MyApp
* __init__.py
* forms.py
* models.py
* utils.py
* views.py
은 "utils.py는"이 안에있다 내 "models.py"에서 "utils.py"안에 있습니까? 이런 식으로 가져 오려고했으나 작동하지 않습니다 ...
from MyProject.MyApp import *
어떻게이 작업을 수행 할 수 있습니까?
최고 감사합니다, 당신이 당신의 import 문을 변경해야
초보자에게는'import *'형식을 사용하지 않는 것이 좋습니다. 'myproject.myapp import utils'에서 'utils.foo'로 모든 것을 참조하는 것이 더 좋습니다. –