Python

Python MTR

Setup Project Poetry poetry init poetry add twisted poetry add twisted-mtr Build Python Script cat << 'EOF' > main.py #!/usr/bin/env python3 ''' An example usage for twisted-mtr which initiates multiple async traceroutes to multiple IPv4 and IPv6 target IP addresses at the same time. You will need to set your source IP addresses correctly and have a working dual IPv4/IPv6 networking stack to run this example. ''' import sys import signal import logging import ipaddress from twisted.

Python Twisted

WebServer with Python Twisted cat << 'EOF' > main.py from twisted.web import server, resource from twisted.internet import reactor, endpoints class Counter(resource.Resource): isLeaf = True numberRequests = 0 def render_GET(self, request): client_ip = request.getClientAddress().host r=request.uri.decode('utf-8') if not r =="/favicon.ico": self.numberRequests += 1 request.setHeader(b"content-type", b"text/plain") content = u"I am request #{} from {}\n".format(self.numberRequests, client_ip) return content.encode("ascii") endpoints.serverFromString(reactor, "tcp:8080").listen(server.Site(Counter())) reactor.run() EOF Run poetry init poetry add twisted poetry run python main.py Browse Open your Browser: http://ip-of-your-host:8080

Python Versions

History Long time ago, there were huge discussions about Python 2.7 or Python 3.xx. Fortunately, these times are gone and we’ve all gotten over the hurdle to Python 3. But are you on 3.6, 3.7, 3.8 ? or even 3.11 or 3.12 ? That’s the current Version you should use for your daily Projects ? Status of Python versions A good indicator is this Website: https://devguide.python.org/versions/ OpenBSD It’s also recommended to check what our Operating System is installing by default, or what you can get from their Package Repository.

OpenBSD 7.4 DevBox

OpenBSD 7.4 … will be released next week (23. Oct 2023). Why not have a look at the upcomming OS and prepare a VM for Software Development ? Preparation grab a fresh VM and Install OpenBSD 7.4 os version puffy74# sysctl kern.version kern.version=OpenBSD 7.4 (GENERIC.MP) #1396: Sun Oct 8 09:20:40 MDT 2023 [email protected]:/usr/src/sys/arch/amd64/compile/GENERIC.MP empty vm puffy74# pkg_info quirks-6.159 exceptions to pkg_add rules and cache add go, rust, python puffy74# pkg_add go rust python3 quirks-6.

Poetry Packages

Let’s play with Packages and Libraries References Python Modules Poetry Scripts Switch to Root Folder cd /some/path/you/want Create a new Package poetry new mypackage add some libraries poetry add requests … add some code … cat << 'EOF' > mypackage/__init__.py print("importing", __name__) EOF cat << 'EOF' > mypackage/main.py print("importing", __name__) def test1(): print("test1") def test2(name: str): print("hello", name) def test3(name: str, age:int): print(f"Hello {name} at age {age}") if __name__ == "__main__": print("This is a Library or Package.

Python TinyDB

Storing Data in JSON - TinyDB Small Example how to Store Data in JSON, and Query them afterwards like a NOSQL DB. Have a look at TinyDB if you wanna see more. Code from tinydb import TinyDB, Query from pprint import pprint # Create or load a database file db = TinyDB('db.json') # insert some sample data def insert(): # Insert data db.insert({'name': 'John', 'age': 30}) db.insert({'name': 'Alice', 'age': 25, 'hobbies': 'sleep'}) db.

Fastapi Project Template

Project Template for FastAPI gave a try with a FastAPI Template, https://github.com/rochacbruno/fastapi-project-template.git Projectname: gugus1234 clone the repo git clone https://github.com/rochacbruno/fastapi-project-template.git gugus1234 cd gugus1234 Switch Poetry i’d like to have poetry as virtual env manager make switch-to-poetry Rename some Stuff had to rename some string in pyproject and different files … mv project_name gugug1234 gsed -i 's/a-flask-test/gugus1234/' pyproject.toml gsed -i 's/project_name/gugus1234/' pyproject.toml gsed -i 's/project_name/gugus1234/g' gugus1234/cli.py gugus1234/app.py gugus1234/config.py gugus1234/security.py Run Poetry once poetry shell poetry lock poetry install Admin User let’s create admin user

Fastapi Simple Security

How to Protect your App with Simple Security Let’s build a small API Endpoint with FastAPI and protect it with SimpleSecurity. API key based security package for FastAPI, focused on simplicity of use: Full functionality out of the box, no configuration required API key security with local sqlite backend, working with both header and query parameters Default 15 days deprecation for generated API keys Key creation, revocation, renewing, and usage logs handled through administrator endpoints No dependencies, only requiring FastAPI and the python standard library Build new App and show the Directory Structure

Python Ping3

Need a Litte Ping Function ? Test cat <<'EOF'> ping.py import argparse from ping3 import ping, verbose_ping def do_ping(host: str, timeout: int = 3, size: int = 1500, output: str = "json"): # output: json|txt # '21.54 ms' if size > 1500: size = 1500 result = ( str( round( ping(dest_addr=host, timeout=timeout, size=size, unit="ms"), 2, ) ) + " ms" ) if output.lower() == "json": return {"host": host, "timeout": timeout, "size": size, "result": result} if output.

Python Logger

a custom logger for Python let’s tune the default logger a bit so he write nice and colored messages. Screenshot config.py a little config File … cat <<'EOF'> config.py LOGGER_MAX_FILE_LENGTH = 10 EOF src/logger.py the logger code in the ‘src’ Folder mkdir src cat <<'EOF'> src/logger.py import logging import datetime import sys from config import * if isinstance(LOGGER_MAX_FILE_LENGTH, int): LOGGER_MAX_FILE_LENGTH = str(LOGGER_MAX_FILE_LENGTH) def get_now() -> str: # # choose your format # current_time = datetime.