2011-11-27 57 views
0

我是Django的新手。我来自PHP,来自CodeIgniter和CodeIgniter,我们拥有Helpers的概念(我们在整个项目中使用的所有函数)。我是新来的Python,我不知道这样做的最好的办法,我结束了这个models.py:Django - 如何组织我在整个项目中使用的所有代码段?

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文件中编写这个函数?

最好的问候,

回答

0

的约定是在应用程序中创建一个utils.py模块和写有所有你的助手,同样,如果你有一些应用程序,它是不能重复使用所有,财产以后专门为您量身定制项目的惯例是称之为'核心',并把你的adhoc代码放在那里