내가 보려고 정리하는/Python
Python API- 230306
보동이용용
2023. 3. 6. 17:41
반응형
fastapi
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="http://127.0.0.1:8000/post" method="post">
<input type="text" name="a" value="666" />
<input type="submit" />
</form>
</body>
</html>
from fastapi import FastAPI, Form
import uvicorn
from starlette.responses import HTMLResponse
app = FastAPI()
@app.get("/", response_class=HTMLResponse)
async def root():
return "hello world"
@app.get("/para", response_class=HTMLResponse)
async def para(a:str):
return "para:"+a
@app.post("/post", response_class=HTMLResponse)
async def post(a:str = Form(...)):
return "hello post:"+a
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
# uvicorn my_fastapi01:app --reload
1. hello world 띄우기
2. a 파라미터로 받아오기
3. form data로 입력한 'a' 가져오기
async def ?
AJAX : Asynchronous JavaScript And XML
fastapi : forward 방식 이동
from starlette.responses import HTMLResponse
from starlette.templating import Jinja2Templates
from starlette.requests import Request
@app.get("/forw")
async def forw(request: Request):
return templates.TemplateResponse("forw.html",{"request":request})
templates 폴더 안의 forw.html 파일로 이동하기!
fastapi : setAttribute 해보기
@app.get("/forw")
async def forw(request: Request):
a = "홍길동"
arr = ["서혜정", "유관순", "아이유", "카리나"]
return templates.TemplateResponse("forw.html",{"request":request, "a":a, "arr":arr})
a는 그냥 출력 되지만, arr은 html에서 풀어줘야한다.
html에서 쓰는 python for문 써보자.
Dispatch forw <br/>
{{a}}<br/>
{{arr}}<br/>
{% for i in arr %}
{{i}}<br/>
{% endfor %}
arr만큼 for문을 돌려서 각각 요소 i번째를 뽑아낸다.
python에서는 들여쓰기로 for문을 끝내지만 여기서는 endfor문으로 for문을 끝낸다.
fastapi : db 가져와서 table에 띄우기
@app.get("/emp")
async def emp(request: Request):
mylist = []
conn = sqlite3.connect("mydb.db")
cur = conn.cursor()
cur.execute("select * from emp")
rows = cur.fetchall()
for e in rows:
print(e)
mylist.append({"e_id":e[0],"e_name":e[1],"sex":e[2],"addr":e[3]})
cur.close()
conn.close()
return templates.TemplateResponse("emp.html",{"request":request, "mylist":mylist})
EMP
<table border="1">
<tr>
<th>사번</th>
<th>이름</th>
<th>성별</th>
<th>주소</th>
</tr>
{% for e in mylist %}
<tr>
<td>{{e.e_id}}</td>
<td>{{e.e_name}}</td>
<td>{{e.sex}}</td>
<td>{{e.addr}}</td>
</tr>
{% endfor %}
</table>
반응형