首页 > 其他分享 >FastAPI开发运维模板

FastAPI开发运维模板

时间:2023-03-28 16:00:30浏览次数:38  
标签:运维 -- FastAPI app storage re namespaces data 模板

main.py

from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
import os


app = FastAPI()


class K8sData(BaseModel):
    operation: Optional[str] = "clean_pvc"
    namespaces: Optional[str] = "test"
    storage: Optional[str] = "nfs-client"
    re: Optional[str] = "test"
    size: Optional[int] = 100

class Aliyun(BaseModel):
    operation: Optional[str] = "poweroff"


@app.get("/healthz")
def read_root():
    return {"ok"}


@app.post("/api/v1/k8s")
def read_item(data:  K8sData):
    if data.operation == "clean_pvc":
        return {"namespaces": data.namespaces, "operation": data.operation, "status": "OK", "result": clean_pvc(data.namespaces, data.storage, data.re, data.size)}


def clean_pvc(namespaces, storage, re, size):
    # shell = os.path.abspath(os.path.join(os.getcwd(), "clean_pvc.sh"))
    shell = "clean_pvc.sh"
    cmd = "bash {shell} {namespaces} {storage} {re} {size}".format(
        shell=shell, namespaces=namespaces, storage=storage, re=re, size=size)
    return os.popen(cmd).read()


@app.post("/api/v1/aliyun")
def read_item(data:  Aliyun):
    if data.operation == "poweroff":
        return {"operation": data.operation, "status": "OK", "result": ""}


def aliyun():
    pass

requirements.txt

anyio==3.6.1
asgiref==3.5.2
click==8.1.3
fastapi==0.78.0
h11==0.13.0
httptools==0.4.0
idna==3.3
pydantic==1.9.1
python-dotenv==0.20.0
PyYAML==6.0
sniffio==1.2.0
starlette==0.19.1
typing_extensions==4.2.0
uvicorn==0.17.6
uvloop==0.16.0
watchgod==0.8.2
websockets==10.3

Dockerfile

FROM python:3.10.5-slim-buster


WORKDIR /home/app

COPY requirements.txt .

RUN pip install --no-cache-dir -r requirements.txt -i https://mirrors.cloud.tencent.com/pypi/simple && \
    useradd -s /bin/bash -m app && \
    rm -f requirements.txt

USER app

COPY --chown=app:app bin/* /usr/local/bin/
COPY main.py .

ENTRYPOINT ["entrypoint.sh"]

CMD ["start"]

bin/entrypoint.sh

#!/bin/bash

set -e

if [ ! -v PORT ]; then
    PORT="8000"
fi

if [ ! -v HOST ]; then
    HOST='0.0.0.0'
fi

ARGS=()

function check_config() {
    param="$1"
    value="$2"
    ARGS+=("--${param}")
    ARGS+=("${value}")
}

check_config "host" "$HOST"
check_config "port" "$PORT"

case "$1" in
start)
    exec uvicorn main:app "${ARGS[@]}" --reload
    ;;
-*)
    exec uvicorn main:app "$@" "${ARGS[@]}" --reload
    ;;
*)
    exec "$@"
    ;;
esac

exit 1

bin/clean_pvc.sh

#!/bin/bash

set -e

export KUBECONFIG=/app/config

namespaces="$1"
storage="$2"
#storage="nfs-client"
re="$3"
#re="node"
size=$4
#sizr=100

kubectl get ns "${namespaces}" && arr=($(kubectl get deploy -n "${namespaces}" --no-headers | grep -P "${re}" | cut -d' ' -f1))

for element in ${arr[@]}; do
  replicas=$(kubectl get deployments.apps -n "${namespaces}" "${element}" --no-headers -o custom-columns=replicas:.status.replicas)
  kubectl scale deployment -n "${namespaces}" "${element}" --replicas=0
  claimName=$(kubectl get deploy -n "${namespaces}" --no-headers ${element} -o custom-columns=claimName:.spec.template.spec.volumes[*].persistentVolumeClaim.claimName)
  kubectl delete pvc -n "${namespaces}" "${claimName}"

  echo "apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: "${claimName}"
  namespace: "${namespaces}"
spec:
  storageClassName: "${storage}"
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: ${size}Gi" | kubectl create -f -

  kubectl scale deployment -n "${namespaces}" "${element}" --replicas=${replicas}
done

bin/kubectl 根据实际的k8s版本下载对应的文件即可

标签:运维,--,FastAPI,app,storage,re,namespaces,data,模板
From: https://www.cnblogs.com/xwjh/p/17265564.html

相关文章

  • 企业降本增效法宝之小程序营销模板
    近年来,小程序作为一种全新的应用形态,受到了人们的广泛关注。由于其轻量级、易传播、低成本等特点,博得了越来越多的企业和开发者的青睐。其中,小程序营销模版 作为小程序应......
  • AC自动机相关模板
    P5357#include<bits/stdc++.h>#defineintlonglong#defineN200005usingnamespacestd;intn,cnt[N]={0};strings[N],t;map<string,int>apr;string......
  • 2023.3.28 【模板】KM算法 | 二分图最大权完美匹配
    2023.3.28【模板】KM算法|二分图最大权完美匹配题目概述给定一张二分图,左右部均有\(n\)个点,共有\(m\)条带权边,且保证有完美匹配。求一种完美匹配的方案,使得最终......
  • H3C SDN运维遇到的问题
    问题解决方式无法与openstack联动实现自动化上线通过控制器打开转发预配置对所有接口下发全量overlay配置解决,通过升级版本也可以新版本虚机热迁移丢包10-20......
  • [FastAPI-33]依赖注入-路径装饰器-全局
    1.路径装饰器fromfastapiimportFastAPI,Header,HTTPException,Depends,statusapp=FastAPI()defverify_token(x_token:str=Header()):ifx_token!=......
  • [FastAPI-32]依赖注入缓存
    fromfastapiimportDepends,FastAPIapp=FastAPI()'''依赖注入缓存现象-依赖条件`get_num`被依赖了两次,但是你会发现其内部打印语句只打印了一次。也就是说,第......
  • [FastAPI-31]嵌套注入
    fromtypingimportUnionfromfastapiimportDepends,FastAPIapp=FastAPI()'''嵌套注入-路径函数get_name需要的形参`username_or_nickname`有依赖条件,所以F......
  • [FastAPI=30]依赖注入
    fromfastapiimportFastAPI,Dependsapp=FastAPI(title="依赖注入")'''依赖注入-共享一块相同逻辑的代码块-共享数据库连接-权限认证,登录状态认证'''BOO......
  • [FastAPI-29]用户注册API-File字段需要在 Form之前
    importtypingfromfastapiimportFastAPI,Form,File,UploadFilefrompydanticimportBaseModelapp=FastAPI(title="注册接口")'''1.需要输入账号密码头......
  • [FastAPI-28]上传多个文件
    importtypingfromfastapiimportFastAPI,File,UploadFileapp=FastAPI(title="Form表单")'''上传多个文件'''@app.post("/files",summary="通过内存缓存上......