Monday, 3 November 2025

#21a Dunder Method - Samples

Python Dunder (Magic) Methods – Complete Guide with Demos

Python Dunder (Magic) Methods – Complete Guide with Demos

Click Run to execute examples or Copy to copy code. Works directly inside Blogger.

Click here for Key characteristics of DUNDER (DOUBLE Under Score ___) methods:

Dunder methods, also known as magic methods or special methods, are a core feature in Python that allow classes to interact with the language's built-in functions and operators. The term "dunder" is a contraction of "double underscore," referring to the fact that these methods are named with double underscores at both the beginning and end (e.g., __init__, __add__, __str__).

Implicit Invocation: Dunder methods are typically not called directly by the programmer. Instead, they are implicitly invoked by the Python interpreter in response to specific actions or operations. For example, when you use the + operator on two objects, Python implicitly calls the __add__ dunder method of the first object.

Operator Overloading: Dunder methods enable operator overloading, allowing you to define custom behavior for operators (like +, -, *, ==, []) when applied to instances of your classes. This makes your custom objects behave more like native Python types. Integration with Built-in Functions: Many built-in Python functions (such as len(), str(), int()) rely on corresponding dunder methods (__len__, __str__, __int__) to determine how they should interact with instances of your classes.

Customizing Class Behavior: Dunder methods allow you to customize various aspects of your class's behavior,

including object initialization (__init__), object representation (__str__, __repr__), attribute access (__getattr__, __setattr__), and iteration (__iter__, __next__).

Examples of common dunder methods:

  • __init__: Called when a new instance of a class is created, used for initialization.
  • __str__: Defines the informal string representation of an object (what print() shows).
  • __repr__: Defines the official string representation of an object, often used for debugging.
  • __add__, __sub__, __mul__: Define behavior for arithmetic operations.
  • __len__: Defines the behavior of the len() function for an object.
  • __getitem__, __setitem__: Define behavior for indexing and slicing (e.g., obj[key]).

By implementing dunder methods in your classes, you can create more robust, intuitive, and "Pythonic" custom objects that seamlessly integrate with the language's features.

__init__ – Initialize instance attributes

class Person:
    def __init__(self, name):
        self.name = name
        print("Hello", self.name)

Person("Alice")

__repr__ – Developer representation

class Point:
    def __init__(self, x, y): self.x, self.y = x, y
    def __repr__(self): return f"Point({self.x},{self.y})"

p = Point(2,3)
print(repr(p))

__str__ – User-friendly string

class Point:
    def __init__(self, x, y): self.x, self.y = x, y
    def __str__(self): return f"({self.x},{self.y})"

print(Point(1,4))

__add__ – Add two objects

class Vec:
    def __init__(self, x, y): self.x, self.y = x, y
    def __add__(self, o): return Vec(self.x + o.x, self.y + o.y)
    def __repr__(self): return f"Vec({self.x},{self.y})"

print(Vec(1,2)+Vec(3,4))

__len__ – Object length

class L:
    def __init__(self, data): self.data = data
    def __len__(self): return len(self.data)

print(len(L([1,2,3])))

__getitem__ – Index access

class Seq:
    def __init__(self): self.data = [10,20,30]
    def __getitem__(self, k): return self.data[k]

s = Seq()
print(s[1])

__call__ – Make instance callable

class Adder:
    def __init__(self, n): self.n = n
    def __call__(self, x): return x + self.n

add5 = Adder(5)
print(add5(10))

__enter__ / __exit__ – Context manager

class Ctx:
    def __enter__(self): print("enter"); return self
    def __exit__(self,exc,val,tb): print("exit")

with Ctx(): print("inside")

__bool__ – Truth value

class C:
    def __init__(self, items): self.items = items
    def __bool__(self): return len(self.items) > 0

print(bool(C([])), bool(C([1])))

__hash__ – Hashable object

class H:
    def __init__(self,v): self.v=v
    def __hash__(self): return hash(self.v)

print({H(5): 'ok'})
© Python Dunder Methods Demo | Works inside Blogger | Built with Pyodide Runtime

#21 Python Dunder Methods - Magic Feature

Complete Python Dunder Methods — Interactive Guide

Complete Python Dunder Methods — Interactive Guide

All common dunder (magic) methods are listed below. Each method has: ℹ️ info (hover/tap), a code snippet, Copy, Run, and a collapsible output panel. The examples are minimal demonstrations so you can run them safely in the browser using Pyodide.

Index — Click to jump

Sunday, 2 November 2025

#20b Python (run+edit in browser ^ all in one)

🐍 Python Basics — 5 Interactive Modules

Edit code live with syntax highlighting and click ▶ Run. Each module runs separately via Pyodide.

Module 1 — Hello & Print

Your first Python program using print() and input().
💬 Show Output
— output here —

Module 2 — Variables & Types

Numbers, strings, booleans, and type checking.
💬 Show Output
— output here —

Module 3 — Control Flow

Using if/else, loops, and range().
💬 Show Output
— output here —

Module 4 — Functions & Modules

Defining functions and using the math library.
💬 Show Output
— output here —

Module 5 — Lists & Comprehensions

Creating lists, slicing, and list comprehensions.
💬 Show Output
— output here —

#20a Python Run

🐍 Python Basics — 5 Interactive Modules

Each module runs separately via Pyodide. Output appears right below the code. Colored console output: 🟢 stdout / 🔴 stderr / 🟣 status

Module 1 — Hello & Print

Your first Python program — using print() and input().
# Module 1 — Hello & print
name = input("What's your name? ")
print(f"Hello, {name}! Welcome to Python basics.")
— output here —

Module 2 — Variables & Types

Numbers, strings, booleans, and type checking.
x = 42
y = 3.14
name = "Ada"
is_ready = True

print(x, type(x))
print(y, type(y))
print(name.upper(), type(name))
print("Is ready?", is_ready)
— output here —

Module 3 — Control Flow

Using if/else, loops, and range().
n = 5
for i in range(1, n+1):
    if i % 2 == 0:
        print(i, "is even")
    else:
        print(i, "is odd")

count = 3
while count > 0:
    print("Counting down:", count)
    count -= 1
— output here —

Module 4 — Functions & Modules

Defining functions and using Python's standard library.
import math

def circle_area(radius):
    return math.pi * radius ** 2

r = 2.5
print(f"Area of circle with radius {r} is {circle_area(r):.3f}")
— output here —

Module 5 — Lists & Comprehensions

Creating lists, slicing, and list comprehensions.
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
evens = [n for n in numbers if n % 2 == 0]
print("numbers:", numbers)
print("squares:", squares)
print("evens:", evens)
print("first two:", numbers[:2])
— output here —

#20 Python Revisit ( + In Browser Python Run)

Python basics — 5 modules (interactive)

Syntax highlighting via Prism.js. In-browser execution via Pyodide. Colored console output: 🟢 stdout / 🔴 stderr / 🟣 status.

Interactive runner

Paste examples into the editor (or use Copy & Use from any module) and click Run. Output appears below.
Editor
Pyodide status: loading...
Quick snippets
Console output
— ready —

Module 1 — Hello & print

The first program: printing to console, comments, and basic I/O.
# Module 1 — Hello & print
name = input("What's your name? ")
print(f"Hello, {name}! Welcome to Python basics.")

Module 2 — Variables & Types

Numbers, strings, booleans, and type checking.
x = 42
y = 3.14
name = "Ada"
is_ready = True

print(x, type(x))
print(y, type(y))
print(name.upper(), type(name))
print("Is ready?", is_ready)

Module 3 — Control Flow

if/else, for loops, while loops, and range.
n = 5
for i in range(1, n+1):
    if i % 2 == 0:
        print(i, "is even")
    else:
        print(i, "is odd")

count = 3
while count > 0:
    print("Counting down:", count)
    count -= 1

Module 4 — Functions & Modules

Defining functions, parameters, return values, and importing a module.
import math

def circle_area(radius):
    return math.pi * radius ** 2

r = 2.5
print(f"Area of circle with radius {r} is {circle_area(r):.3f}")

Module 5 — Lists & Comprehensions

Creating lists, indexing, slicing, and list comprehensions.
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
evens = [n for n in numbers if n % 2 == 0]
print("numbers:", numbers)
print("squares:", squares)
print("evens:", evens)
print("first two:", numbers[:2])

Wednesday, 22 October 2025

#19 Web site Demo

Python Website Demo: Full Tutorial (Login, Projects, Customers, Stories)

Python Website Demo Tutorial

Build a complete demo web application using Python + Flask, featuring: login, projects, customers, and success stories pages. Each module gets you closer to a real-world site!

Module 1: Setup & Install Flask

pip install flask flask-login
mkdir pywebdemo
cd pywebdemo
touch app.py
mkdir templates static

Module 2: Base Flask App & Page Routing

# app.py
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/projects')
def projects():
    return render_template('projects.html')

@app.route('/customers')
def customers():
    return render_template('customers.html')

@app.route('/stories')
def stories():
    return render_template('stories.html')

if __name__ == '__main__':
    app.run(debug=True)

Module 3: Basic Page Templates

<!-- templates/home.html -->
<h1>Welcome to Demo Company</h1>
<a href="/login">Login</a> | <a href="/projects">Projects</a> | <a href="/customers">Customers</a> | <a href="/stories">Success Stories</a>
<!-- templates/projects.html -->
<h2>Our Projects</h2>
<ul>
  <li>Project A: AI Web Platform</li>
  <li>Project B: Mobile Solution</li>
</ul>
<!-- templates/customers.html -->
<h2>Our Customers</h2>
<ul>
  <li>Customer Alpha</li>
  <li>Customer Beta</li>
</ul>
<!-- templates/stories.html -->
<h2>Success Stories</h2>
<p>Customer Alpha tripled sales with our platform!</p>
<p>Customer Beta expanded globally with our mobile tech.</p>

Module 4: Login Page & User System

# app.py (add)
from flask import request, flash
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user

app.secret_key = 'REPLACE_WITH_A_SECRET_KEY'
login_manager = LoginManager()
login_manager.init_app(app)

# Simple Fake User
class User(UserMixin):
    def __init__(self, id):
        self.id = id

@login_manager.user_loader
def load_user(user_id):
    return User(user_id)
# app.py (add route)
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        if request.form['username'] == 'admin' and request.form['password'] == 'password':
            user = User('admin')
            login_user(user)
            return redirect(url_for('home'))
        else:
            flash('Bad credentials!')
    return render_template('login.html')
<!-- templates/login.html -->
<form method="POST">
  <label>Username:</label>
  <input name="username" type="text"><br>
  <label>Password:</label>
  <input name="password" type="password"><br>
  <button type="submit">Login</button>
</form>
{% with messages = get_flashed_messages() %}
  {% if messages %}
    <p style="color:red;">{{ messages[0] }}</p>
  {% endif %}
{% endwith %}
# app.py (add route)
@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('home'))

Module 5: Protected Pages and Navigation

# app.py (protect routes)
@app.route('/admin')
@login_required
def admin():
    return "

Admin Only Page

"

Module 6: Basic Styling and Navigation Bar

<!-- templates/base.html -->
<nav>
  <a href="/">Home</a> | 
  <a href="/projects">Projects</a> | 
  <a href="/customers">Customers</a> | 
  <a href="/stories">Success Stories</a> | 
  {% if current_user.is_authenticated %}
    <a href="/logout">Logout</a>
  {% else %}
    <a href="/login">Login</a>
  {% endif %}
</nav>
<hr>
{% block content %}{% endblock %}
<!-- Usage: in your pages -->
{% extends "base.html" %}
{% block content %}
  ...page content...
{% endblock %}
/* static/style.css */
body { font-family: Arial, sans-serif; background: #f7faff; }
nav { font-size: 1.2em; margin-bottom: 12px; }
a { color: #00adb5; text-decoration: none; margin-right: 10px; }
hr { margin-bottom: 30px; }

Module 7: Adding Fake Data for Projects & Customers

# app.py
projects_data = [
  {"title": "AI Web Platform", "desc": "Cutting-edge machine learning project."},
  {"title": "Mobile Solution", "desc": "Cross-platform mobile app."}
]
customers_data = ["Customer Alpha", "Customer Beta"]

@app.route('/projects')
def projects():
    return render_template('projects.html', projects=projects_data)

@app.route('/customers')
def customers():
    return render_template('customers.html', customers=customers_data)
{% extends "base.html" %}
{% block content %}
  <h2>Our Projects</h2>
  <ul>
    {% for p in projects %}
      <li><b>{{ p.title }}</b> — {{ p.desc }}</li>
    {% endfor %}
  </ul>
{% endblock %}

Module 8: Success Stories Dynamic Content

# app.py
stories_data = [
  {"customer": "Alpha", "story": "Tripled sales!"},
  {"customer": "Beta", "story": "Expanded globally!"}
]

@app.route('/stories')
def stories():
    return render_template('stories.html', stories=stories_data)
{% extends "base.html" %}
{% block content %}
  <h2>Success Stories</h2>
  <ul>
    {% for s in stories %}
      <li><b>{{ s.customer }}:</b> {{ s.story }}</li>
    {% endfor %}
  </ul>
{% endblock %}

Module 9: Flash Messages & User Feedback

# On login fail (see login above)
flash('Bad credentials!')
{% with messages = get_flashed_messages() %}
  {% if messages %}
    <div style="color:red;">
    {% for message in messages %}
      {{ message }}<br>
    {% endfor %}
    </div>
  {% endif %}
{% endwith %}

Module 10: Finalizing & Running Your Demo Website

export FLASK_APP=app.py
flask run
  1. Visit http://127.0.0.1:5000/ in your browser.
  2. Login using admin / password (demo only).
  3. Explore projects, customers, and stories pages.
  4. You can expand with databases, forms, and REST APIs later!
This boilerplate gives you a fast way to try out and demo a real Python-based web application!

#18 gmail AUthentication

Gmail Authentication with Django: Step-by-Step Tutorial

Gmail Authentication in Django: Step-by-Step Tutorial

Learn how to set up Gmail (Google) authentication on your Django site using the popular third-party package django-allauth. This method lets users log in or sign up with their Google account in a secure, scalable way.

Step 1: Install Required Packages

pip install django-allauth

Step 2: Add Apps and Settings in settings.py

INSTALLED_APPS = [
    # Django default apps...
    "django.contrib.sites",
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    "allauth.socialaccount.providers.google",
]

SITE_ID = 1

AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
]

LOGIN_REDIRECT_URL = "/"

Step 3: Add Allauth URLs to Project

# mysite/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path("accounts/", include("allauth.urls")),
]

Step 4: Create a Google OAuth App

  • Go to Google Cloud Console > APIs & Services > Credentials
  • Create a new OAuth Client ID (Web application)
  • Add authorized redirect URI: http://localhost:8000/accounts/google/login/callback/
  • Save your Client ID and Secret.

Step 5: Configure Google Provider in Django Admin

  1. Run the server and log in to /admin
  2. Find Sites and make sure domain is localhost
  3. Find Social applications and add Google:
    • Provider: Google
    • Name: Google
    • Client ID: (your Google client ID)
    • Secret Key: (your Google secret)
    • Sites: Select your current site

Step 6: Customizing Login Button in Template

<a href="{% provider_login_url 'google' %}">
  Login with Google
</a>

Step 7: Try It Out!

  • Visit /accounts/login/ and click Login with Google
  • Authenticate with your Gmail account
  • Get redirected to your app, now signed in!

Extra: Customizing Forms, User Model, and Redirects

  • Override templates in templates/account/
  • Extend user model for extra fields if needed
  • Change LOGIN_REDIRECT_URL for custom flows
With django-allauth, you can add many other social providers easily (Facebook, Twitter, etc).

#17 Django

Django Masterclass: 10 Modules to Professional Web Apps

Django Masterclass: 10 Modules to Professional Web Apps

Step up to building robust, scalable web applications with Django! This 10-part blog series takes you from setup to production deployment through hands-on modules with code, explanations, and best practices.

Module 1: Introduction to Django & Installation

pip install django
django-admin startproject mysite
cd mysite
python manage.py runserver

Module 2: Django App Structure Explained

python manage.py startapp blog
  • mysite/ (project root)
  • blog/ (your app: models, views, templates)
  • manage.py (Django CLI)

Module 3: Models and Admin

# blog/models.py
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True)
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser

Module 4: Views and URLs

# blog/views.py
from django.shortcuts import render
from .models import Post

def post_list(request):
    posts = Post.objects.all()
    return render(request, "post_list.html", {"posts": posts})
# blog/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path("", views.post_list, name="post_list"),
]
# mysite/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("blog.urls")),
]

Module 5: Templates and Static Files

{% for post in posts %}
  <h2>{{ post.title }}</h2>
  <p>{{ post.body }}</p>
  <small>{{ post.pub_date }}</small>
{% endfor %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
python manage.py collectstatic

Module 6: Forms and User Input

# blog/forms.py
from django import forms

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ["title", "body"]
<form method="POST">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Publish</button>
</form>

Module 7: Authentication (Login, Logout, Signup)

from django.contrib.auth import login, logout, authenticate
# Use Django's built-in auth views, templates, and User model for user management.
# mysite/urls.py (add)
from django.contrib.auth import views as auth_views
urlpatterns += [
    path("login/", auth_views.LoginView.as_view(), name="login"),
    path("logout/", auth_views.LogoutView.as_view(), name="logout"),
]
<a href="{% url 'login' %}">Log In</a>
<a href="{% url 'logout' %}">Log Out</a>

Module 8: Advanced Features – Class-based Views & Pagination

from django.views.generic import ListView
from .models import Post

class PostListView(ListView):
    model = Post
    paginate_by = 5
    template_name = "post_list.html"
# blog/urls.py (add)
path("posts/", PostListView.as_view(), name="post_list"),

Module 9: REST API with Django Rest Framework

pip install djangorestframework
# blog/api.py
from rest_framework import viewsets
from .models import Post
from .serializers import PostSerializer

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
# blog/serializers.py
from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = "__all__"
# mysite/urls.py (add)
from rest_framework import routers
from blog.api import PostViewSet

router = routers.DefaultRouter()
router.register(r"posts", PostViewSet)
urlpatterns += [
    path("api/", include(router.urls)),
]

Module 10: Deployment to Production

  1. Create requirements.txt:
    pip freeze > requirements.txt
    
  2. Push to GitHub
    git init
    git add .
    git commit -m "Deploy Django app"
    git remote add origin https://github.com/yourname/yourrepo.git
    git push -u origin master
    
  3. Deploy on Render, Heroku, or any cloud provider:
    web: gunicorn mysite.wsgi
    
  4. Collect static files on server:
    python manage.py collectstatic
    
Django supports secure admin, scalable apps, and RESTful APIs with best practices and rapid development.

#16 FAST API

FastAPI Masterclass: 10 Modules

FastAPI Masterclass: Build & Deploy APIs in 10 Modules

This comprehensive guide introduces you to FastAPI, the modern Python framework for building high-performance APIs and web apps. Each module builds on the next, taking you from setup to deployment.

Module 1: Introduction to FastAPI

FastAPI is a high-performance web framework built for speed with async support. Install it and run your first app.

pip install fastapi uvicorn
# app.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello FastAPI"}

# Run with: uvicorn app:app --reload

Module 2: Path and Query Parameters

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "query": q}

Module 3: Request Body with Pydantic

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    is_offer: bool | None = None

@app.post("/items/")
def create_item(item: Item):
    return {"item": item}

Module 4: Handling Responses

Customize your JSON responses and status codes.

from fastapi.responses import JSONResponse

@app.get("/custom")
def custom_response():
    return JSONResponse(content={"status": "success"}, status_code=201)

Module 5: Error Handling

from fastapi import HTTPException

@app.get("/divide")
def divide(a: int, b: int):
    if b == 0:
        raise HTTPException(status_code=400, detail="Division by zero not allowed")
    return {"result": a / b}

Module 6: Background Tasks

from fastapi import BackgroundTasks

def write_log(message: str):
    with open("log.txt", "a") as f:
        f.write(f"{message}\n")

@app.post("/log/")
def log_message(background_tasks: BackgroundTasks, message: str):
    background_tasks.add_task(write_log, message)
    return {"status": "Task scheduled"}

Module 7: Working with Databases (SQLite + SQLAlchemy)

pip install sqlalchemy
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)

Base.metadata.create_all(bind=engine)

Module 8: Authentication with FastAPI

from fastapi.security import OAuth2PasswordBearer
from fastapi import Depends

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/users/me")
def read_current_user(token: str = Depends(oauth2_scheme)):
    return {"token": token}

Module 9: Building a RESTful API

users = []

@app.post("/users/")
def create_user(name: str):
    user = {"id": len(users) + 1, "name": name}
    users.append(user)
    return user

@app.get("/users/")
def get_users():
    return users

Module 10: Deploying FastAPI (Using Uvicorn + Git)

  1. Create a requirements.txt file:
    pip freeze > requirements.txt
    
  2. Create a Procfile for Heroku/Render:
    web: uvicorn app:app --host=0.0.0.0 --port=$PORT
    
  3. Push to GitHub and Deploy via Render or Heroku Dashboard.
FastAPI automatically generates interactive API docs at /docs and /redoc!

#15 Locate your phone number

Flask: Locate Phone Numbers by Region & Carrier

Build a Flask App to Locate Phone Numbers

This guide shows you how to create a Python Flask web tool that locates phone numbers—revealing region and carrier information using the phonenumbers library.

Step 1: Install Requirements

pip install Flask phonenumbers

Step 2: Create the Flask App (app.py)

from flask import Flask, request, render_template_string
import phonenumbers
from phonenumbers import geocoder, carrier

app = Flask(__name__)

TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
    <title>Phone Number Locator</title>
    <style>
        body { font-family: Arial, sans-serif; margin:40px; }
        .container { max-width: 500px; margin: auto; }
        input[type=text] { width: 80%; padding: 8px; }
        input[type=submit] { padding: 8px 16px; }
        .result { margin-top:20px; background: #f0fafc; padding: 16px; border-radius: 5px;}
    </style>
</head>
<body>
    <div class="container">
        <h2>Phone Number Locator</h2>
        <form method="post">
            <label for="phone">Enter Phone Number (with country code):</label><br><br>
            <input type="text" name="phone" placeholder="+14155552671"/><br><br>
            <input type="submit" value="Locate">
        </form>
        {% if info %}
        <div class="result">
            <b>Number:</b> {{ info['number'] }} <br>
            <b>Country/Region:</b> {{ info['region'] }} <br>
            <b>Carrier:</b> {{ info['carrier'] }} <br>
        </div>
        {% endif %}
    </div>
</body>
</html>
"""

@app.route('/', methods=['GET', 'POST'])
def locate():
    info = None
    if request.method == 'POST':
        number = request.form['phone']
        try:
            parsed = phonenumbers.parse(number, None)
            region = geocoder.description_for_number(parsed, "en")
            carrier_name = carrier.name_for_number(parsed, "en")
            info = {
                'number': number,
                'region': region if region else 'Unknown',
                'carrier': carrier_name if carrier_name else 'Unknown'
            }
        except Exception as e:
            info = {'number': number, 'region': 'Invalid number', 'carrier': 'Invalid number'}
    return render_template_string(TEMPLATE, info=info)

if __name__ == '__main__':
    app.run(debug=True)

Step 3: Run Locally

python app.py
Open http://127.0.0.1:5000/ in your browser.
Enter an international phone number (e.g., +14155552671 for US).

Features

  • Input any phone number in international format
  • Returns region/country and carrier name
  • Simple, clean HTML interface
  • Shows error for invalid phone numbers

#14 Develop and Deploy Flask

Flask: Build & Deploy Fast—From Local App to Git Hosting

Flask: Build & Deploy Fast

This guide walks you through developing a simple Flask app and deploying it to production using Git and a web dashboard such as Render or Heroku.

Step 1: Set Up Your Flask App Locally

  1. Install Flask:
    pip install flask
  2. Create app.py:
    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello():
        return "Hello, Flask World!"
    
    if __name__ == '__main__':
        app.run(debug=True)
    
  3. Test your app locally:
    python app.py
    Open http://127.0.0.1:5000/ in your browser. You should see “Hello, Flask World!”

Step 2: Prepare for Deployment

  1. Create a requirements.txt file:
    pip freeze > requirements.txt
  2. Add a Procfile (for platforms like Heroku or Render):
    web: gunicorn app:app
  3. Install Gunicorn (for production server):
    pip install gunicorn

Step 3: Push Your Code to GitHub

  1. Initialize and push to a new Git repo:
    git init
    git add .
    git commit -m "Initial Flask app"
    git remote add origin https://github.com/yourusername/your-repo.git
    git push -u origin master
    

Step 4: Deploy Using a Web Dashboard (Heroku/Render)

  1. On Render or Heroku:
    • Create a new Web Service or App
    • Connect your GitHub repository
    • Build command: pip install -r requirements.txt
    • Start command: gunicorn app:app
    • Click Deploy!
  2. Visit your live app URL:
    You’ll receive a unique URL (e.g., https://your-app.onrender.com) to access your Flask app in production.

Summary

  • Develop Flask locally, test, and verify
  • Prepare deployment files needed for cloud hosting
  • Push code to GitHub
  • Deploy from a browser-friendly dashboard—no CLI required!
  • Share your app with the world!

#21a Dunder Method - Samples

Python Dunder (Magic) Methods – Complete Guide with Demos Python Dunder (Magic) Methods – Complete Guide with Demos ...