FastAPI + Streamlit 계산기앱
1
2
3
4
5
# requirements.txt
fastapi==0.115.8
uvicorn==0.34.0
streamlit==1.41.1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# calculator.py
def calculate(operation, x, y):
'''
:param operation: takes the string [add, sub, mul, div]
:param x & y: takes the integer values
:return: result of the operation
'''
if operation == 'add':
return x + y
elif operation == 'sub':
if x > y:
return x - y
else:
return y - x
elif operation == 'mul':
return x * y
elif operation == 'div':
if y != 0:
return x / y
else:
return 'Division by zero is not possible'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# fast_api.py
from fastapi import FastAPI
from pydantic import BaseModel
from calculator import calculate
class UserInput(BaseModel):
operation: str
x: float
y: float
app = FastAPI()
@app.post("/calculate/")
async def calculate_result(user_input: UserInput):
'''
:param user_input: takes the operation, x and y values
:return: result of the operation
'''
return calculate(user_input.operation, user_input.x, user_input.y)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# stream_lit.py
import streamlit as st
import json
import requests
st.title("FastAPI Streamlit Calculator")
# taking user inputs
option = st.selectbox("What operation You want to perform?", ["add", "sub", "mul", "div"])
st.write("")
st.write("Select the numbers from slider below 👇")
x = st.slider("X", 0, 100, 20)
y = st.slider("Y", 0, 130, 10)
# converting the inputs into a json format
inputs = {"operation": option, "x": x, "y": y}
# when the user clicks on botton it will fetch the API
if st.button("Calculate"):
res = requests.post(url="http://127.0.0.1:8000/calculate/", data=json.dumps(inputs))
st.subheader(f"Response from API 🚀= {res.text}")
1
2
uvicorn fast_api:app --reload
streamlit run stream_lit.py
Streamlit🔥+ FastAPI⚡️- The ingredients you need for your next Data Science Recipe Streamlit is an open-source, free, all-python framework to rapidly build and share interactive dashboards and web apps for Data Science /… Streamlit is an open-source, free, all-python framework to rapidly build and share interactive dashboards and web apps for Data Science /…
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.