Python

Python - Little Wordcloud

Do you like Word Clouds ?

I do …!

following a litte Script which Parse a Website and build a appropriate Word Cloud

Script

mkdir ~/mywordcloud; cd ~/mywordcloud

cat <<'EOF' > main.py
import fire
import matplotlib.pyplot as plt
import pandas as pd
import re
import requests
from bs4 import BeautifulSoup
from wordcloud import STOPWORDS, WordCloud


def gen_cloud_tag(url: str = "https://blog.stoege.net"):
    # add https
    if not url.startswith("https://"):
        url = "https://" + url

    # get Webpage
    response = requests.get(url, timeout=5, allow_redirects=True)
    soup = BeautifulSoup(response.text, "html.parser")
    words = soup.get_text()

    # split with multiple delimiters
    words = re.split(r"[\n\r]", words)

    # build Dataframe
    df = pd.DataFrame(words)

    # Stop Words
    comment_words = ""
    stopwords = set(STOPWORDS)

    # iterate
    for val in df.values:
        # typecaste each val to string
        val = str(val)

        # split the value
        tokens = val.split()

        # Converts each token into lowercase
        for i in range(len(tokens)):
            tokens[i] = tokens[i].lower()

        comment_words += " ".join(tokens) + " "

    # Build Wordcloud
    wordcloud = WordCloud(
        width=800,
        height=800,
        background_color="white",
        stopwords=stopwords,
        min_font_size=10,
    ).generate(comment_words)

    # Build Image
    plt.figure(figsize=(8, 8), facecolor=None)
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.tight_layout(pad=0)

    # show Image
    plt.show()


if __name__ == "__main__":
    fire.Fire(gen_cloud_tag)
EOF

Init Project

you need a few python libraries. use some virtual env like venv, poetry or whatever your want

Flask JWT - Sample

Flask & JWT

getting your hands dirty with Flask and JWT

Source

with some modifications by myself …

Environment

Test under macOS & OpenBSD, Poetry installed and working

Script

build virtual env

export app="app100"
export FLASK_APP="${app}/app"
poetry new ${app}
cd ${app}

set python 3.10

poetry env use $(which python3.10)
gsed -i "s/python = \"^3.*$/python = \"^3.10\"/" pyproject.toml
poetry lock

add packages

wget -4 -O requirements.txt https://raw.githubusercontent.com/GrahamMorbyDev/jwt-flask/master/requirements.txt
echo "marshmallow-sqlalchemy" >> requirements.txt
poetry add $(awk -F '==' '!/sha256/{print $1}' requirements.txt |tr '\n' ' ')
wget -4 -O ${app}/app.py https://raw.githubusercontent.com/GrahamMorbyDev/jwt-flask/master/app.py
poetry shell

create db

Django on Gooogle Cloud

I’ll give a try running an Application on Google Cloud. Not with great sucess :(

Source

Get Cloud List, Active Account

gcloud auth list
gcloud config set account '[email protected]'

List Projects

gcloud config list project
[core]
project = cloud-run-372113

Your active configuration is: [cloudshell-6045]
username@cloudshell:~ (cloud-run-372113)$

Set Project ID

gcloud config set project cloud-run-372113
username@cloudshell:~ (cloud-run-372113)$ gcloud config set project cloud-run-372113
Updated property [core/project].

Enable API

gcloud services enable \
  artifactregistry.googleapis.com \
  cloudbuild.googleapis.com \
  run.googleapis.com
username@cloudshell:~ (cloud-run-372113)$ gcloud services enable \
  artifactregistry.googleapis.com \
  cloudbuild.googleapis.com \
  run.googleapis.com
ERROR: (gcloud.services.enable) User [[email protected]] does not have permission to access projects instance [cloud-run-372113] (or it may not exist): Project 'cloud-run-372113' not found or permission denied.
Help Token: AXyIxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- '@type': type.googleapis.com/google.rpc.PreconditionFailure
  violations:
  - subject: ?error_code=210002&type=Project&resource_id=cloud-run-372113
    type: googleapis.com
- '@type': type.googleapis.com/google.rpc.ErrorInfo
  domain: serviceusage.googleapis.com
  metadata:
    resource_id: cloud-run-372113
    type: Project
  reason: RESOURCES_NOT_FOUND
username@cloudshell:~ (cloud-run-372113)$

Any Comments ?

sha256: bbf813a31c1281e47acfdca36d3b92b75b87039c93d4f295cd9a5825953e8628

Alpine - Pandas on Docker Image

How to install Pandas on Alpine Linux

Run Alpine Container

docker run -it alpine

add packages

apk update
apk add python3 py3-pip gcc python3-dev g++

add / build pandas

time pip install pandas
real 26m 13.14s
user 30m 46.40s
sys   3m 27.51s

Happy Pandas !


Any Comments ?

sha256: afb99c7e3ed003bee48b65795a153c4fe7835fe3dae0759b70ab2bfb5adc4fd5

Fastapi

FastAPI - Dependencies and Custom Headers

Source

Code

from fastapi import Depends, FastAPI, Header, HTTPException

app = FastAPI()


async def verify_token(x_token: str = Header()):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=400, detail="X-Token header invalid")


async def verify_key(x_key: str = Header()):
    if x_key != "fake-super-secret-key":
        raise HTTPException(status_code=400, detail="X-Key header invalid")
    return x_key


@app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)])
async def read_items():
    return [{"item": "Foo"}, {"item": "Bar"}]

Test’s

Failed

no Custom Header

curl -s http://localhost/api/items/ |jq
{
  "detail": [
    {
      "loc": [
        "header",
        "x-token"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    },
    {
      "loc": [
        "header",
        "x-key"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}

adding “x-token”

Url Shortener for CLI

CLI Url Shortener

wrote a little URL Shortener in Python with FastAPI and a wrapper script for cli usage. needs httpie & jq packages. python backend is under development, cli wrapper for different os right here …

Usage

somehost$ ./myurlshort

usage: /usr/local/bin/myurlshort http://veeeeeeeeeeeeeeeeeeeeeeeeeery.long.url.to

anyhost$ ./myurlshort http://my-url-to-short.egal.world.planet.universe
https://url.stoege.net/xXxXx

CLI Wrappers

OpenBSD

cat << 'EOF' > myurlshort
#!/usr/bin/env bash

# url shortener for openbsd, v1.0, 2022-09-12, by @stoege

which jq >/dev/null || ( echo -e "*** jq not installed ***\ndoas pkg_add jq\n"; )
which https >/dev/null || ( echo -e "*** httpie not installed ***\ndoas pkg_add httpie\n"; )

if [[ $# -ne 1 ]]; then
  echo -e "\nusage: $0 http://veeeeeeeeeeeeeeeeeeeeeeeeeery.long.url.to\n"
  exit 1
fi

url="$1"

# check if http/https set
if ! ( [[ $1 == http* ]] || [[ $1 == https* ]] ); then
  url="https://$1"
  echo "adding https:// ... -> $url"
fi

https post url.stoege.net/url target_url="$url" |jq -r '.url'

exit 0
EOF

chmod 755 myurlshort

macOS

cat << 'EOF' > myurlshort
#!/usr/bin/env bash

# url shortener for macos, v1.0, 2022-09-12, by @stoege

which jq >/dev/null || ( echo -e "*** jq not installed ***\nbrew install jq\n"; )
which https >/dev/null || ( echo -e "*** httpie not installed ***\nbrew install httpie\n"; )

if [[ $# -ne 1 ]]; then
  echo -e "\nusage: $0 http://veeeeeeeeeeeeeeeeeeeeeeeeeery.long.url.to\n"
  exit 1
fi

url="$1"

# check if http/https set
if ! ( [[ $1 == http* ]] || [[ $1 == https* ]] ); then
  url="https://$1"
  echo "adding https:// ... -> $url"
fi

https post url.stoege.net/url target_url="$url" |jq -r '.url'

exit 0
EOF

chmod 755 myurlshort

Alpine

cat << 'EOF' > myurlshort
#!/usr/bin/env bash

# url shortener for alpine, v1.0, 2022-09-12, by @stoege

which jq >/dev/null || ( echo -e "*** jq not installed ***\napk add jq\n"; )
which https >/dev/null || ( echo -e "*** httpie not installed ***\napk add httpie\n"; )

if [[ $# -ne 1 ]]; then
  echo -e "\nusage: $0 http://veeeeeeeeeeeeeeeeeeeeeeeeeery.long.url.to\n"
  exit 1
fi

url="$1"

# check if http/https set
if ! ( [[ $1 == http* ]] || [[ $1 == https* ]] ); then
  url="https://$1"
  echo "adding https:// ... -> $url"
fi

https post url.stoege.net/url target_url="$url" |jq -r '.url'

exit 0
EOF

chmod 755 myurlshort

Any Comments ?

sha256: 75b0a781fd4569791f3d43932694e155a9443a739f0bf43b0e0904ce299eec3e

JC - JSON from CLI

how to build json from cli

we all like json, do we ? https://kellyjonbrazil.github.io/jc/docs/parsers/ping

add package

doas pkg_add jc

try ping

openbsd-box # ping -c 3 1.1.1.1 |jc --ping -p 2>/dev/null
{
  "destination_ip": "1.1.1.1",
  "data_bytes": 56,
  "pattern": null,
  "destination": "1.1.1.1",
  "packets_transmitted": 3,
  "packets_received": 3,
  "packet_loss_percent": 0.0,
  "duplicates": 0,
  "round_trip_ms_min": 9.219,
  "round_trip_ms_avg": 9.826,
  "round_trip_ms_max": 10.158,
  "round_trip_ms_stddev": 0.43,
  "responses": [
    {
      "type": "reply",
      "bytes": 64,
      "response_ip": "1.1.1.1",
      "icmp_seq": 0,
      "ttl": 59,
      "time_ms": 10.158,
      "duplicate": false
    },
    {
      "type": "reply",
      "bytes": 64,
      "response_ip": "1.1.1.1",
      "icmp_seq": 1,
      "ttl": 59,
      "time_ms": 9.219,
      "duplicate": false
    },
    {
      "type": "reply",
      "bytes": 64,
      "response_ip": "1.1.1.1",
      "icmp_seq": 2,
      "ttl": 59,
      "time_ms": 10.101,
      "duplicate": false
    }
  ]
}

Compatible platforms: linux, darwin, freebsd -> had to redirect the stderr to /dev/null because OpenBSD is not (yet) supported officially…

Python PIP3

Python PIP

OpenBSD 7.1

# python3 --version
Python 3.9.12

# python3 -m pip --version
pip 22.0.4 from /usr/local/lib/python3.9/site-packages/pip (python 3.9)

List installed Packages

python3 -m pip list

List outdated Packages

python3 -m pip list --outdated --format columns

Any Comments ?

sha256: 6ada0942bc4d02ee477ab233571e893547049a379479b61910541e561d2f053a

Little Mail Validator in Python

wrote a little Mail Adresse Validator in Python. use it, modify it, like it … best practice for python is to use a virtual env like Poetry (or virtualenv) and add the “email-validator” module like this:

poetry add email-validator

Code

few lines of code …

#!/usr/bin/env python3

from email_validator import validate_email, EmailNotValidError

ok=[]
nok=[]

emails = [
        "[email protected]", "[email protected]", "[email protected]",
        "[email protected]", "asf.asdf", "[email protected]", "[email protected]"
        ]

print ("\nMy Little Mail Validator\n")

for email in emails:

    try:
        # Validate.
        valid = validate_email(email)

        # Update with the n
        email = valid.email

        # Append to List
        ok.append(email)

    except EmailNotValidError as e:

        # email is not valid, exception message is human-readable
        nok.append(str(e))


print ("*** Mail ok ***")
for item in ok:
    print("ok: ", item)

print ("\n*** Mail NOT ok ***")
for item in nok:
    print("NOK:", item,"!")

print()

Run

just run and enjoy …

Python

Python Snippets

RealPython Best Practices: https://realpython.com/tutorials/best-practices/

Flush Stdout

import sys
from time import sleep

for i in range(1, 101):
    print(".", end="")
    sys.stdout.flush()
    sleep(0.01)

Remove a substring from the end of a string

url = "abcdc.com"
url.removesuffix(".com")  # Returns 'abcdc'
url.removeprefix("abcdc.")  # Returns 'com'

or

url = "abcdc.com"
if url.endswith(".com"):
    url = url[:-4]

or regex

import re

url = "abcdc.com"
url = re.sub("\.com$", "", url)

Modul ‘ping3’

echo "# allow all users to create icmp sockets" > /etc/sysctl.d/ping_group.conf
echo "net.ipv4.ping_group_range=0 2147483647"   > /etc/sysctl.d/ping_group.conf
sysctl net.ipv4.ping_group_range='0   2147483647'

Convert CSV to JSON

cat LARGEFILE.csv |python3 -c 'import csv, json, sys; print(json.dumps([dict(r) for r in csv.DictReader(sys.stdin)]))' > LARGEFILE.json

Show System Path

python3.10 -c "import sys; print('\n'.join(sys.path))"

Zfill

Padding Zero