크리스피코드
'파이썬' 태그의 글 목록

파이썬

Python

파이썬 API 정적 문서(StaticFiles)와 동적 문서(Jinja2)

from starlette.templating import Jinja2Templates from starlette.staticfiles import StaticFiles from fastapi import FastAPI, Request import uvicorn app = FastAPI() # 정적 문서 경로 app.mount("/static", StaticFiles(directory="static"), name="static") # 동적 문서 경로 (Jinja2 사용) templates = Jinja2Templates(directory="templates") @app.get("/") @app.get("/hello") async def emp(request: Request): return template..

Python

FastAPI에서 응답을 HTML 형식으로 하기

파이썬, 내 경우에는 FastAPI에서 HTML로 응답을 전송하고자 한다. 이 경우 어노테이션의 컨텍스트 경로 뒤에 response_class=HTMLResponse를 추가해주어야한다. 그 다음에는 return에 문자열로 HTML 문서 형식에 맞게 작성하면 된다.

Python

파이썬 딕셔너리

파이썬의 딕셔너리(Dictionary)는 자바의 Map이나 자바스크립트의 객체, JSON과 매우 비슷한 형태를 하고 있는 자료형이다. {key1 : value1, key2 : value2, key3 : value3} 여기서 key는 식별자의 역할을 하며 key를 통해 value를 가져올 수 있다. student = {'id' : 'a001', 'name' : 'one', 'score' : '95'} 값을 꺼낼 때는 get 함수, 또는 대괄호를 사용하면 된다. 차이점은 존재하지 않는 key를 가져오려고 할 때인데 get() 함수의 경우 None을 리턴하고 대괄호[ ]를 이용한 방식의 경우 오류를 일으킨다. student.get('name') # one student['name'] # one 대괄호를 사용해..

Python

FastAPI 리다이렉트 / 포워딩

리다이렉트는 RedirectResponse를 사용한다. RedirectResponse("경로") 를 반환하여 경로의 페이지로 클라이언트가 리다이렉트할 수 있도록 한다. 포워딩하기 위해서는 Jinja2가 필요하다. Anaconda의 경우 Jinja2가 미리 설치되어있다. from starlette.templating import Jinja2Templates from starlette.responses import RedirectResponse from starlette.staticfiles import StaticFiles from fastapi import FastAPI import uvicorn app = FastAPI() # html 문서가 담겨있는 디렉토리를 지정 templates = Jinja2T..

Python

html에서 파이썬 변수 사용하기

1. 표현식 표현식은 중괄호를 중첩하여 표현할 수 있다. 결과 {{result}} 2. 문(Statement) 조건문, 반복문 등의 로직을 작성하는 부분은 중괄호와 퍼센트 기호로 표현할 수 있다. 구구단 2단 {% for i in range(1, 10) %} 2 * {{i}} = {{2 * i}} {% endfor %} {% if param > 10 %} 10보다 큼 {% elif param > 20 %} 20보다 큼 {% else %} {{ param }} {% endif %} 3. 주석 주석은 중괄호와 샵 기호로 표현할 수 있다. {# 이곳은 주석입니다. #}

Python

FastAPI get방식, post방식

1. get방식 get방식은 파라미터를 추가하는 것으로 데이터를 받을 수 있다. 파라미터에 작성되는 변수명은 쿼리스트링의 'name'과 동일하게 작성하면 된다. from fastapi import FastAPI, Form import uvicorn app = FastAPI() @app.get("/") async def root(): return 'welcome!' @app.get("/get") async def get(a): return {"param" : a} if __name__ == "__main__": uvicorn.run(app, host="localhost", port="80") 2. post 방식 post 방식 또한 파라미터를 추가하면 된다. 하지만 get과 다르게 변수를 From() 객체로..

Python

파이썬 FastAPI 첫 시작

1. FastAPI 설치 FastAPI는 파이썬으로 빠르게 웹 개발을 할 수 있는 웹 프레임워크이다. pip install fastapi 2. Uvicorn 설치 웹 서버로는 Uvicorn을 사용합니다. pip install uvicorn 3. 파이썬 작성 from fastapi import FastAPI import uvicorn # FastAPI 인스턴스 생성 app = FastAPI() # 요청 시 응답을 해주는 함수들 @app.get("/") async def root(): return 'welcome!' @app.get("/hello") async def world(): return 'hello!' # 서버 실행 if __name__ == "__main__": uvicorn.run(app, ho..

Python

파이썬 sqlite 연동

1. DB Browser for SQLite 설치 GUI로 DB를 관리할 수 있는 DB Browser를 설치한다. https://sqlitebrowser.org/ DB Browser for SQLite DB Browser for SQLite The Official home of the DB Browser for SQLite Screenshot What it is DB Browser for SQLite (DB4S) is a high quality, visual, open source tool to create, design, and edit database files compatible with SQLite. DB4S is for users and dev sqlitebrowser.org 2. 데이터베이스 ..