calibrestekje/calibrestekje/api.py

29 lines
826 B
Python
Raw Normal View History

2020-02-28 11:32:58 +00:00
"""User facing API."""
2020-02-29 23:24:43 +00:00
from re import IGNORECASE, compile
2020-02-28 11:32:58 +00:00
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from calibrestekje.bindings import * # noqa
2020-02-29 23:24:43 +00:00
def title_sort(title):
"""Title sorting SQLAlchemy view function."""
regex = r"^(A|The|An|Der|Die|Das|Den|Ein|Eine|Einen|Dem|Des|Einem|Eines)\s+"
title_pat = compile(regex, IGNORECASE)
match = title_pat.search(title)
if match:
prep = match.group(1)
title = title.replace(prep, "") + ", " + prep
return title.strip()
2020-02-28 11:32:58 +00:00
def init_session(url: str):
"""Initialise a SQLAlchemy session against a Calibre database."""
2020-02-29 23:24:43 +00:00
engine = create_engine(url)
session = Session(engine)
connection = session.connection()
connection.connection.create_function("title_sort", 1, title_sort)
return session