Code With Python
39K subscribers
841 photos
24 videos
22 files
746 links
This channel delivers clear, practical content for developers, covering Python, Django, Data Structures, Algorithms, and DSA – perfect for learning, coding, and mastering key programming skills.
Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
#70. What is operator overloading?
A: Operator overloading allows you to redefine the behavior of built-in operators (like +, -, *) for your custom classes. This is done by implementing the corresponding magic methods (e.g., __add__ for +, __mul__ for *).

---
Part 5: Advanced Concepts & Libraries (Q71-85)

#71. Explain exception handling in Python.
A: Exception handling is a mechanism for responding to runtime errors.
try: The block of code to be attempted, which may cause an error.
except: This block is executed if an error occurs in the try block. You can specify the type of exception to catch.
else: This block is executed if no exceptions are raised in the try block.
finally: This block is always executed, whether an exception occurred or not. It's often used for cleanup operations.

try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Result is {result}")
finally:
print("Execution finished.")

Result is 5.0
Execution finished.


#72. How do you raise a custom exception?
A: You can define a custom exception by creating a new class that inherits from the built-in Exception class. Then, use the raise keyword to throw it.

class MyCustomError(Exception):
pass

raise MyCustomError("Something went wrong!")


#73. What is the purpose of the with statement?
A: The with statement simplifies exception handling by encapsulating common try...finally cleanup patterns. It is used with objects that support the context management protocol (which have __enter__ and __exit__ methods). It's most commonly used for managing file streams, ensuring the file is closed automatically.

# The file is automatically closed after this block
with open('file.txt', 'w') as f:
f.write('hello')


#74. What is the difference between multithreading and multiprocessing?
A:
Multithreading: Multiple threads run within the same process, sharing the same memory space. Due to the GIL, it's best for I/O-bound tasks (like network requests or file operations) where threads can wait without blocking the entire program.
Multiprocessing: Multiple processes run, each with its own memory space and Python interpreter. This allows for true parallelism and is ideal for CPU-bound tasks (like heavy calculations) as it bypasses the GIL.

#75. What is the difference between a module and a package?
A:
Module: A single Python file (.py) containing statements and definitions.
Package: A way of organizing related modules into a directory hierarchy. A directory must contain a file named __init__.py (which can be empty) to be considered a package.
---
#76. What are virtual environments? Why are they important?
A: A virtual environment is an isolated Python environment that allows you to manage dependencies for a specific project separately. They are important because they prevent package version conflicts between different projects on the same machine.

#77. What is pip?
A: pip is the standard package manager for Python. It allows you to install and manage third-party libraries and packages from the Python Package Index (PyPI).
#78. How does Python's for loop work internally?
A: The for loop in Python works with the iterator protocol. When you write for item in iterable:, Python first calls iter(iterable) to get an iterator object. Then, it repeatedly calls next() on this iterator object and assigns the result to item until a StopIteration exception is raised, which signals the end of the loop.

#79. What is the requests library used for?
A: The requests library is the de-facto standard for making HTTP requests in Python. It simplifies the process of interacting with web services and APIs.

import requests

response = requests.get('https://api.github.com')
print(response.status_code)

200


#80. How do you work with JSON files in Python?
A: Use the built-in json module.
json.dump() / json.dumps(): To serialize a Python object into a JSON formatted stream or string.
json.load() / json.loads(): To de-serialize a JSON formatted stream or string into a Python object.

import json

data = {'name': 'John', 'age': 30}
json_string = json.dumps(data)
print(json_string)

{"name": "John", "age": 30}

---
#81. What is the os module used for?
A: The os module provides a way of using operating system-dependent functionality like reading or writing to the file system, interacting with environment variables, and managing directories.

#82. What is monkey-patching?
A: Monkey-patching is a technique used to dynamically modify or extend code at runtime. For example, you can change the behavior of a function or a method in a third-party library without altering the original source code.

#83. What is a metaclass?
A: A metaclass is a "class of a class". It defines how a class behaves. A class is an instance of a metaclass. In Python, type is the default metaclass. It's an advanced concept used for creating custom class behaviors.

#84. What is the difference between range() and xrange()?
A: This is a Python 2 question.
• In Python 2, range() created an actual list in memory, which was inefficient for very large ranges. xrange() created a generator-like object that yielded numbers on demand.
• In Python 3, the old range() was removed, and xrange() was renamed to range(). So, Python 3's range() behaves like Python 2's memory-efficient xrange().

#85. What are some popular Python frameworks for web development?
A:
Django: A high-level, "batteries-included" framework that encourages rapid development and clean, pragmatic design.
Flask: A lightweight microframework that is simpler and more flexible, allowing developers to choose their own libraries and tools.
FastAPI: A modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints.

---
Part 6: Coding Problems & Algorithms (Q86-100)

#86. Write a function to check if a string is a palindrome.
A: A palindrome reads the same forwards and backward. The easiest way is to compare the string with its reversed version.

def is_palindrome(s):
# Clean the string (optional, depends on requirements)
s = ''.join(filter(str.isalnum, s)).lower()
return s == s[::-1]

print(is_palindrome("A man, a plan, a canal: Panama"))
print(is_palindrome("racecar"))
print(is_palindrome("hello"))

True
True
False


#87. Write a Fibonacci sequence generator.
A: A generator is memory-efficient for this task.
1
def fibonacci_generator(n):
a, b = 0, 1
count = 0
while count < n:
yield a
a, b = b, a + b
count += 1

for num in fibonacci_generator(10):
print(num, end=' ')

0 1 1 2 3 5 8 13 21 34


#88. Solve the FizzBuzz problem.
A: Print numbers from 1 to n. But for multiples of three, print "Fizz" instead of the number, and for the multiples of five, print "Buzz". For numbers which are multiples of both three and five, print "FizzBuzz".

def fizzbuzz(n):
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)

fizzbuzz(15)


#89. Find the factorial of a number using recursion.
A: The factorial of n is the product of all positive integers up to n.

def factorial(n):
if n < 0:
return "Factorial does not exist for negative numbers"
elif n == 0:
return 1
else:
return n * factorial(n - 1)

print(factorial(5))

120


#90. Reverse a string in Python.
A: The simplest and most Pythonic way is to use slicing.

my_string = "hello"
reversed_string = my_string[::-1]
print(reversed_string)

olleh

---
#91. Find the most frequent element in a list.
A: The collections.Counter class is perfect for this.

from collections import Counter

my_list = [1, 2, 3, 2, 4, 2, 5, 2]
count = Counter(my_list)
most_common_element = count.most_common(1)[0][0]
print(most_common_element)

2


#92. Check if two strings are anagrams.
A: Anagrams are words formed by rearranging the letters of another. If the sorted versions of the two strings are equal, they are anagrams.

def are_anagrams(s1, s2):
return sorted(s1) == sorted(s2)

print(are_anagrams("listen", "silent"))
print(are_anagrams("hello", "world"))

True
False


#93. Flatten a nested list.
A: This can be solved with recursion.

def flatten(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten(item))
else:
flat_list.append(item)
return flat_list

nested = [1, [2, 3], 4, [5, [6, 7]]]
print(flatten(nested))

[1, 2, 3, 4, 5, 6, 7]


#94. Find all pairs of an integer array whose sum is equal to a given number.
A: A hash set (or a dictionary) can be used to solve this in O(n) time.

def find_sum_pairs(arr, target_sum):
seen = set()
pairs = []
for num in arr:
complement = target_sum - num
if complement in seen:
pairs.append((complement, num))
seen.add(num)
return pairs

my_array = [2, 7, 4, 1, 5, 6]
print(find_sum_pairs(my_array, 8))

[(1, 7), (2, 6)]


#95. Write a simple decorator that logs the execution time of a function.
A: Use the time module and wrap the function call.

import time

def timer_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function {func.__name__} took {end_time - start_time:.4f} seconds to run.")
return result
return wrapper

@timer_decorator
def long_running_function():
time.sleep(1)

long_running_function()

Function long_running_function took 1.0010 seconds to run.

---
#96. Write a function that takes a list of numbers and returns a new list containing only the even numbers.
A: List comprehension is a great way to do this.
def filter_even_numbers(numbers):
return [num for num in numbers if num % 2 == 0]

my_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(filter_even_numbers(my_numbers))

[2, 4, 6, 8, 10]


#97. Explain what * does when unpacking a list or tuple.
A: The * operator can be used to unpack an iterable into individual elements. It's often used for function arguments or in assignments.

numbers = [1, 2, 3, 4, 5]

first, *middle, last = numbers

print(f"First: {first}")
print(f"Middle: {middle}")
print(f"Last: {last}")

First: 1
Middle: [2, 3, 4]
Last: 5


#98. Write a function to merge two sorted lists into a single sorted list.
A: You can simply concatenate them and sort, but a more efficient approach (O(n+m)) is to iterate through both lists simultaneously.

def merge_sorted_lists(list1, list2):
# The simple, Pythonic way
return sorted(list1 + list2)

l1 = [1, 3, 5]
l2 = [2, 4, 6]
print(merge_sorted_lists(l1, l2))

[1, 2, 3, 4, 5, 6]


#99. What will be the output of the following code?
A: This question tests understanding of mutable default arguments.

def my_func(item, my_list=[]):
my_list.append(item)
return my_list

print(my_func(1))
print(my_func(2))
print(my_func(3))

[1]
[1, 2]
[1, 2, 3]

The default list is created only once when the function is defined. It is then shared across all subsequent calls, leading to this surprising behavior. The correct way is to use my_list=None as the default.

#100. How would you count the occurrences of each word in a given text sentence?
A: The collections.Counter is the ideal tool for this task.

from collections import Counter
import re

sentence = "The quick brown fox jumps over the lazy dog dog"
# Pre-process: lowercase and split into words
words = re.findall(r'\w+', sentence.lower())
word_counts = Counter(words)

print(word_counts)

Counter({'the': 2, 'dog': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1})


━━━━━━━━━━━━━━━
By: @DataScience4
3
💡 Top 50 Operations for Text Processing in Python
💡 Top 50 Operations for Text Processing in Python

I. Case & Whitespace Manipulation

• Convert to lowercase.
text = "Hello World"
lower_text = text.lower()

• Convert to uppercase.
upper_text = text.upper()

• Capitalize the first letter of the string.
capitalized = "hello world".capitalize()

• Convert to title case (each word starts with a capital).
title_text = "hello world".title()

• Swap character case.
swapped = "Hello World".swapcase()

• Remove leading and trailing whitespace.
padded_text = "  hello  "
stripped_text = padded_text.strip()

• Remove leading whitespace.
left_stripped = padded_text.lstrip()

• Remove trailing whitespace.
right_stripped = padded_text.rstrip()


II. Searching, Replacing & Counting

• Find the first index of a substring.
index = "hello world".find("world") # Returns 6

• Check if a string starts with a substring.
starts_with_hello = text.startswith("Hello") # True

• Check if a string ends with a substring.
ends_with_world = text.endswith("World") # True

• Replace a substring with another.
new_text = text.replace("World", "Python")

• Count occurrences of a substring.
count = "hello hello".count("hello") # Returns 2


III. Splitting & Joining

• Split a string into a list of words.
words = text.split(' ') # ['Hello', 'World']

• Join a list of strings into a single string.
word_list = ["Hello", "Python"]
joined_text = " ".join(word_list)

• Split a string into lines.
multiline = "line one\nline two"
lines = multiline.splitlines()

• Partition a string at the first occurrence of a separator.
parts = "user@domain.com".partition('@') # ('user', '@', 'domain.com')


IV. Character & String Checks

• Check if all characters are alphabetic.
"HelloWorld".isalpha() # True

• Check if all characters are digits.
"12345".isdigit() # True

• Check if all characters are alphanumeric.
"Python3".isalnum() # True

• Check if all characters are whitespace.
"  \t\n".isspace() # True


V. Regular Expressions (re module)

• Find the first match of a pattern.
import re
match = re.search(r'\d+', 'There are 10 apples.')

• Find all matches of a pattern.
numbers = re.findall(r'\d+', '10 apples and 20 oranges')

• Substitute a pattern with a replacement string.
no_digits = re.sub(r'\d', '#', 'My pin is 1234')

• Split a string by a regex pattern.
items = re.split(r'[,;]', 'apple,banana;cherry')


VI. Basic NLP - Tokenization & Cleaning
(Requires pip install nltk)

• Sentence Tokenization.
from nltk.tokenize import sent_tokenize
# nltk.download('punkt') # Run once
text = "Hello Mr. Smith. How are you?"
sentences = sent_tokenize(text)

• Word Tokenization.
from nltk.tokenize import word_tokenize
words = word_tokenize("Hello, how are you?")

• Remove punctuation.
import string
text = "A string with... punctuation!"
clean = text.translate(str.maketrans('', '', string.punctuation))

• Remove stop words.
from nltk.corpus import stopwords
# nltk.download('stopwords') # Run once
stop_words = set(stopwords.words('english'))
filtered = [w for w in words if not w.lower() in stop_words]


VII. Word Normalization (Stemming & Lemmatization)

• Stemming (reduce words to their root form).
from nltk.stem import PorterStemmer
ps = PorterStemmer()
stemmed = ps.stem("running") # 'run'

• Lemmatization (reduce words to their dictionary form).
from nltk.stem import WordNetLemmatizer
# nltk.download('wordnet') # Run once
lemmatizer = WordNetLemmatizer()
lemma = lemmatizer.lemmatize("better", pos="a") # 'good'


VIII. Advanced NLP Analysis
(Requires pip install spacy and python -m spacy download en_core_web_sm)

• Part-of-Speech (POS) Tagging.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Apple is looking at buying a U.K. startup.")
for token in doc: print(token.text, token.pos_)

• Named Entity Recognition (NER).
for ent in doc.ents:
print(ent.text, ent.label_) # Apple ORG, U.K. GPE

• Get word frequency distribution.
from nltk.probability import FreqDist
fdist = FreqDist(word_tokenize("this is a test this is only a test"))


IX. Text Formatting & Encoding

• Format strings with f-strings.
name = "Alice"
age = 30
message = f"Name: {name}, Age: {age}"

• Pad a string with leading zeros.
number = "42".zfill(5) # '00042'

• Encode a string to bytes.
byte_string = "hello".encode('utf-8')

• Decode bytes to a string.
original_string = byte_string.decode('utf-8')


X. Text Vectorization
(Requires pip install scikit-learn)

• Create a Bag-of-Words (BoW) model.
from sklearn.feature_extraction.text import CountVectorizer
corpus = ["This is the first document.", "This is the second document."]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus)

• Get feature names (the vocabulary).
print(vectorizer.get_feature_names_out())

• Create a TF-IDF model.
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(corpus)


XI. More String Utilities

• Center a string within a width.
centered = "Hello".center(20, '-') # '-------Hello--------'

• Check if a string is in title case.
"This Is A Title".istitle() # True

• Find the highest index of a substring.
"test test".rfind("test") # Returns 5

• Split from the right.
"path/to/file.txt".rsplit('/', 1) # ['path/to', 'file.txt']

• Create a character translation table.
table = str.maketrans('aeiou', '12345')
vowels_to_num = "hello".translate(table) # 'h2ll4'

• Remove a specific prefix.
"TestCase".removeprefix("Test") # 'Case'

• Remove a specific suffix.
"filename.txt".removesuffix(".txt") # 'filename'

• Check for unicode decimal characters.
"½".isdecimal() # False
"123".isdecimal() # True

• Check for unicode numeric characters.
"½".isnumeric() # True
"²".isnumeric() # True


#Python #TextProcessing #NLP #RegEx #NLTK

━━━━━━━━━━━━━━━
By: @DataScience4
LlamaIndex | AI Coding Tools

📖 A high-level framework for building RAG and agentic applications.

🏷️ #Python
embedding | AI Coding Glossary

📖 A learned vector representation that maps discrete items, such as words, sentences, documents, images, or users, into a continuous space.

🏷️ #Python
vector database | AI Coding Glossary

📖 A data system optimized for storing and retrieving embedding vectors.

🏷️ #Python
Quiz: A Close Look at a FastAPI Example Application

📖 Practice FastAPI basics with path parameters, request bodies, async endpoints, and CORS. Build confidence to design and test simple Python web APIs.

🏷️ #intermediate #api #web-dev
A Close Look at a FastAPI Example Application

📖 Set up an example FastAPI app, add path and query parameters, and handle CRUD operations with Pydantic for clean, validated endpoints.

🏷️ #intermediate #api #web-dev
💡 Top 50 FastAPI Operations in Python
👇👇👇👇
Please open Telegram to view this post
VIEW IN TELEGRAM
💡 Top 50 FastAPI Operations in Python

I. Basic App & Routing

• Create a FastAPI instance.
from fastapi import FastAPI
app = FastAPI()

• Define a GET endpoint.
@app.get("/")
def read_root():
return {"Hello": "World"}

• Define a POST endpoint.
@app.post("/items/")
def create_item(item: dict):
return item

• Define a path parameter.
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}

• Define a query parameter.
@app.get("/search/")
def search_items(q: str):
return {"query": q}

• Define an optional query parameter.
from typing import Optional
@app.get("/list/")
def list_items(skip: int = 0, limit: Optional[int] = None):
return {"skip": skip, "limit": limit}


II. Request Body & Pydantic Models

• Create a Pydantic model for request body.
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float

• Use a Pydantic model in a POST request.
@app.post("/items/")
def create_item(item: Item):
return item

• Use a Pydantic model with a path parameter.
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_id": item_id, **item.dict()}

• Define a nested Pydantic model.
class User(BaseModel):
username: str
class FullItem(Item):
owner: User


III. Data Validation & Metadata

• Add validation to a query parameter.
from fastapi import Query
@app.get("/items/")
def read_items(q: str = Query(..., min_length=3, max_length=50)):
return {"q": q}

• Add validation to a path parameter.
from fastapi import Path
@app.get("/users/{user_id}")
def read_user(user_id: int = Path(..., gt=0, le=1000)):
return {"user_id": user_id}

• Add metadata (title, description) to a parameter.
q: str = Query(None, title="Search Query", description="Query string")

• Provide an example for a Body field.
from fastapi import Body
item: Item = Body(..., example={"name": "Foo", "price": 35.4})

• Use an alias for a model field.
from pydantic import Field
class Item(BaseModel):
item_name: str = Field(..., alias="itemName")


IV. Response Models & Status Codes

• Set a response status code.
from fastapi import status
@app.post("/items/", status_code=status.HTTP_201_CREATED)
def create_item(item: Item):
return item

• Use response_model to filter output.
class ItemOut(BaseModel):
name: str
@app.post("/items/", response_model=ItemOut)
def create_item(item: Item):
return item

• Exclude fields from response_model.
# Returns all fields from Item model except 'price'
@app.get("/items/{item_id}", response_model=Item, response_model_exclude={"price"})

• Return a direct Response.
from fastapi import Response
@app.get("/legacy/")
def get_legacy_data():
return Response(content="<data>some legacy xml</data>", media_type="application/xml")


V. Dependencies
• Define a simple function dependency.
from fastapi import Depends
async def common_parameters(q: Optional[str] = None):
return {"q": q}

• Inject a dependency into an endpoint.
@app.get("/users/")
async def read_users(commons: dict = Depends(common_parameters)):
return commons

• Create a dependency with yield (for setup/teardown).
async def get_db():
db = DBSession()
try:
yield db
finally:
db.close()

• Use a class as a dependency.
class CommonQueryParams:
def __init__(self, q: Optional[str] = None):
self.q = q

@app.get("/search/")
async def search(commons: CommonQueryParams = Depends()):
return commons


VI. Security

• Setup OAuth2 password flow.
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

• Protect an endpoint with a security dependency.
@app.get("/users/me")
async def read_users_me(token: str = Depends(oauth2_scheme)):
return {"token": token}

• Get the current authenticated user.
async def get_current_user(token: str = Depends(oauth2_scheme)):
# logic to get user from token
return user

@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
return current_user


VII. Advanced Routing

• Create an APIRouter.
from fastapi import APIRouter
router = APIRouter()
@router.get("/users/")
def get_users():
return [{"username": "user1"}]

• Include a router in the main app.
app.include_router(router, prefix="/api/v1", tags=["users"])

• Add tags to endpoints for documentation.
@app.get("/items/", tags=["items"])

• Add a summary and description to an endpoint.
@app.get("/", summary="Root Endpoint", description="Returns a welcome message.")

• Deprecate an endpoint.
@app.get("/old-path", deprecated=True)


VIII. Middleware, Events & Background Tasks

• Create an app startup event.
@app.on_event("startup")
async def startup_event():
print("Application startup")

• Create an app shutdown event.
@app.on_event("shutdown")
def shutdown_event():
print("Application shutdown")

• Add custom middleware.
from fastapi import Request
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
response = await call_next(request)
return response

• Define a background task.
from fastapi import BackgroundTasks
def write_notification(email: str, message=""):
# send email logic
pass

• Add a background task to an endpoint.
@app.post("/send/{email}")
def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, email, message="some notification")
return {"message": "Notification sent"}


IX. Handling Forms, Files & Cookies

• Handle form data.
from fastapi import Form
@app.post("/login/")
def login(username: str = Form(...), password: str = Form(...)):
return {"username": username}

• Handle file uploads.
from fastapi import File, UploadFile
@app.post("/files/")
async def create_file(file: bytes = File(...)):
return {"file_size": len(file)}

• Handle UploadFile (better for large files).
1
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
return {"filename": file.filename, "content_type": file.content_type}

• Set a response cookie.
from fastapi import Response
@app.post("/cookie/")
def create_cookie(response: Response):
response.set_cookie(key="fakesession", value="fake-cookie-session-value")
return {"message": "Cookie set"}

• Read a request cookie.
from fastapi import Cookie
@app.get("/read-cookie/")
def read_cookie(fakesession: Optional[str] = Cookie(None)):
return {"session": fakesession}


X. Error Handling & Advanced Responses

• Handle HTTPException.
from fastapi import HTTPException
@app.get("/items/{item_id}")
def read_item(item_id: str):
if item_id not in items_db:
raise HTTPException(status_code=404, detail="Item not found")

• Return a custom JSONResponse.
from fastapi.responses import JSONResponse
@app.get("/custom/")
def custom_response():
return JSONResponse(status_code=202, content={"message": "Accepted"})

• Return an HTMLResponse.
from fastapi.responses import HTMLResponse
@app.get("/page", response_class=HTMLResponse)
def read_page():
return "<h1>Hello World</h1>"

• Define a WebSocket endpoint.
from fastapi import WebSocket
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
await websocket.send_text("Hello from WebSocket")
await websocket.close()

• Handle a path operation that may not exist.
@app.get("/{full_path:path}")
def read_catch_all(full_path: str):
return {"path": full_path}

• Mount a static files directory.
from fastapi.staticfiles import StaticFiles
app.mount("/static", StaticFiles(directory="static"), name="static")

• Add a custom exception handler.
from fastapi import Request
from fastapi.responses import JSONResponse

class MyCustomException(Exception): pass

@app.exception_handler(MyCustomException)
async def custom_exception_handler(request: Request, exc: MyCustomException):
return JSONResponse(status_code=418, content={"message": "I'm a teapot"})

• Read a request header.
from fastapi import Header
@app.get("/headers/")
async def read_headers(user_agent: Optional[str] = Header(None)):
return {"User-Agent": user_agent}

• Get a raw Request object.
from fastapi import Request
@app.get("/request-info")
def get_request_info(request: Request):
return {"client_host": request.client.host}


#Python #FastAPI #API #WebDevelopment #Pydantic

━━━━━━━━━━━━━━━
By: @DataScience4
💡 Top 50 FastAPI Operations in Python
👇👇👇👇
Please open Telegram to view this post
VIEW IN TELEGRAM
💡 Top 70 Django ORM Operations

I. Model Definition
(in models.py)

• Define a character field.
from django.db import models
name = models.CharField(max_length=100)

• Define a foreign key relationship (many-to-one).
author = models.ForeignKey('Author', on_delete=models.CASCADE)

• Define a many-to-many relationship.
tags = models.ManyToManyField('Tag')

• Define a model's Meta class for default ordering.
class Meta:
ordering = ['-pub_date']

• Define the string representation of an object.
def __str__(self):
return self.headline


II. Creating Objects

• Create and save an object in one step.
entry = Entry.objects.create(headline="New Title", author=some_author)

• Create an instance and save it separately.
new_author = Author(name="John Doe")
new_author.save()

• Create multiple objects in a single query.
Author.objects.bulk_create([Author(name="A"), Author(name="B")])

• Add an object to a ManyToManyField.
entry.tags.add(tag1, tag2)


III. Retrieving Objects (Basic QuerySets)

• Retrieve all objects.
all_entries = Entry.objects.all()

• Retrieve a single object by a unique constraint (e.g., PK).
entry = Entry.objects.get(pk=1)

• Filter objects that match criteria.
entries = Entry.objects.filter(pub_date__year=2023)

• Exclude objects that match criteria.
entries = Entry.objects.exclude(headline__startswith="Old")

• Get the first object from a queryset.
first_entry = Entry.objects.order_by('pub_date').first()

• Get the last object from a queryset.
last_entry = Entry.objects.order_by('pub_date').last()

• Get an object, or create it if it doesn't exist.
obj, created = Author.objects.get_or_create(name="Unique Name")


IV. Field Lookups for Filtering

• Exact match (case-sensitive).
Entry.objects.filter(headline__exact="Hello World")

• Case-insensitive exact match.
Entry.objects.filter(headline__iexact="hello world")

• Case-sensitive contains.
Entry.objects.filter(headline__contains="World")

• Case-insensitive contains.
Entry.objects.filter(headline__icontains="world")

• Match against a list of values.
Entry.objects.filter(pk__in=[1, 3, 5])

• Greater than (__gt) or greater than or equal (__gte).
Entry.objects.filter(rating__gt=4)

• Less than (__lt) or less than or equal (__lte).
Entry.objects.filter(rating__lte=3)

• Starts with or ends with a string.
Entry.objects.filter(headline__startswith="The")

• Match within a range.
Entry.objects.filter(pub_date__range=["2023-01-01", "2023-03-31"])

• Filter by a date component.
Entry.objects.filter(pub_date__year=2023, pub_date__month=5)

• Check if a field is NULL.
Entry.objects.filter(pub_date__isnull=True)


V. Slicing & Ordering QuerySets

• Slice a queryset (similar to Python lists).
first_ten = Entry.objects.all()[:10]

• Order results in ascending order.
Entry.objects.order_by('headline')

• Order results in descending order.
Entry.objects.order_by('-pub_date')

• Order results randomly.
Entry.objects.order_by('?')


VI. Modifying Objects

• Update a single object's fields.
entry = Entry.objects.get(pk=1)
entry.rating = 5
entry.save()

• Update multiple objects in a single query.
Entry.objects.filter(pub_date__year=2022).update(rating=0)

• Remove an object from a ManyToManyField.
entry.tags.remove(tag1)


VII. Deleting Objects

• Delete a single object.
entry = Entry.objects.get(pk=1)
entry.delete()

• Delete multiple objects in a single query.
Entry.objects.filter(rating=0).delete()


VIII. Spanning Relationships

• Filter based on a related model's field.
Entry.objects.filter(author__name="John Doe")

• Use a field lookup on a related model.
Entry.objects.filter(author__name__startswith="John")

• Access related objects from the "one" side of a relationship.
author = Author.objects.get(name="John Doe")
authors_entries = author.entry_set.all()


IX. Aggregation
(Requires from django.db.models import ...)

• Calculate aggregate values over an entire queryset.
from django.db.models import Avg
avg_rating = Entry.objects.aggregate(Avg('rating'))

• Average (Avg).
Entry.objects.aggregate(average_rating=Avg('rating'))

• Sum (Sum).
Entry.objects.aggregate(total_ratings=Sum('rating'))

• Maximum (Max) and Minimum (Min).
Entry.objects.aggregate(max_r=Max('rating'), min_r=Min('rating'))

• Count (Count).
Entry.objects.aggregate(num_entries=Count('pk'))

• Count distinct values.
Entry.objects.aggregate(num_authors=Count('author', distinct=True))


X. Annotation

• Add a calculated field to each object in a queryset.
from django.db.models import Count
authors = Author.objects.annotate(entry_count=Count('entry'))

• Access an annotated value.
for author in authors:
print(author.name, author.entry_count)

• Get results as a list of dictionaries.
Entry.objects.values('headline', 'author__name')


XI. F() Expressions

• Import F() expressions.
from django.db.models import F

• Update a field based on its own value.
Entry.objects.filter(pk=1).update(rating=F('rating') + 1)

• Filter by comparing two fields on the same model.
Entry.objects.filter(rating__gt=F('author__rating'))


XII. Q() Objects

• Import Q() objects for complex queries.
from django.db.models import Q

• Create an OR query.
Entry.objects.filter(Q(headline__startswith='A') | Q(headline__startswith='B'))

• Create a NOT query.
Entry.objects.filter(~Q(headline__icontains='boring'))


XIII. QuerySet Evaluation

• Get the count of objects efficiently.
count = Entry.objects.count()

• Check if any objects exist efficiently.
exists = Entry.objects.filter(rating=5).exists()

• Get the count (evaluates the full queryset).
count = len(Entry.objects.all())

• Check for existence (evaluates the full queryset).
if Entry.objects.filter(rating=5): # True if queryset is not empty
...

• Iteration (evaluates the queryset).
for entry in Entry.objects.all():
print(entry.headline)


XIV. Optimization
• Fetch related ForeignKey objects in the same query.
entries = Entry.objects.select_related('author').all()

• Fetch related ManyToManyField objects in a separate efficient query.
entries = Entry.objects.prefetch_related('tags').all()

• Load only specific model fields.
entries = Entry.objects.only('headline')

• Defer loading of specific model fields.
entries = Entry.objects.defer('body_text')

• Execute raw, unmanaged SQL.
authors = Author.objects.raw('SELECT * FROM myapp_author')

• Get results as a list of tuples.
Entry.objects.values_list('headline', 'pub_date')


XV. Transactions

• Import the transaction module.
from django.db import transaction

• Run a block of code within a database transaction.
with transaction.atomic():
# All database operations here are either committed together or rolled back.
author.save()
entry.save()


XVI. Managers & Model Methods

• Create a custom Manager for common queries.
class PublishedEntryManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='published')

• Add a custom method to a QuerySet via its Manager.
Entry.objects.get_queryset().by_author("John Doe")

• Add a custom method to a model for object-specific logic.
class Entry(models.Model):
#...
def is_recent(self):
return self.pub_date > timezone.now() - timedelta(days=1)


#Python #Django #ORM #Database #Backend

━━━━━━━━━━━━━━━
By: @DataScience4
1
inference | AI Coding Glossary

📖 The phase where a trained model processes new inputs to produce outputs.

🏷️ #Python