📘 Official Documentation
Python - Docs
Python - On DevDocs.io
⭐ Popular Frameworks (ordered from lower to higher learning curve)
🛠️ Installing Python on Ubuntu
sudo apt update
sudo apt install python3 python3-pip
🍺 Installation with Homebrew
brew install python
📦 Standard Package Manager (pip — included)
Check version:
pip3 --version
Install a package:
pip install <package>
🔧 Installation with ASDF
System dependencies
sudo apt update
sudo apt install -y build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev
Install plugin + version
asdf plugin add python
asdf list-all python
# install different versions
asdf install python 3.12.2
asdf install python 2.7.18
# Set a global version
asdf global python 3.12.2
# Set a local version
# - Remember that a local version only affects the current directory that contains the .tool-versions file
asdf local python 2.7.18
Example: .tool-versions
python 3.12.2
📝▶️ Create and run a Python file
Create file:
touch hello.py
Content of hello.py
print("Hello World from Python!")
💻 Run locally:
python3 hello.py
🟦 Basic example in Python
🗂️🌐 Static file web server.
Note: Python already includes a basic built-in web server. You don’t need to install anything.
What it does:
- Defines the name of the query parameter
- Obtains the value of the query parameter from the URL
- strip_html_tags(text): Removes HTML tags leaving only inner content.
- Renders the variable received in the query parameter inside the
<H1>tag
📝 Create file: touch index.py
📦 Content of index.py
import re
import urllib.parse
from http.server import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
# Get parameters from the URL
parsed = urllib.parse.urlparse(self.path)
query = urllib.parse.parse_qs(parsed.query)
username = query.get("username", ["invitado"])[0]
username = strip_html_tags(username)
# Response
content = f"""
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Hola</title>
</head>
<body style="text-align:center">
<h1>Hola, {username}</h1>
</body>
</html>
"""
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(content.encode("utf-8"))
def strip_html_tags(text):
return re.sub(r"<[^>]+>", "", text)
# Start server
if __name__ == "__main__":
server = HTTPServer(("localhost", 7000), Handler)
print("Server running at http://localhost:7000")
print("Test at http://localhost:7000?username=Homero")
server.serve_forever()
▶️ Run the project / start the server
python3 index.py
👉 visit:
http://localhost:7000/?username=Homero
⚙️🧩 JSON REST API
What it does:
- Reads data from a
data.jsonfile - Exposes one endpoint with that data
- A list of characters at
/characters - And the data of a character by id
/characters/:id
- A list of characters at
Example file: data.json
[
{
"id": 1,
"age": 39,
"name": "Homer Tompson",
"portrait_path": "https://cdn.thesimpsonsapi.com/500/character/1.webp"
},
{
"id": 2,
"age": 39,
"name": "Marge Simpson",
"portrait_path": "https://cdn.thesimpsonsapi.com/500/character/2.webp"
}
]
📝 Create file: touch api.py
▶️ Content of the file: api.py
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
# Load data.json
def load_characters():
with open("data.json", "r", encoding="utf-8") as f:
return json.load(f)
class MyHandler(BaseHTTPRequestHandler):
def _send_json(self, data, status=200):
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(data, ensure_ascii=False).encode("utf-8"))
def do_GET(self):
characters = load_characters()
# GET /characters
if self.path == "/characters":
self._send_json(characters)
return
# GET /characters/:id
if self.path.startswith("/characters/"):
try:
id_str = self.path.split("/")[2]
char_id = int(id_str)
except:
self._send_json({"error": "Invalid ID"}, 400)
return
found = next((c for c in characters if c["id"] == char_id), None)
if found:
self._send_json(found)
return
else:
self._send_json({"error": "Character not found"}, 404)
return
# If no route matches
self._send_json({
"error": "Route not found",
"url_list": "http://localhost:7001/characters",
"url_character": "http://localhost:7001/characters/1"
}, 404)
if __name__ == "__main__":
server = HTTPServer(("localhost", 7001), MyHandler)
print("Server running at http://localhost:7001/characters")
server.serve_forever()
▶️ Run the project / start the server
python3 api.js
👉 visit:
http://localhost:7001/characters
To test URL sanitization:
http://localhost:7001/characters/1
Si quieres puedo traducir otro artículo también.

Top comments (0)