DEV Community

artem
artem

Posted on

4 2

контекстные менеджеры

https://docs.python.org/3/library/contextlib.html

в случае, когда у вас есть скоуп для применения ресурса, оч классно использовать контекстные менеджеры
объявляется декоратором @contextmanager, дальше при помощи with используется
вы наверняка встречали, когда работали с файлами:
with open('workfile') as f: позволяет вам провести все операции с файлом — он закроется автоматически при выходе из скоупа

пример кейса — коннекшн к бд, открываем его, в нем открываем курсор (контекстный менеджер в контекстном менеджере), в скоупе делаем что-то и конекшн закроется при выходе автоматом, и дальше его можно переиспользовать

объявление

@contextmanager
def connection(driver, server, database, user, password):
    params = f'DRIVER={{{driver}}};SERVER={server};DATABASE={database};' \
             f'Trusted_Connection=no;UID={user};PWD={password}'
    conn = pyodbc.connect(params)
    yield conn
    conn.close()


@contextmanager
def cursor(driver, server, database, user, password):
    with connection(driver, server, database, user, password) as conn:
        csr = conn.cursor()
        yield csr
        csr.close()

пример использования

        with cursor(driver=self.config.driver, server=self.config.address, database=database,
                    user=self.config.user, password=self.config.password) as curs:
            curs.execute(f'truncate table {table_name}')
            curs.commit()

или можно использовать конекшн, а не курсор напрямую (пандас работает через конекшн)

        with connection(driver=self.config.driver, server=self.config.address, database=database,
                        user=self.config.user, password=self.config.password) as conn:
            df = pandas.read_sql(script, conn)

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay