Learn Python Coding
Learn Python through simple, practical examples and real coding ideas. Clear explanations, useful snippets, and hands-on learning for anyone starting or improving their programming skills. Admin: @HusseinSheikho || @Hussein_Sheikho
Больше📈 Аналитический обзор Telegram-канала Learn Python Coding
Канал Learn Python Coding (@pythonre) языкового сегмента Английский является активным участником. Сейчас сообщество объединяет 40 869 подписчиков, занимая 3 289 место в категории Технологии и приложения и 9 124 место в регионе Индия.
📊 Показатели аудитории и динамика
С момента создания невідомо проект демонстрирует стремительный рост, собрав аудиторию из 40 869 подписчиков.
Согласно последним данным от 30 октября, 2026, канал показывает стабильную активность. За последние 30 дней изменение числа участников составило 330, а за последние 24 часа — 1, при этом общий охват остаётся высоким.
- Статус верификации: Не верифицирован
- Уровень вовлечённости (ER): Средний показатель вовлечённости аудитории составляет 5.55%. В первые 24 часа после публикации контент обычно набирает 1.63% реакций от общего числа подписчиков.
- Охват публикаций: В среднем каждый пост получает 2 270 просмотров. В течение первых суток публикация набирает 665 просмотров.
- Реакции и взаимодействия: Аудитория активно поддерживает контент: среднее количество реакций на один пост — 3.
- Тематические интересы: Контент сосредоточен на ключевых темах, таких как math, harvard, oxford, supervision, waybienad.
📝 Описание и контентная политика
Автор описывает ресурс как площадку для выражения субъективного мнения:
“Learn Python through simple, practical examples and real coding ideas. Clear explanations, useful snippets, and hands-on learning for anyone starting or improving their programming skills.
Admin: @HusseinSheikho || @Hussein_Sheikho”
Благодаря высокой частоте обновлений (последние данные получены 31 октября, 2026) канал поддерживает актуальность и высокий уровень охвата публикаций. Аналитика показывает, что аудитория активно взаимодействует с контентом, что делает его важной точкой влияния в категории Технологии и приложения.
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.@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 ✨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).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. Dependenciesfrom 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 ✨
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() # TrueV. 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.