38
submitted 1 year ago* (last edited 1 year ago) by GodOfThunder@lemm.ee to c/python@programming.dev

I've seen two approaches which I'm going to post in the comments to see which one is considered best. Feel free to suggest others.

you are viewing a single comment's thread
view the rest of the comments
[-] GodOfThunder@lemm.ee 27 points 1 year ago

A function decorator: You can create a decorator that handles the connection and cursor creation and passes the cursor to the decorated function.

import sqlite3
from functools import wraps

DB_FILE = "your_database_file.db"

def with_cursor(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        conn = sqlite3.connect(DB_FILE)
        cursor = conn.cursor()

        result = func(cursor, *args, **kwargs)

        conn.commit()
        cursor.close()
        conn.close()

        return result

    return wrapper

@with_cursor
def insert_post_to_db(cursor: sqlite3.Cursor, issue: Issue, lemmy_post_id: int) -> None:
    cursor.execute(
        "INSERT INTO posts (issue_url, lemmy_post_id, issue_title, issue_body) VALUES (?, ?, ?, ?)",
        (issue.url, lemmy_post_id, issue.title, issue.formatted_body),
    )
this post was submitted on 14 Jul 2023
38 points (100.0% liked)

Python

5976 readers
5 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

📅 Events

October 2023

November 2023

PastJuly 2023

August 2023

September 2023

🐍 Python project:
💓 Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 1 year ago
MODERATORS