Django - 如何组织我在整个项目中使用的代码片段?

时间:2011-11-27 16:22:14

标签: django helpers

我是Django的新手。我来自PHP,来自CodeIgniter和CodeIgniter,我们有Helpers的概念(我们在整个项目中使用的功能)。我是Python的新手,我不知道这样做的最好方法,我最终得到了这个models.py:

from django.db import models
import unicodedata


class JobsadsText(models.Model):
    hash = models.TextField(primary_key=True)
    site_name = models.TextField()
    uri = models.TextField()
    job_title = models.TextField()
    job_description = models.TextField()
    country_ad = models.TextField()
    zone_ad = models.TextField()
    location_ad = models.TextField()
    date_inserted = models.DateTimeField()
    class Meta:
    db_table = u'jobsads_text'
    managed = False

    def get_absolute_url(self):
    return "/frame/" + format_string_to_uri(self.zone_ad) + "/" + format_string_to_uri(self.location_ad) + "/" + format_string_to_uri(self.job_title) + ".html"

    def ascii_job_title(self):
    return strip_accents(self.job_title)

    def ascii_job_description(self):
    return strip_accents(self.job_description)

    def ascii_country_ad(self):
    return strip_accents(self.country_ad)

    def ascii_zone_ad(self):
    return strip_accents(self.zone_ad)

    def ascii_location_ad(self):
    return strip_accents(self.location_ad)
    # Para poder pesquisar palavras sem acentos - END -

    def __unicode__(self):
    return self.job_title


# H E L P E R S
# 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') )

'''
Esta funcao formata uma string para poder ser usada num URI
'''
def format_string_to_uri(string):
    # Para substituir os caracteres q nao sao permitidos no URL
    replacements = {"(" : "(", ")" : ")", "!" : "-", "$" : "-", "?" : "-", ":" : "-", " " : "-", "," : "-", "&" : "-", "+" : "-", "-" : "-", "/" : "-", "." : "-", "*" : "-",}
    return _strtr(_strip_accents(string).lower(), replacements)

# 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') )

我在整个项目中使用这个函数(strip_accents,format_string_to_uri,_strtr,_strip_accents)。如何以我不需要在每个* .py文件中编写此函数的方式组织此函数?

最诚挚的问候,

1 个答案:

答案 0 :(得分:0)

惯例是在你的应用程序中创建一个utils.py模块并在那里写下你的所有帮助程序,如果你有一些根本不可重复使用的应用程序,那些专门为你的项目定制的东西,惯例是调用它& #39;核心'并将您的特殊代码放在那里