Python (101) 썸네일형 리스트형 FastAPI, Javascript: EventSource Example EventSource HTTP를 통해서 server-sent-events (SSEs)를 받기 위한 인터페이스 페이지 새로고침 없이 real-time(실시간)으로 서버에서 데이터를 받을 때 유용하게 쓸 수 있다. 아래는 오픈소스 g6의 데이터 베이스가 설치되는 과정에서 Python 코루틴을 활용하여 백엔드 FastAPI에서 프론트엔드 Javascript로 페이지 리로딩 없이 설치 정보를 전달하는 예제 @router.get("/process") async def install_process(request: Request): async def install_event(): db_connect = DBConnect() engine = db_connect.engine SessionLocal = db_connect.. FastAPI: WebSocket Example 1. Websocket을 통해 서버로부터 일정 주기로 데이터 받아오기 * fastapi와 websocket 사용을 위한 uvicorn[standard] 설치 pip install fastapi "uvicorn[standard]" * main.py from fastapi import FastAPI, WebSocket import asyncio app = FastAPI() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() counter = 0 while True: counter += 1 await websocket.send_json({"message": f"Update #{count.. SQLAlchemy: db pool 관리 DB connection pool from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker engine = create_engine( self._url, poolclass=QueuePool, pool_size=20, max_overflow=40, pool_timeout=70, pool_recycle=60, ) poolclass - 어떠한 connection pool을 사용할지에 대한 옵션 일반적으로 QueuePool을 사용하며, 옵션에 별도 명시하지 않을 경우 default 값이기도 하다. QueuePool - 재사용 가능한 pool 사용 - 다수의 동시적인 connection 허용 (multiple concurrent da.. Python: 서버 부하테스트 - locust python script로 간단하게 서버 부하테스트를 할 수 있는 library 사용법이 간단하고, 브라우저를 통해 분석 그래프까지 제공해준다. 설치: pip install locust locustfile.py 작성 from locust import HttpUser, task, between class WebsiteUser(HttpUser): wait_time = between(1, 5) @task def load_test(self): self.client.get("/your-endpoint") 테스트할 서버를 실행시키고, locust도 함께 실행시켜주자 locust는 기본적으로 8089 포트로 연결된다. 나는 fastapi 서버를 실행시키고 있고, fastapi는 기본적으로 8000포트로 열린다. fa.. request.scope vs request.headers in FastAPI # ChatGPT Q. in Python FastAPI, How can I see the request user's prefix whethere http or https? A. In FastAPI, you can determine whether a request uses HTTP or HTTPS by inspecting the request object. The request object contains various information about the incoming HTTP request, including the scheme which indicates whether the request was made using HTTP or HTTPS. To access the request object in FastAPI,.. FastAPI & SQLAlchemy: SQLAlchemy from 1.4 to 2.0 DB 연결 from fastapi import Depends from sqlalchemy import create_engine from sqlalchemy.orm import Session, sessionmaker from typing_extensions import Annotated engine = create_engine(DATABASE_URL) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine, expire_on_commit=True) async def get_db() -> Session: db = SessionLocal() try: yield db finally: db.close() db = Annotated[Se.. Python: datetime strftime strptime 의미 구분, # 어떤 의미? python 내장 라이브러리인 datetime을 통해서 특정 시간을 문자열로, 문자열을 특정 시간으로 변환 가능 이때, strftime과 strptime이 있는데, 이 의미를 알지 못해서 구분이 잘되지 않아 찾아보았다. strftime은 datetime 형태의 데이터를 문자열로 바꿔주고 strptime은 날짜형태로 되어 있는 문자열을 datetime 데이터로 바꿔준다. strftime: string format time (string format의 time) strptime: string parse time (string을 parse해서 time으로) 이제 헷갈리지 않고 기억이 잘 나지 않으려나 Python: python-dotenv - .env 파일 관련 library # load_dotenv # override 환경변수로 사용할 부분을 .env 파일로 따로 빼서 관리하는 경우에, 파이썬에서 해당 파일에서 변수를 불러오는 방법중의 하나로 python-dotenv 라이브러리가 있다. 설치: pip install python-dotenv from dotenv import load_dotenv import os load_dotenv()# .env에 있는 변수를 환경변수로 불러오기 os.getenv("DEBUG", False) # 환경변수에서 "DEBUG"로 이름이 되어있는 변수의 값 가져오기, 없을경우 False를 default 값으로 사용 위와 같이 하면 일반적으로 된다. 그런데, 잘 작업을 하던 중에 이상한 에러가 발생... # .env DEBUG = "False" # True or False .env 파일에 위와.. 이전 1 2 3 4 5 6 ··· 13 다음