我是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)
如何在“models.py”中调用“utils.py”中的函数?我试图像这样导入,但它不起作用......
from MyProject.MyApp import *
我怎样才能做到这一点?
最诚挚的问候,
答案 0 :(得分:1)
您需要将import语句更改为:
from MyProject.MyApp.utils import *
答案 1 :(得分:0)
你的一个问题是:
- 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
。
第二个是德米特里指出的那个。