50 lines
1.1 KiB
Python
50 lines
1.1 KiB
Python
import re
|
|
import unicodedata
|
|
from sqlalchemy.orm import exc
|
|
from werkzeug.exceptions import abort
|
|
|
|
|
|
def get_object_or_404(model, *criterion):
|
|
try:
|
|
rv = model.query.filter(*criterion).one()
|
|
except (exc.NoResultFound, exc.MultipleResultsFound):
|
|
abort(404)
|
|
else:
|
|
return rv
|
|
|
|
|
|
def strip_accents(text):
|
|
"""
|
|
Strip accents from input String.
|
|
|
|
:param text: The input string.
|
|
:type text: String.
|
|
|
|
:returns: The processed String.
|
|
:rtype: String.
|
|
"""
|
|
try:
|
|
text = unicode(text, 'utf-8')
|
|
except (TypeError, NameError): # unicode is a default on python 3
|
|
pass
|
|
text = unicodedata.normalize('NFD', text)
|
|
text = text.encode('ascii', 'ignore')
|
|
text = text.decode("utf-8")
|
|
return str(text)
|
|
|
|
|
|
def text_to_id(text):
|
|
"""
|
|
Convert input text to id.
|
|
|
|
:param text: The input string.
|
|
:type text: String.
|
|
|
|
:returns: The processed String.
|
|
:rtype: String.
|
|
"""
|
|
text = strip_accents(text.lower())
|
|
text = re.sub('[ ]+', '_', text)
|
|
text = re.sub('[^0-9a-zA-Z_-]', '', text)
|
|
return text
|