2022年9月9日 星期五

FAST API

# uvicorn main:app --reload --host 0.0.0.0


import os

from typing import List

import logging


from fastapi import FastAPI, HTTPException

from fastapi.middleware.cors import CORSMiddleware

from pydantic import BaseModel


import httpx

import uvicorn

import webbrowser


if not os.path.exists("./logs/"):

    os.makedirs("./logs/")


logging.basicConfig(

    level=logging.INFO,

    format="%(asctime)s [%(levelname)s] %(message)s",

    handlers=[

        logging.FileHandler("./logs/debug.log"),

        logging.StreamHandler()

    ]

)


app = FastAPI(title="fastapi title")

app.add_middleware(

    CORSMiddleware,

    allow_origins="*",

    allow_credentials=True,

    allow_methods=["*"],

    allow_headers=["*"],

)


@app.get("/")

def root():

    return {"name": "fastapi root"}


async def demo(url: str):

    try:

        async with httpx.AsyncClient() as client:

            r = await client.post(url)

            print(r.status_code)

            print(r.text)

            return r.text

    except Exception as e:

        print(e)

        raise HTTPException(status_code=404, detail=f"failed to connect url {url}")


class Item(BaseModel):

    id: int

    value: float


class Items(BaseModel):

    items: List[Item]


@app.put("/put_items")

def put_items(items: Items):

    logging.info(f"items")

    logging.info(f"{items}")

    return {"message": f"received items count {len(items.items)}"}


if __name__ == "__main__":

    webbrowser.open('http://127.0.0.1:22909/docs', new=2)

    uvicorn.run("a:app", host="127.0.0.1", port=22909, log_level="info", reload=True, debug=True)


2022年9月5日 星期一

Build Python wheel file 2022 using setuptools

 https://www.youtube.com/watch?v=AM2dgUAdwaQ


once
====
sudo apt install python3.8-venv

library
=======
mkdir callib
touch callib/__init__.py
touch callib/tools.py
echo 'def add_them(x, y):' >> callib/tools.py
echo ' print(f"adding {x} and {y}")' >> callib/tools.py
echo ' return x+y' >> callib/tools.py
touch setup.py
echo 'import setuptools' >> setup.py
echo 'setuptools.setup(name="callib", version="1.0", packages=["callib"])' >> setup.py

build and test
==============
python3 -m venv venv
source venv/bin/activate
pip install wheel setuptools
python setup.py bdist_wheel --universal
cd dist
ls callib-1.0-py2.py3-none-any.whl
python3 -m venv venv
source venv/bin/activate
pip install callib-1.0-py2.py3-none-any.whl
touch test.py
echo 'from callib import tools' >> test.py
echo 'print(tools.add_them(2,3))' >> test.py
python3 test.py
echo "now we should see adding 2 and 3"


multiple modules
================
mkdir f20001
touch f20001/__init__.py
touch f20001/__main__.py
nano f20001/__main__.py
```
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
    return "<p>Hello, 20001!</p>"
if __name__=="__main__":
    app.run(host='0.0.0.0', port=20001)
```

mkdir f20002
touch f20002/__init__.py
touch f20002/__main__.py
nano f20002/__main__.py
```
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
    return "<p>Hello, 20002!</p>"
if __name__=="__main__":
    app.run(host='0.0.0.0', port=20002)
```

mkdir src/
mkdir src/f20003
touch src/f20003/__init__.py
touch src/f20003/__main__.py
nano src/f20003/__main__.py
```
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
    return "<p>Hello, 20003!</p>"
if __name__=="__main__":
    app.run(host='0.0.0.0', port=20003)
```

setup.py for multiple modules
======================
touch setup.py
cat /dev/null > setup.py
nano setup.py
```
import setuptools
setuptools.setup(name="callib", version="1.0", package_dir={"f20003":"src/f20003"}, packages=["callib", "f20001", "f20002", "f20003"], install_requires=["flask"])
```

build and test for multiple modules
====================
source venv/bin/activate
rm -rf dist
python setup.py bdist_wheel --universal
cd dist
python3 -m venv venv
source venv/bin/activate
echo "pip install callib-1.0-py2.py3-none-any.whl"
pip install *.whl
python3 -m f20001
firefox http://127.0.0.1:20001
python3 -m f20002
firefox http://127.0.0.1:20002
python3 -m f20003
firefox http://127.0.0.1:20003

 




End
End
End

2022年9月2日 星期五

Ansible 2022

 https://www.tutorialspoint.com/ansible/ansible_environment_setup.htm



sudo apt-get update
sudo apt-get install software-properties-common
sudo apt-add-repository ppa:ansible/ansible
sudo apt-get update
sudo apt-get install ansible
ansible --version
echo ansible 2.10.15


https://tdhopper.com/blog/automating-python-with-ansible

ansible -i 'localhost,' -c local -m ping all

localhost | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}

ansible all -i 'localhost, ' -c local -a "/bin/echo hello"
localhost | CHANGED | rc=0 >>
hello


TBC

2022年8月30日 星期二

How can I merge multiple commits onto another branch as a single squashed commit 2022

 https://stackoverflow.com/questions/5308816/how-can-i-merge-multiple-commits-onto-another-branch-as-a-single-squashed-commit


                                         15 Answers

29

Suppose you worked in feature/task1 with multiple commits.

  1. Go to your project branch (project/my_project)

     git checkout project/my_project
    
  2. Create a new branch (feature/task1_bugfix)

     git checkout -b feature/task1_bugfix
    
  3. Merge with the --squash option

     git merge --squash feature/task1
    
  4. Create a single commit

     git commit -am "add single comments"
    
  5. Push your branch

     git push --set-upstream origin feature/task1_bugfix
    

2022年8月13日 星期六

2022年8月10日 星期三

Using httpx in FastAPI to call Flask API

calculate.py

from flask import Flask, redirect, url_for, request
import datetime

app = Flask(__name__)

@app.route('/calculate',methods = ['POST', 'GET'])
def calculate():
   now = datetime.datetime.now()
   if request.method == 'POST':
      res = f"POST {now}"
   else:
      res = f"GET {now}"
   print(res)
   return res

if __name__ == '__main__':
   app.run(debug = True, host='0.0.0.0', port=5000)


client.py

import httpx

with httpx.Client() as client:
    r = client.post("http://127.0.0.1:5000/calculate")
    print(r.status_code)
    print(r.text)


api.py

# uvicorn main:app --reload
# pip install fastapi[all]
# pip install uvicorn

from fastapi import FastAPI
from enum import Enum
from typing import Union
import httpx

import webbrowser
webbrowser.open("http://127.0.0.1:8000")
webbrowser.open("http://127.0.0.1:8000/redoc")
webbrowser.open("http://127.0.0.1:8000/openapi.json")
webbrowser.open("http://127.0.0.1:8000/docs")

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}
    
@app.get("/pretend")
async def pretend():
    async with httpx.AsyncClient() as client:
        r = await client.post("http://127.0.0.1:5000/calculate")
        print(r.status_code)
        print(r.text)
        return r.text
   

2022年8月6日 星期六

Introduction to git and GitHub 2022

 Week 1


Reference

https://git-scm.com/docs/gittutorial

commit
mkdir project
git init
git add .
git commit
touch file1 file2 file3
git add file1 file2 file3
git diff --cached
git status
git commit
git commit -a
git log
git log -p
git log --stat --summary

branch
git branch experimental
git branch
git switch experimental
echo first >> file1
git commit -a
git switch master
echo second >> file1
git commit -a
git merge experimental
git diff
git commit -a
git branch -d experimental
git branch -D crazy-idea
TBC

Collaboration

git clone /home/alice/project myrepo\
cd myrepo
echo bob >> file.txt
git commit -a
alice$ cd /home/alice/project
alice$ git pull /home/bob/myrepo master // pull = fetch + merge to current branch
alice$ git fetch /home/bob/myrepo master
alice$ git log -p HEAD..FETCH_HEAD // range notation
alice$ gitk HEAD..FETCH_HEAD
alice$ git remote add bob /home/bob/myrepo
alice$ git fetch bob
alice$ git log -p master..bob/master  // better range notation
alice$ git merge bob/master
alice$ git pull . remotes/bob/master // what? pulling from her own remote-tracking branch?
bob$ git pull  // pull = fetch + merge to current branch
bob$ git config --get remote.origin.url
/home/alice/project
bob$ git config -l  // show git clone config
bob$ git branch -r origin/master
bob$ git clone alice.org:/home/alice/project myrepo

History

git log
git show c82a22c39cbc32576f64f5c6b3f24b99ea8149c7
git show c82a22c39c
git show c82a22c39
git show c82a22c3
git show c82a22c
git show c82a22
git show HEAD # tip of current branch
git show experiment # tip of experiment branch
git show HEAD^ # parent of HEAD
git show HEAD^^ # grandparent of HEAD
git show HEAD~4 # great-great grandparent of HEAD
git show HEAD^1 # same as HEAD^
git show HEAD^2 # second parent of HEAD
git tag v2.5 1b2e1d63ff
git diff v2.5 HEAD
git branch stable v2.5  # create a new branch named stable based on v2.5
git reset --hard HEAD^  # reset to state at HEAD^ i.e. parent of HEAD
git grep "hello" v2.5
git log v2.5..v2.6 # commit between v2.5 and v2.6
git log v2.5.. # commit since v2.5
git log --since="2 week ago"  # commit from the last 2 weeks
git log v2.5.. Makefile # commit since v2.5 which modify Makefile
gitk --since="2 weeks ago" drivers/ # commits that modify directory
 

Diff

diff apple banana

diff -u apple banana

diff -u apple banana > diff.diff

meld, kdiff3, vimdiff

patch banana < diff.diff




2007 to 2023 HP and Dell Servers Comparison

  HP Gen5 to Gen11  using ChatGPT HP ProLiant Gen Active Years CPU Socket Popular HP CPUs Cores Base Clock Max RAM Capacity Comparable Dell ...