Init Commit

This commit is contained in:
2026-01-17 15:58:06 +03:30
commit b6ad4d18be
6 changed files with 397 additions and 0 deletions

28
Codes/api-redis-json.py Normal file
View File

@@ -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}"}

26
Codes/api-redis.py Normal file
View File

@@ -0,0 +1,26 @@
from fastapi import FastAPI
import redis
# connect to redis (make sure redis is running locally)
r = redis.Redis(host="192.168.6.160", 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"}

22
Codes/mysql_test.py Normal file
View File

@@ -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()

22
Codes/redis_test.py Normal file
View File

@@ -0,0 +1,22 @@
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 == None:
print("Undefined Key")
exit
else:
print(value.decode('utf-8'))
elif (method == 2):
key=str(input("enter key name: "))
value=str(input("enter value: "))
r.set(key,value)
else:
print("Incorrect Input")
exit

127
Docs/Basic/01-data-types.md Normal file
View File

@@ -0,0 +1,127 @@
Data Types In Python :
int : normal numbers like (1 , -100 , 20326 ,0 , ..)
float :
string: txts in ""
list [1,2,3,4,5] or ['abbas', 2 ,-10 , 2.65]
dictionary: {'name': abbas , 'l_name': 'gholi'}
set: like set but dont have duplications
```python
print(type(var)) # Return Varible Type
```
strings:
strings is imutable (can,t change after set string with str[0]='i')
```python
string="this is string about abbas gholi #1"
print(string[0]) # --> Return t
print(string[1:3]) # --> Return his
print(string[-1]) # --> Return 1
# [start : end]
```
```python
string='012345678'
print(string[5]) # --> return '5'
print(string[1,5]) # --> return '1234'
print(string[1,4,2]) # --> return 13
print(string[::-1]) # --> return 876543210
```
```python
# String With Enter Every Char
"""
Hi This Is String Without Any Limits Like
enter
" "
and any more
"""
```
string methods:
```python
string="AbbAsGholi
print(string.upper()) # Return ABBASGHOLI
print(string.lower()) # Return abbasgholi
print(string.islower()) # Return False
print(string.index('i')) # Return 8
```
```python
string = "abbas,mmd,asghar"
list_strings = string.split(",")
print(list_strings) # out put is : ['abbas','mmd','asghar']
```
```python
f_name = 'abbas'
l_name = 'gholi'
age = 25
final_data = " Information: first_name: %s , last_name: %s , age : %i" % (f_name,l_name,age)
final_data = "Information: first_name: {} , last_name: {} , age : {}".format(f_name,l_name,age)
final_data = "Information: first_name: {0} , last_name: {1} , age : {2}".format(f_name,l_name,age)
final_data = "Information: first_name: {f} , last_name: {l} , age : {a}".format(f=f_name,l=l_name,a=age)
final_data = f"Information: first_name: {f_name} , last_name: {l_name} , age : {age}"
```
lists:
```python
list = [1,2,3,'pizze']
print(list[0]) # Return 1
print(list[1:3]) # Return 2,3
print(list[-1]) # Return 'pizze'
print(len(list)) # Return 4
print(list.count(3)) # return 3
list_last_value = list.pop()
print(list_last_value,list) # return 'pizze' , [1,2,3]
```
```python
list = [9,5,1,10]
list.sort()
print(list) # [1,5,9,10]
```
```python
list = [9,5,1,10]
list[0] = 2
print(list) # [2,5,1,10]
list.reverse()
print(list) # [10,2,5,2]
```
dictionary:
```python
price = {
"oil": 500000,
"egg": 350000
"frute" : {
"apple": 100000
"orange": 120000
}
}
print(price['oil'])
print(price['frute']['apple'])
print(price.keys()) # show keys
print(price.values()) # show values
print(price.items()) # show all key , values
print(price.get('egg')) # Return egg
print(price.get('water'),-1) # return -1
```
boolian:

172
Docs/Redis.md Normal file
View File

@@ -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()
```