This repository has been archived on 2023-10-10. You can view files and clone it, but cannot push or open issues or pull requests.
paste/paste/db.py

47 lines
1.2 KiB
Python
Raw Normal View History

2023-09-25 13:30:27 +00:00
"""Manage db connection and insert."""
import logging
from redis import Redis
from paste import config
def connect_redis() -> Redis:
"""
Connect to redis.
:return: Redis connection object.
"""
2023-09-25 14:12:36 +00:00
return Redis(
host=config.REDIS_HOST, port=config.REDIS_PORT, db=0, decode_responses=True
)
2023-09-25 13:30:27 +00:00
def check_content_exist(key: str) -> bool:
"""
Verify if key already exist in redis db.
:param key: Key to check.
:return: True if existed, else false.
"""
db = connect_redis()
return db.exists(key)
def insert_content_db(url_id: str, expiration: int, content: str, secret: str) -> None:
2023-09-25 13:30:27 +00:00
"""
:param secret: Secret key for delete url
2023-09-25 13:30:27 +00:00
:param url_id: key for access to content.
:param expiration: Content expiration in second. Set 0 if no expiration.
2023-09-25 13:30:27 +00:00
:param content: Paste content
:return: None
"""
2023-09-25 14:12:36 +00:00
if not check_content_exist(url_id):
2023-09-25 13:30:27 +00:00
db = connect_redis()
data = {"content": content, "secret": secret}
for key, key_content in data.items():
db.hset(url_id, key, key_content)
if expiration != 0:
db.expire(url_id, expiration)
2023-09-25 13:30:27 +00:00
else:
2023-09-26 09:32:42 +00:00
logging.error(f"Key : {url_id} already exist") # noqa: G004