Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding python3-fastapi templates #287

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions template/python3-fastapi-debian/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
FROM openfaas/of-watchdog:0.8.2 as watchdog
FROM python:3.10-slim

COPY --from=watchdog /fwatchdog /usr/bin/fwatchdog
RUN chmod +x /usr/bin/fwatchdog

ARG ADDITIONAL_PACKAGE
RUN apt update && apt install -y musl-dev gcc make ${ADDITIONAL_PACKAGE}

# Add non root user
RUN useradd -ms /bin/bash app
RUN chown app /home/app

USER app

ENV PATH=$PATH:/home/app/.local/bin

WORKDIR /home/app/

COPY requirements.txt .
USER root
RUN pip install -r requirements.txt
USER app
COPY index.py .

RUN mkdir -p function
RUN touch ./function/__init__.py
WORKDIR /home/app/function/
COPY function/requirements.txt .
RUN pip install --user -r requirements.txt

WORKDIR /home/app/

USER root
# remove build dependencies
RUN apt remove musl-dev gcc make -y
COPY function function
RUN chown -R app:app ./
USER app

ENV fprocess="uvicorn index:app --workers 1 --host 0.0.0.0 --port 8000"

ENV cgi_headers="true"
ENV mode="http"
ENV upstream_url="http://127.0.0.1:8000"

HEALTHCHECK --interval=5s CMD [ -e /tmp/.lock ] || exit 1

CMD ["fwatchdog"]
Empty file.
51 changes: 51 additions & 0 deletions template/python3-fastapi-debian/function/handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# author: Justin Guese, 11.3.22, [email protected]
from fastapi import HTTPException
from fastapi import APIRouter
from pydantic import BaseModel
from typing import Dict, List
from os import environ
import glob

# reads in secrets to environment variables, such that they can be
# easily used with environ["SECRET_NAME"]
def readSecretToEnv(secretpath):
secretname = secretpath.split('/')[-1]
with open(secretpath, "r") as f:
environ[secretname] = f.read()
for secret in glob.glob("/var/openfaas/secrets/*"):
readSecretToEnv(secret)

router = APIRouter()

# just as an example
class User(BaseModel):
id: int
name: str
age: int
colleagues: List[str]

class ResponseModel(BaseModel):
data: Dict
# user: User
# otherStuff: str

@router.post("/", response_model = ResponseModel, tags=["Main Routes"])
def handle(request: Dict):
"""handle a request to the function
Args:
req (dict): request body
"""
try:
res = ResponseModel(data=request)
except Exception as e:
raise HTTPException(status_code=500, detail=str(repr(e)))
return res

@router.get("/", response_model = ResponseModel, tags=["Main Routes"])
def get():
return ResponseModel(data={"message": "Hello from OpenFAAS!"})

# again just as an example, delete this if not required
@router.get("/users/{user_id}", response_model = User, tags=["Main Routes"])
def getUser(user_id: int):
return User(id = user_id, name="Exampleuser", age=20, colleagues=["Colleague 1", "Colleague 2"])
Empty file.
19 changes: 19 additions & 0 deletions template/python3-fastapi-debian/index.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# author: Justin Guese, 11.3.22, [email protected]
from os import environ
import glob
from fastapi import FastAPI, Request
from fastapi.openapi.docs import get_swagger_ui_html
from function.handler import router

app = FastAPI()
app.include_router(router)

# required to render /docs path
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html(req: Request):
root_path = req.scope.get("root_path", "").rstrip("/")
openapi_url = root_path + app.openapi_url
return get_swagger_ui_html(
openapi_url=openapi_url,
title="API",
)
2 changes: 2 additions & 0 deletions template/python3-fastapi-debian/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
fastapi
uvicorn
2 changes: 2 additions & 0 deletions template/python3-fastapi-debian/template.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
language: python3-fastapi-debian
fprocess: uvicorn index:app --workers 1 --host 0.0.0.0 --port 8000
49 changes: 49 additions & 0 deletions template/python3-fastapi/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
FROM openfaas/of-watchdog:0.8.2 as watchdog
FROM python:3.10-alpine

COPY --from=watchdog /fwatchdog /usr/bin/fwatchdog
RUN chmod +x /usr/bin/fwatchdog

ARG ADDITIONAL_PACKAGE
RUN apk --no-cache add musl-dev gcc make ${ADDITIONAL_PACKAGE}

# Add non root user
RUN addgroup -S app && adduser app -S -G app
RUN chown app /home/app

USER app

ENV PATH=$PATH:/home/app/.local/bin

WORKDIR /home/app/

COPY requirements.txt .
USER root
RUN pip install -r requirements.txt
USER app
COPY index.py .

RUN mkdir -p function
RUN touch ./function/__init__.py
WORKDIR /home/app/function/
COPY function/requirements.txt .
RUN pip install --user -r requirements.txt

WORKDIR /home/app/

USER root
# remove build dependencies
RUN apk del musl-dev gcc make
COPY function function
RUN chown -R app:app ./
USER app

ENV fprocess="uvicorn index:app --workers 1 --host 0.0.0.0 --port 8000"

ENV cgi_headers="true"
ENV mode="http"
ENV upstream_url="http://127.0.0.1:8000"

HEALTHCHECK --interval=5s CMD [ -e /tmp/.lock ] || exit 1

CMD ["fwatchdog"]
Empty file.
51 changes: 51 additions & 0 deletions template/python3-fastapi/function/handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# author: Justin Guese, 11.3.22, [email protected]
from fastapi import HTTPException
from fastapi import APIRouter
from pydantic import BaseModel
from typing import Dict, List
from os import environ
import glob

# reads in secrets to environment variables, such that they can be
# easily used with environ["SECRET_NAME"]
def readSecretToEnv(secretpath):
secretname = secretpath.split('/')[-1]
with open(secretpath, "r") as f:
environ[secretname] = f.read()
for secret in glob.glob("/var/openfaas/secrets/*"):
readSecretToEnv(secret)

router = APIRouter()

# just as an example
class User(BaseModel):
id: int
name: str
age: int
colleagues: List[str]

class ResponseModel(BaseModel):
data: Dict
# user: User
# otherStuff: str

@router.post("/", response_model = ResponseModel, tags=["Main Routes"])
def handle(request: Dict):
"""handle a request to the function
Args:
req (dict): request body
"""
try:
res = ResponseModel(data=request)
except Exception as e:
raise HTTPException(status_code=500, detail=str(repr(e)))
return res

@router.get("/", response_model = ResponseModel, tags=["Main Routes"])
def get():
return ResponseModel(data={"message": "Hello from OpenFAAS!"})

# again just as an example, delete this if not required
@router.get("/users/{user_id}", response_model = User, tags=["Main Routes"])
def getUser(user_id: int):
return User(id = user_id, name="Exampleuser", age=20, colleagues=["Colleague 1", "Colleague 2"])
Empty file.
19 changes: 19 additions & 0 deletions template/python3-fastapi/index.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# author: Justin Guese, 11.3.22, [email protected]
from os import environ
import glob
from fastapi import FastAPI, Request
from fastapi.openapi.docs import get_swagger_ui_html
from function.handler import router

app = FastAPI()
app.include_router(router)

# required to render /docs path
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html(req: Request):
root_path = req.scope.get("root_path", "").rstrip("/")
openapi_url = root_path + app.openapi_url
return get_swagger_ui_html(
openapi_url=openapi_url,
title="API",
)
2 changes: 2 additions & 0 deletions template/python3-fastapi/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
fastapi
uvicorn
2 changes: 2 additions & 0 deletions template/python3-fastapi/template.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
language: python3-fastapi
fprocess: uvicorn index:app --workers 1 --host 0.0.0.0 --port 8000