Django - Как организовать фрагменты кода, которые я использую по всему проекту? - PullRequest
0 голосов
/ 27 ноября 2011

Я новичок в Джанго. Я пришел из PHP, из CodeIgniter и в CodeIgniter у нас есть концепция помощников (функций, которые мы используем во всем проекте). Я новичок в 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 голосов
/ 27 ноября 2011

Соглашение состоит в том, чтобы создать модуль utils.py в вашем приложении и записать туда всех ваших помощников, также если у вас есть какое-то приложение, которое вообще не может быть повторно использовано, что-то специально приспособленное для вашего проекта, условно назвать его ' core 'и вставьте туда свой код adhoc

...