Python on Ubuntu: Installation, Setup, and First Steps

Python on Ubuntu: Installation, Setup, and First Steps

๐Ÿ“˜ Official Documentation ### โญ Popular Frameworks (ordered from lower to higher learning curve) ### ๐Ÿ› ๏ธ Installing Python on Ubuntu ### ๐Ÿบ Installation with Homebrew ### ๐Ÿ“ฆ Standard Package Manager (pip โ€” included) ### ๐Ÿ”ง Installation with ASDF ### ๐Ÿ“โ–ถ๏ธ Create and run a Python file ## ๐ŸŸฆ Basic example in Python ### ๐Ÿ—‚๏ธ๐ŸŒ Static file web server. ### โš™๏ธ๐Ÿงฉ JSON REST API I recommend viewing first โ€“ installation of Homebrew and asdf on Ubuntu (it's short, just 5 commands) Python - Docs

Python - On DevDocs.io Install plugin + version Example: .tool-versions Note: Python already includes a basic built-in web server. You donโ€™t need to install anything. ๐Ÿ“ Create file: touch index.py ๐Ÿ“ฆ Content of index.py โ–ถ๏ธ Run the project / start the server ๐Ÿ‘‰ visit:
http://localhost:7000/?username=Homero Example file: data.json ๐Ÿ“ Create file: touch api.py โ–ถ๏ธ Content of the file: api.py โ–ถ๏ธ Run the project / start the server ๐Ÿ‘‰ visit:
http://localhost:7001/characters To test URL sanitization:
http://localhost:7001/characters/1 Si quieres puedo traducir otro artรญculo tambiรฉn. 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 <package> COMMAND_BLOCK:
pip install <package> COMMAND_BLOCK:
pip install <package> 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 # 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 COMMAND_BLOCK:
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 COMMAND_BLOCK:
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 CODE_BLOCK:
python 3.12.2 CODE_BLOCK:
python 3.12.2 CODE_BLOCK:
python 3.12.2 CODE_BLOCK:
touch hello.py CODE_BLOCK:
touch hello.py CODE_BLOCK:
touch hello.py CODE_BLOCK:
print("Hello World from Python!") CODE_BLOCK:
print("Hello World from Python!") CODE_BLOCK:
print("Hello World from Python!") CODE_BLOCK:
python3 hello.py CODE_BLOCK:
python3 hello.py CODE_BLOCK:
python3 hello.py COMMAND_BLOCK:
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() COMMAND_BLOCK:
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() COMMAND_BLOCK:
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() 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 # 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() COMMAND_BLOCK:
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() COMMAND_BLOCK:
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() CODE_BLOCK:
python3 api.js CODE_BLOCK:
python3 api.js CODE_BLOCK:
python3 api.js - Flask โ€” Minimalist, simple.
- FastAPI โ€” Very fast, modern.
- Django โ€” Complete and structured. - 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.
- strip_html_tags(text): Removes HTML tags leaving only inner content.
- Renders the variable received in the query parameter inside the <H1> tag - strip_html_tags(text): Removes HTML tags leaving only inner content. - Reads data from a data.json file
- 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 /characters
- And the data of a character by id /characters/:id - A list of characters at /characters
- And the data of a character by id /characters/:id