-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
78 lines (62 loc) · 2.07 KB
/
main.py
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel
app = FastAPI()
# Глобальный массив для маршрута /list
global_list = []
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/sum1n/{n}")
def sum1n(n: int):
result = sum(range(1, n + 1))
return {"result": result}
@app.get("/fibo")
def fibo(n: int):
def fibonacci(num):
a, b = 0, 1
for _ in range(num):
a, b = b, a + b
return a
result = fibonacci(n)
return {"result": result}
@app.post("/reverse")
def reverse(string: str = Header(...)):
result = string[::-1]
return {"result": result}
# Модель для добавления элемента в глобальный массив
class Element(BaseModel):
element: str
# Маршрут для добавления элемента в массив
@app.put("/list")
def add_to_list(item: Element):
global global_list
global_list.append(item.element)
return {"result": global_list}
# Маршрут для получения глобального массива
@app.get("/list")
def get_list():
return {"result": global_list}
# Модель для математического выражения
class Expression(BaseModel):
expr: str
# Маршрут для калькулятора
@app.post("/calculator")
def calculator(expression: Expression):
try:
num1, operator, num2 = expression.expr.split(',')
num1, num2 = float(num1), float(num2)
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
if num2 == 0:
raise HTTPException(status_code=403, detail="zerodiv")
result = num1 / num2
else:
raise HTTPException(status_code=400, detail="invalid")
return {"result": result}
except ValueError:
raise HTTPException(status_code=400, detail="invalid")