Does basic Python have any equivalent to extending Django templates?

25 views Asked by At

What I mean is that with Django templates, you can create a quite long file A, have a couple of "block" elements in it that can be extended in other files, and then you can create files B and C which don't have to contain much at all.


{% extends "file_A" %}
{% block foo %}something something{% endblock %}

So I'd like to be able to take a Python file I use over and over with only two things being changed in each instance, like the following ...


from datetime import datetime
from typing import Optional

from etc import config
from etc.database import Post

uri = config.MUSEUMS_URI
CURSOR_EOF = 'eof'


def handler(cursor: Optional[str], limit: int) -> dict:
    posts = Post.select().\
        where(Post.feed == 'museums').\
        order_by(Post.cid.desc()).\
        order_by(Post.indexed_at.desc()).\
        limit(limit)

    if cursor:
        if cursor == CURSOR_EOF:
            return {
                'cursor': CURSOR_EOF,
                'feed': []
            }
        cursor_parts = cursor.split('::')
        if len(cursor_parts) != 2:
            raise ValueError('Malformed cursor')

        indexed_at, cid = cursor_parts
        indexed_at = datetime.fromtimestamp(int(indexed_at) / 1000)
        posts = posts.where(((Post.indexed_at == indexed_at) & (Post.cid < cid)) | (Post.indexed_at < indexed_at))

    feed = [{'post': post.uri} for post in posts]

    cursor = CURSOR_EOF
    last_post = posts[-1] if posts else None
    if last_post:
        cursor = f'{int(last_post.indexed_at.timestamp() * 1000)}::{last_post.cid}'

    return {
        'cursor': cursor,
        'feed': feed
    }

... and make that a template that I can just extend, so that every file based on it only has to include the parts that actually change — in this case, that would be


uri = config.MUSEUMS_URI

and


...
where(Post.feed == 'museums').\
...

I don't immediately see how I could just make a module and import it into other files and do what I want to do, which is essentially to fill in or replace placeholders in the file which would be imported into other files that actually differ among each other in only two details.

0

There are 0 answers