On this page
Python Libraries and Frameworks
Overview of Popular Libraries
- NumPy: A powerful library for numerical computations. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on them.
Example:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.mean()) # Calculate the mean of the array
- Pandas: A library for data manipulation and analysis. It provides data structures like Series and DataFrame, making it easier to handle structured data.
Example:
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
print(df)
- Matplotlib: A plotting library used to create static, interactive, and animated visualizations in Python.
Example:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Plot')
plt.show()
Introduction to Web Frameworks
- Flask: A lightweight web framework that is easy to get started with. Flask is known for its simplicity and flexibility, making it a good choice for small to medium-sized web applications.
Example:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
- Django: A high-level web framework that encourages rapid development and clean, pragmatic design. Django includes many built-in features, such as an admin panel, authentication, and ORM (Object-Relational Mapping).
Example:
# Django example (project setup)
django-admin startproject mysite
cd mysite
python manage.py startapp myapp
python manage.py runserver
Working with APIs
APIs (Application Programming Interfaces): Allow applications to interact with each other. In Python, you can use libraries like requests to send HTTP requests to interact with web APIs.
Example:
import requests
response = requests.get('https://api.example.com/data')
if response.status_code == 200:
data = response.json()
print(data)
else:
print("Failed to retrieve data")
Common API Operations:
- GET: Retrieve data from an API.
- POST: Send data to an API to create or update resources.
- PUT: Update existing resources on the server.
- DELETE: Remove resources from the server.
requests — HTTP Client
import requests
response = requests.post(
'https://api.example.com/users',
json={'name': 'Alice', 'email': '[email protected]'},
headers={'Authorization': f'Bearer {token}'},
timeout=10
)
response.raise_for_status()
user = response.json()
Always set timeout to prevent hanging indefinitely.
FastAPI vs Flask vs Django
| Framework | Best for |
|---|---|
| Flask | Microservices, APIs, learning |
| Django | Full-stack apps with admin, ORM, auth |
| FastAPI | High-performance async APIs with auto docs |
Virtual Environments per Project
python -m venv .venv
source .venv/bin/activate
pip install flask pandas requests
Isolate dependencies so Project A’s Django 4 does not conflict with Project B’s Django 5.
Popular Utility Libraries
| Library | Purpose |
|---|---|
httpx |
Async HTTP client |
pydantic |
Data validation |
click |
CLI applications |
pytest |
Testing framework |
black |
Code formatting |
API Error Handling
try:
response = requests.get(url, timeout=5)
response.raise_for_status()
except requests.HTTPError as e:
print(f"HTTP error: {e.response.status_code}")
except requests.ConnectionError:
print("Network unreachable")