Python
Redis DB API
Python에서 redis 라이브러리를 이용한 Redis 연결, Pool, 키 관리 정리
1) Redis 연결
패키지 설치
pip install redis
기본 연결
import redis
con = redis.StrictRedis(host="127.0.0.1", port=6379)
Connection Pool
import redis
redis_pool = redis.ConnectionPool(
host="127.0.0.1",
port=6379,
max_connections=4
)
with redis.StrictRedis(connection_pool=redis_pool) as con:
con.set("key", "value")
print(con.get("key"))
2) 키의 만료 시간 설정
# 설정 (초 단위)
con.set("album", "genesis", 30)
# 만료시간 확인
print(con.ttl("album"))
# 만료시간 수정
con.expire("album", 100)
3) 자료구조 활용
List
con.rpush("list", "adam")
con.rpush("list", "rusia")
con.rpush("list", "cidar")
# 조회
for item in con.lrange("list", 0, -1):
print(item)
4) 주의할 점
- Python 최신 버전에서는
pymysql설치가 안 되는 경우가 있음 - MariaDB 사용 시 Python 3.13 권장
- 실제 DB 연동은 특별한 경우가 아니라면 ORM 사용 권장
- Django: 내장 ORM 사용
- FastAPI: SQLAlchemy 등 별도 ORM 설치
댓글