Python - instalación y configuración en Ubuntu
📘 Documentación Oficial ### ⭐ Frameworks Populares (ordenado de menor a mayor curva) ### 🛠️ Instalación de Python en Ubuntu ### 🍺 Instalación con Homebrew ### 📦 Gestor de Paquetes Estándar (pip — viene incluido) ### 🔧 Instalación con ASDF ### 📝▶️ Crear y ejecutar un archivo Python ## 🟦 Ejemplo básico en Python ### 🗂️🌐 Servidor Web de archivos estáticos. ### ⚙️🧩 Json API Rest Recomiendo ver antes - instalacion de Homebrew y asdf en ubuntu ( es corto son 5 comandos) Python - Docu
Python - On DevDocs.io Dependencias del sistema Instalar plugin + versión Ejemplo: .tool-versions 💻 Ejecutar Localmente: Nota: Python ya trae un servidor web básico integrado. No necesitas instalar nada. 📝 Crear archivo: touch index.py 📦 Contenido de index.py ▶️ Correr el proyecto / levantar el servidor 👉 visitar:
http://localhost:7000/?username=Homero Ejemplo de archivo: data.json 📝 Crear archivo: touch api.py ▶️ Contenido del archivo: api.py ▶️ Correr el proyecto / levantar el servidor 👉 visitar:
http://localhost:7001/characters Para probar el sanitizado de url:
http://localhost:7001/characters/1 Templates let you quickly answer FAQs or store snippets for re-use. Hide child comments as well For further actions, you may consider blocking this person and/or reporting abuse COMMAND_BLOCK:
sudo apt update
sudo apt install python3 python3-pip COMMAND_BLOCK:
sudo apt update
sudo apt install python3 python3-pip COMMAND_BLOCK:
sudo apt update
sudo apt install python3 python3-pip COMMAND_BLOCK:
brew install python COMMAND_BLOCK:
brew install python COMMAND_BLOCK:
brew install python COMMAND_BLOCK:
pip3 --version COMMAND_BLOCK:
pip3 --version COMMAND_BLOCK:
pip3 --version COMMAND_BLOCK:
pip install <paquete> COMMAND_BLOCK:
pip install <paquete> COMMAND_BLOCK:
pip install <paquete> COMMAND_BLOCK:
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 COMMAND_BLOCK:
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 COMMAND_BLOCK:
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 COMMAND_BLOCK:
asdf plugin add python
asdf list-all python # instalar distintas versiones
asdf install python 3.12.2
asdf install python 2.7.18 # Configurar una version global
asdf global python 3.12.2 # Configurar una version Local
# - Recuerda que una version localsolo afecta al directorioactual que contenga el archivo .tool-versions
asdf local python 2.7.18 COMMAND_BLOCK:
asdf plugin add python
asdf list-all python # instalar distintas versiones
asdf install python 3.12.2
asdf install python 2.7.18 # Configurar una version global
asdf global python 3.12.2 # Configurar una version Local
# - Recuerda que una version localsolo afecta al directorioactual que contenga el archivo .tool-versions
asdf local python 2.7.18 COMMAND_BLOCK:
asdf plugin add python
asdf list-all python # instalar distintas versiones
asdf install python 3.12.2
asdf install python 2.7.18 # Configurar una version global
asdf global python 3.12.2 # Configurar una version Local
# - Recuerda que una version localsolo afecta al directorioactual que contenga el archivo .tool-versions
asdf local python 2.7.18 CODE_BLOCK:
python 3.12.2 CODE_BLOCK:
python 3.12.2 CODE_BLOCK:
python 3.12.2 CODE_BLOCK:
touch hola.py CODE_BLOCK:
touch hola.py CODE_BLOCK:
touch hola.py CODE_BLOCK:
print("Hola Mundo desde Python!") CODE_BLOCK:
print("Hola Mundo desde Python!") CODE_BLOCK:
print("Hola Mundo desde Python!") CODE_BLOCK:
python3 hola.py CODE_BLOCK:
python3 hola.py CODE_BLOCK:
python3 hola.py COMMAND_BLOCK:
import re
import urllib.parse
from http.server import BaseHTTPRequestHandler, HTTPServer class Handler(BaseHTTPRequestHandler): def do_GET(self): # Obtener parámetros desde la 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) # Respuesta 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) # Levantar servidor
if __name__ == "__main__": server = HTTPServer(("localhost", 7000), Handler) print("Servidor corriendo en http://localhost:7000") print("Prueva en http://localhost:7000?username=Homero") server.serve_forever() COMMAND_BLOCK:
import re
import urllib.parse
from http.server import BaseHTTPRequestHandler, HTTPServer class Handler(BaseHTTPRequestHandler): def do_GET(self): # Obtener parámetros desde la 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) # Respuesta 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) # Levantar servidor
if __name__ == "__main__": server = HTTPServer(("localhost", 7000), Handler) print("Servidor corriendo en http://localhost:7000") print("Prueva en http://localhost:7000?username=Homero") server.serve_forever() COMMAND_BLOCK:
import re
import urllib.parse
from http.server import BaseHTTPRequestHandler, HTTPServer class Handler(BaseHTTPRequestHandler): def do_GET(self): # Obtener parámetros desde la 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) # Respuesta 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) # Levantar servidor
if __name__ == "__main__": server = HTTPServer(("localhost", 7000), Handler) print("Servidor corriendo en http://localhost:7000") print("Prueva en http://localhost:7000?username=Homero") server.serve_forever() CODE_BLOCK:
python3 index.py CODE_BLOCK:
python3 index.py CODE_BLOCK:
python3 index.py CODE_BLOCK:
[ { "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" }
] CODE_BLOCK:
[ { "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" }
] CODE_BLOCK:
[ { "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" }
] COMMAND_BLOCK:
import json
from http.server import BaseHTTPRequestHandler, HTTPServer # Cargar 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": "ID inválido"}, 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": "Personaje no encontrado"}, 404) return # Si no coincide ninguna ruta self._send_json({ "error": "Ruta no encontrada", "url_lista": "http://localhost:7001/characters", "url_personaje": "http://localhost:7001/characters/1" }, 404) if __name__ == "__main__": server = HTTPServer(("localhost", 7001), MyHandler) print("Servidor corriendo en http://localhost:7001/characters") server.serve_forever() COMMAND_BLOCK:
import json
from http.server import BaseHTTPRequestHandler, HTTPServer # Cargar 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": "ID inválido"}, 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": "Personaje no encontrado"}, 404) return # Si no coincide ninguna ruta self._send_json({ "error": "Ruta no encontrada", "url_lista": "http://localhost:7001/characters", "url_personaje": "http://localhost:7001/characters/1" }, 404) if __name__ == "__main__": server = HTTPServer(("localhost", 7001), MyHandler) print("Servidor corriendo en http://localhost:7001/characters") server.serve_forever() COMMAND_BLOCK:
import json
from http.server import BaseHTTPRequestHandler, HTTPServer # Cargar 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": "ID inválido"}, 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": "Personaje no encontrado"}, 404) return # Si no coincide ninguna ruta self._send_json({ "error": "Ruta no encontrada", "url_lista": "http://localhost:7001/characters", "url_personaje": "http://localhost:7001/characters/1" }, 404) if __name__ == "__main__": server = HTTPServer(("localhost", 7001), MyHandler) print("Servidor corriendo en http://localhost:7001/characters") server.serve_forever() CODE_BLOCK:
python3 api.js CODE_BLOCK:
python3 api.js CODE_BLOCK:
python3 api.js - Flask — Minimalista, simple.
- FastAPI — Muy rápido, moderno.
- Django — Completo y estructurado. - Definir el nombre del parámetro de consulta (query parameter)
- Obtener el valor del parámetro de consulta de la URL. strip_html_tags(text):Elimina etiquetas HTML dejando solo el contenido interior.
- strip_html_tags(text):Elimina etiquetas HTML dejando solo el contenido interior.
- Se dibuja la variable recivida en el query parameter dentro de la etiqueta - strip_html_tags(text):Elimina etiquetas HTML dejando solo el contenido interior. - Lee los datos desde un archivo data.json
- expones 1 endpoint con esos datos Una Lista de personajes en /characters y los datos de un personaje por id /characters/:id
- Una Lista de personajes en /characters
- y los datos de un personaje por id /characters/:id - Una Lista de personajes en /characters
- y los datos de un personaje por id /characters/:id