비동기 PG¶
logfire.instrument_asyncpg() 기능을 사용할 수 있습니다. 로그파이어 탐지 비동기 PostgreSQL 드라이버.
설치¶
asyncpg 추가와 함께 logfire 설치:
{{ install_logfire(extras=['asyncpg']) }}
사용법¶
도커를 사용하여 PostgreSQL 데이터베이스를 설정하고 비동기 pg를 사용하여 데이터베이스에 연결하는 파이썬 스크립트를 실행하여 비동기 pg와 함께Logfire를 사용하는 방법을 시연합니다.
¶
Postgre 설정도커가 있는 데이터베이스
먼저 Postgre를 초기화해야 합니다. 이 작업은 다음 명령으로 Docker를 사용하여 쉽게 수행할 수 있습니다.
docker run --name postgres \
-e POSTGRES_USER=user \
-e POSTGRES_PASSWORD=secret \
-e POSTGRES_DB=database \
-p 5432:5432 -d postgres
이 주문은 다음 작업을 완료합니다.
-
--name postgres: 도커 컨테이너의 이름을 정의합니다. -
-e POSTGRES_USER=user: PostgreSQL 서버에 대한 사용자를 설정합니다. -
-e POSTGRES_PASSWORD=secretPostgreSQL 서버의 암호를 설정합니다. -
-e POSTGRES_DB=database이렇게 하면 파이썬 스크립트에 사용된 것과 동일한 데이터베이스인 "데이터베이스"라는 새 데이터베이스가 생성됩니다. -
-p 5432:5432이렇게 하면 PostgreSQL 인스턴스가 포트 5432의 로컬 컴퓨터에서 사용할 수 있습니다. -
-d postgres: 이 경우 사용할 도커 이미지를 나타냅니다. "
파이썬 스크립트 실행¶
다음 Python 스크립트는 PostgreSQL 데이터베이스에 연결하고 일부 SQL 쿼리를 실행합니다.
import asyncio
import asyncpg
import logfire
logfire.configure()
logfire.instrument_asyncpg()
async def main():
connection: asyncpg.Connection = await asyncpg.connect(
user='user', password='secret', database='database', host='0.0.0.0', port=5432
)
with logfire.span('Create table and insert data'):
await connection.execute('CREATE TABLE IF NOT EXISTS test (id serial PRIMARY KEY, num integer, data varchar);')
# Insert some data
await connection.execute('INSERT INTO test (num, data) VALUES ($1, $2)', 100, 'abc')
await connection.execute('INSERT INTO test (num, data) VALUES ($1, $2)', 200, 'def')
# Query the data
for record in await connection.fetch('SELECT * FROM test'):
logfire.info('Retrieved {record=}', record=record)
asyncio.run(main())
UI에서 프로젝트로 이동하면 스크립트 생성 범위가 표시됩니다.
本文总阅读量次