2011-11-27 39 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代碼放在那裏