Python (100) 썸네일형 리스트형 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 파일에 위와.. python sqlalchemy: MySQL, PostgreSQL 호환 작업 python ORM library중 하나인 sqlalchemy를 MySQL, PostgreSQL 모두 동작이 가능하도록 호환성을 고려하여 사용하기 1. Boolean: MySQL이든 PostgreSQL이든 Boolean Column 속성 사용하기 MySQL tinyint vs PostgreSQL boolean MySQL은 Boolean을 표현할 때 tinyint 타입을 권장 0을 false, 1을 true로 sqlalchemy로 Boolean type을 import하고 Column을 Boolean으로 설정하면 생성된 table의 column이 tinyint(1)로 설정되어 있는 것을 확인 가능 PostgreSQL은 boolean 타입 지원 boolean 타입 속성 컬럼에는 false, true 값이 들어.. 이전 1 2 3 4 5 6 ··· 13 다음