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)
|
|
|
|
|
|
|
|
|
2023-09-26 12:53:08 +00:00
|
|
|
def insert_content_db(url_id: str, expiration: int, content: str, secret: str) -> None:
|
2023-09-25 13:30:27 +00:00
|
|
|
"""
|
|
|
|
|
2023-09-26 12:53:08 +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.
|
2023-10-01 20:01:21 +00:00
|
|
|
: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()
|
2023-09-26 12:53:08 +00:00
|
|
|
data = {"content": content, "secret": secret}
|
|
|
|
for key, key_content in data.items():
|
|
|
|
db.hset(url_id, key, key_content)
|
2023-10-01 20:01:21 +00:00
|
|
|
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
|