Code With Python
39K subscribers
842 photos
24 videos
22 files
747 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
🏆 Connecting Python to MySQL: `mysql-connector`

📢 Master connecting Python to MySQL with `mysql-connector-python`, and troubleshoot 'module not found' errors for seamless data integration.

Tap to unlock the complete answer and gain instant insight.

━━━━━━━━━━━━━━━
By: @DataScience4
2👍1
🏆 Generate Website Screenshots with Python Flask

📢 Generate website screenshots effortlessly! Learn to build your own tool using Python and Flask. Essential for web development and QA.

Tap to unlock the complete answer and gain instant insight.

━━━━━━━━━━━━━━━
By: @DataScience4
How to Convert Bytes to Strings in Python

📖 Turn Python bytes to strings, pick the right encoding, and validate results with clear error handling strategies.

🏷️ #basics
1
Tip for clean tests in Python:

In most cases, your tests should cover:

- all happy path scenarios
- edge/corner/boundary cases
- negative tests
- security checks and invalid inputs

import uuid
from dataclasses import dataclass
from typing import Optional


@dataclass
class User:
    username: str


class InMemoryUserRepository:
    def __init__(self):
        self._users = []

    def add(self, user: User) -> None:
        self._users.append(user)

    def search(self, query: Optional[str] = None) -> list[User]:
        if query is None:
            return self._users
        else:
            return [
                user
                for user in self._users
                if query in user.username
            ]


# happy path
def test_search_users_without_query_lists_all_users():
    user1 = User(username="john@doe.com")
    user2 = User(username="marry@doe.com")
    repository = InMemoryUserRepository()
    repository.add(user1)
    repository.add(user2)

    assert repository.search() == [user1, user2]


# happy path
def test_search_users_with_email_part_lists_all_matching_users():
    user1 = User(username="john@doe.com")
    user2 = User(username="bob@example.com")
    user3 = User(username="marry@doe.com")
    repository = InMemoryUserRepository()
    repository.add(user1)
    repository.add(user2)
    repository.add(user3)

    assert repository.search("doe") == [user1, user3]


# edge test case
def test_search_users_with_empty_query_lists_all_users():
    user1 = User(username="john@doe.com")
    user2 = User(username="marry@doe.com")
    repository = InMemoryUserRepository()
    repository.add(user1)
    repository.add(user2)

    assert repository.search("") == [user1, user2]


# negative test case
def test_search_users_with_random_query_lists_zero_users():
    user1 = User(username="john@doe.com")
    repository = InMemoryUserRepository()
    repository.add(user1)

    assert repository.search(str(uuid.uuid4())) == []


# security test
def test_search_users_with_sql_injection_has_no_effect():
    user1 = User(username="john@doe.com")
    repository = InMemoryUserRepository()
    repository.add(user1)

    repository.search("DELETE FROM USERS;")
    assert repository.search() == [user1]


👉 @DataScience4
Please open Telegram to view this post
VIEW IN TELEGRAM
5👍3
Quiz: How to Serve a Website With FastAPI Using HTML and Jinja2

📖 Review how to build dynamic websites with FastAPI and Jinja2, and serve HTML, CSS, and JS with HTMLResponse and StaticFiles.

🏷️ #intermediate #api #front-end #web-dev
How to Use Google's Gemini CLI for AI Code Assistance

📖 Learn how to use Gemini CLI to bring Google's AI-powered coding assistance directly into your terminal to help you analyze and fix code.

🏷️ #intermediate #ai #tools
evaluation | AI Coding Glossary

📖 The process of measuring how well an AI system or model meets its objectives.

🏷️ #Python
1
vector | AI Coding Glossary

📖 An ordered array of numbers that represents a point, magnitude, and direction.

🏷️ #Python
Topic: Python Standard Library

📖 Practical Python standard library tutorials to master datetime, pathlib, argparse, subprocess, logging, and more. Write faster, cleaner, dependency-free code.

🏷️ #86_resources
1
Topic: Algorithms Tutorials

📖 Learn Python algorithms: sorting, searching, graphs, DP, Big O. Use heapq, bisect, deque, lru_cache, timeit. Study practical tips and FAQs for interviews.

🏷️ #22_resources
1
Meet Our Team

📖 Meet Real Python's team of expert Python developers, educators, and 190+ contributors bringing real-world experience to create practical Python education.

🏷️ #Python
🔥1
Pydantic AI | AI Coding Tools

📖 A Python framework for building typed LLM agents leveraging Pydantic.

🏷️ #Python
bias | AI Coding Glossary

📖 A systematic deviation from truth or fairness.

🏷️ #Python
1
Google Antigravity | AI Coding Tools

📖 An agent-first IDE where AI agents operate the editor, terminal, and browser and produce verifiable Artifacts of their work.

🏷️ #Python
nearest neighbor | AI Coding Glossary

📖 The data point in a reference set that has the smallest distance to a query point.

🏷️ #Python
autoregressive generation | AI Coding Glossary

📖 A method in which a model produces a sequence one token at a time, with each token conditioned on all previously generated tokens.

🏷️ #Python
Quiz: Build a Python MCP Client to Test Servers From Your Terminal

📖 Learn how to create a Python MCP client, start an AI-powered chat session, and run it from the command line. Check your understanding.

🏷️ #intermediate #ai #projects
3
💀 How to encrypt a PDF with a password using Python

Ready Python script: takes a regular PDF and creates a password-protected copy.

📦 Library installation
pip install PyPDF2


⌨️ Code
from __future__ import annotations
from pathlib import Path
from typing import Union

from PyPDF2 import PdfReader, PdfWriter

PDFPath = Union[str, Path]


def encrypt_pdf(input_path: PDFPath, output_path: PDFPath, password: str) -> Path:
    """
    Encrypts a PDF file with a password and saves it to output_path.
    Returns the path to the encrypted file.
    """
    in_path = Path(input_path)
    out_path = Path(output_path)

    reader = PdfReader(in_path)
    writer = PdfWriter()

    for page in reader.pages:
        writer.add_page(page)

    writer.encrypt(password)

    with out_path.open("wb") as f:
        writer.write(f)

    return out_path


def encrypt_with_suffix(input_path: PDFPath, password: str, suffix: str = "_encrypted") -> Path:
    """
    Creates an encrypted copy next to the original file.
    For example: secret.pdf → secret_encrypted.pdf
    """
    in_path = Path(input_path)
    output_path = in_path.with_name(f"{in_path.stem}{suffix}{in_path.suffix}")
    return encrypt_pdf(in_path, output_path, password)


if __name__ == "__main__":
    pdf_file = "secret.pdf"
    pdf_password = "pythontoday"

    encrypted_path = encrypt_with_suffix(pdf_file, pdf_password)
    print(f"Encrypted file created: {encrypted_path}")


💡 Where it will be useful

🟢send a document to a client with the password via a separate channel;
🟢store important PDFs in encrypted form;
🟢integrate encryption into your service/bot/admin panel.

#python #code #tipsandtricks

https://t.me/DataScience4 🌟
Please open Telegram to view this post
VIEW IN TELEGRAM
4👍1👎1
4🔥1