diff --git a/Caching/redis/Codes/api-json.py b/Caching/redis/Codes/api-json.py new file mode 100644 index 0000000..9e1b6d4 --- /dev/null +++ b/Caching/redis/Codes/api-json.py @@ -0,0 +1,28 @@ +from fastapi import FastAPI +from pydantic import BaseModel +import redis + +# Connect to Redis +r = redis.Redis(host="192.168.6.160", port=30553, db=0, decode_responses=True) + +app = FastAPI() + +# For sending JSON data +class Item(BaseModel): + key: str + value: str | None = None # make value optional + +@app.get("/") +def home(): + return {"message": "Redis API is working!"} + +# Set key/value using JSON body +@app.post("/set") +def set_json(item: Item): + r.set(item.key, item.value) + return {"message": f"Saved {item.key} = {item.value}"} + +@app.post("/get") +def get_json(item: Item): + value = r.get(item.key) + return {"Key": f"{value}"} \ No newline at end of file diff --git a/Caching/redis/Codes/api-set-get.py b/Caching/redis/Codes/api-set-get.py new file mode 100644 index 0000000..077adea --- /dev/null +++ b/Caching/redis/Codes/api-set-get.py @@ -0,0 +1,26 @@ +from fastapi import FastAPI +import redis + +# connect to redis (make sure redis is running locally) +r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True) + +app = FastAPI() + +@app.get("/") +def home(): + return {"message": "Redis API is working!"} + +# Set a key/value +@app.post("/set/{key}/{value}") +def set_key(key: str, value: str): + r.set(key, value) + return {"message": f"Key '{key}' set with value '{value}'"} + +# Get a key/value +@app.get("/get/{key}") +def get_key(key: str): + value = r.get(key) + if value: + return {"key": key, "value": value} + else: + return {"error": f"Key '{key}' not found"} diff --git a/Caching/redis/Codes/Simple_python.py b/Caching/redis/Codes/set-get.py similarity index 100% rename from Caching/redis/Codes/Simple_python.py rename to Caching/redis/Codes/set-get.py diff --git a/Caching/redis/python-redis.md b/Caching/redis/python-redis.md new file mode 100644 index 0000000..363b4dc --- /dev/null +++ b/Caching/redis/python-redis.md @@ -0,0 +1,172 @@ +# Python + Redis Quick Guide + +This document explains how to set up Python, connect to Redis, and perform basic cache operations. + +--- + +## 1. Setup + +Install Python and create a virtual environment: + +```bash +sudo apt install python3-full +python3 -m venv .venv +source .venv/bin/activate +``` + +--- + +## 2. Connect and Test Redis Connection + +```python +import redis + +r = redis.Redis(host='localhost', port=6379, db=0) +print(r.ping()) # Should print True +``` + +**Expected Output:** + +``` +True +``` + +--- + +## 3. Caching Scenario Example + +This example demonstrates caching data in Redis with a TTL (Time To Live). + +```python +import redis +import time + +r = redis.Redis(host='localhost', port=6379, db=0) + +def get_data_from_db(): + print("Fetching from DB...") + time.sleep(2) # Simulate slow query + return {"user": "alice", "age": 30} + +def get_user(user_id): + cache_key = f"user:{user_id}" + + # Check cache first + cached = r.get(cache_key) + if cached: + print("Cache hit") + return eval(cached) + + # Fetch from DB + data = get_data_from_db() + + # Store in Redis with TTL (10 seconds) + r.set(cache_key, str(data), ex=10) + return data + +print(get_user(1)) +print(get_user(1)) # Should hit cache +``` + +--- + +## 4. Connect, Set, and Get Example + +```python +import redis + +r = redis.Redis(host="192.168.6.160", port=6379, db=0) + +r.set('name', 'radin') + +name = r.get('name') +print(name) +print(name.decode("utf-8")) +``` + +--- + +## 5. Interactive Read/Write Example + +```python +import redis + +method = int(input("Enter Method: (1.Read/2.Write) ")) + +r = redis.Redis(host="192.168.6.160", port=6379, db=0) + +if method == 1: + key = str(input("Enter key name: ")) + value = r.get(key) + if value is None: + print("Undefined Key") + else: + print(value) +elif method == 2: + key = str(input("Enter key name: ")) + value = str(input("Enter value: ")) + r.set(key, value) +else: + print("Incorrect Input") +``` + +--- + +## 6. Professional Version (Improved Code) + +```python +import redis +import sys + +def connect_redis(host="192.168.6.160", port=6379, db=0): + """Establish a connection to Redis.""" + try: + client = redis.Redis(host=host, port=port, db=db, decode_responses=True) + # Test connection + client.ping() + return client + except redis.ConnectionError as e: + print(f"Error connecting to Redis: {e}") + sys.exit(1) + +def read_key(client): + """Read a key from Redis.""" + key = input("Enter key name: ").strip() + value = client.get(key) + if value is None: + print("Undefined Key") + else: + print(f"Value: {value}") + +def write_key(client): + """Write a key-value pair to Redis.""" + key = input("Enter key name: ").strip() + value = input("Enter value: ").strip() + client.set(key, value) + print(f"Successfully set key '{key}' with value '{value}'.") + +def main(): + client = connect_redis() + + print("Select Method:") + print("1. Read") + print("2. Write") + + try: + method = int(input("Enter method (1 or 2): ").strip()) + except ValueError: + print("Invalid input. Please enter 1 or 2.") + sys.exit(1) + + if method == 1: + read_key(client) + elif method == 2: + write_key(client) + else: + print("Incorrect input. Please enter 1 or 2.") + sys.exit(1) + +if __name__ == "__main__": + main() +``` + diff --git a/Databases/Mariadb/python-mysql.py b/Databases/Mariadb/python-mysql.py new file mode 100644 index 0000000..d69a937 --- /dev/null +++ b/Databases/Mariadb/python-mysql.py @@ -0,0 +1,22 @@ +import mysql.connector + +# Connect to the database +conn = mysql.connector.connect( + host="localhost", + user="your_user", + password="your_password", + database="your_database" +) + +cursor = conn.cursor() + +# Run a query +cursor.execute("SELECT * FROM your_table;") + +# Fetch and print results +for row in cursor.fetchall(): + print(row) + +# Close connection +cursor.close() +conn.close()