Python 112

[FastAPI] (7) MySQL 연결 및 API Test

MySQL 설치 및 DB 생성 1-1. MySql 설치 (로컬 pc에 직접 설치) https://www.mysql.com/downloads/ MySQL :: MySQL Downloads MySQL Cluster CGE MySQL Cluster is a real-time open source transactional database designed for fast, always-on access to data under high throughput conditions. MySQL Cluster MySQL Cluster Manager Plus, everything in MySQL Enterprise Edition Learn More » C www.mysql.com 1-2. Docker MySQL 설치 doc..

Python/FastAPI 2022.11.01

[FastAPI] (6) 보일러 플레이트 (Boiler Plate)

BoilerPlate란? BoilerPlate Code란 재 사용할 수 있는 뼈대 코드로, 보일러 플레이트를 작성해 놓고, 프로젝트 신규 생성 시마다 적용하여 사용 가능하다. 폴더 구조 FastAPI BoilerPlate ┌─FastAPI BoilerPlate │ └─deployments │ │ │ └─ Dockerfile ├─src │ ├─app.py : 최초 main 실행 함수 │ │ │ ├─dtos/ : Input, Output 전달 Object │ │ │ ├─db/ : DB Connect and CRUD │ │ │ ├─models/ : DB models │ │ │ ├─router/ : API Router │ │ │ ├─services/ : 비즈니스 로직 서비스 │ │ │ └─test/ : 모듈별 ..

Python/FastAPI 2022.10.27

[FastAPI] (5) FastAPI Validation - Path, Query, Field

Path, Query, Field Pydantic의 데이터 검증에 덧붙여 FastAPI의 Field, Path, Query를 사용해 매개변수를 명시적으로 정의하고, 좀더 세부적인 데이터 검증이 가능하다. gt, ge, lt, le : 숫자 대소비교 (greater than, less than 등) min_length, max_length : 문자열 길이 값 min_items, max_items : List, Set등의 Collection 객체 담당 regex 등 도 사용 가능 방법에는 크게 2가지가 존재 함수 인자에서 FastAPI의 Path, Query를 활용하는 방법 BaseModel을 상속한 Class에서 Pydantic의 Field 사용 방법 예제 공통 부분 - 임의 데이터셋 생성 예제 1과 예제..

Python/FastAPI 2022.10.26

[FastAPI] (4) FastAPI POST 작성법

POST Method FastAPI 에서 POST Method는 다음과 같은 특징이 있다. Schema Dependency가 존재한다. (Pydantic) BaseModel을 상속 받은 객체로 인자를 넘겨 받아야 한다. POST Method 예제 1 Pydantic의 이메일 (EmailStr), 파일 경로, 우편 번호, URL(HttpURL) 를 사용하면 다양한 형태의 값을 쉽게 검증 가능 from fastapi import FastAPI, status from pydantic import BaseModel, HttpUrl from typing import Optional app = FastAPI() class User(BaseModel): name:str url:Optional[HttpUrl] = No..

Python/FastAPI 2022.10.26

[Python Utils] Python 매직메소드 (MagicMethod) 이해하기

매직메소드란? "__Method__" 형태의 인스턴스(객체)가 생성될 때 인터프리터에 의해 자동으로 호출되는 메소드 매직메소드 예시 __init__, __call__, __getattribute__ 등은 모두 매직메소드의 형태로 호출된다. # 1. 기본 MagicMethod class A: def __init__(self): print("A 클래스 __init__ 생성자 매직메소드로 실행됨") # 2. Class를 함수 호출하기, __call__ 매직메소드 class B: def __call__(self, *args, **kwargs): print("B 클래스 __call__ 매직메소드로 호출됨") b = B() b() # 3. '.' 도 __getattribute__ 의 매직메소드 class C: de..

Python/Utils 2022.10.14

[FastAPI] (3) FastAPI 열거형 enum - GET

Enum이란? 열거형 (Enumeration) 객체로, Python 에서 Query Parameters, Path Parameters에 대한 Entity 정의를 하기 위해 사용 Case 1 from enum import Enum class Score(str, Enum): A="A" B="B" C="C" @app.get("/grade") def get_grade(score:Score): return {"score":score} 요청 1) curl localhost:8000/grade?score=A => { "score":A } 반환 요청 2) curl localhost:8000/grade => 422 entity error 발생 요청 3) curl localhost:8000/grade?score=D => ..

Python/FastAPI 2022.10.05

[FastAPI] (2) FastAPI 경로 매개변수, 쿼리 매개변수 - GET

경로 매개변수란? 경로 매개변수(Path Parameters)란 URL 경로에 들어가는 변수를 의미 아래 예시에서의 user_id를 뜻함 (매개 : 넘겨주는 + 변수 : 변하는 값) Case 1 @app.get("/users/{user_id}") def get_user(user_id:int): return {"user_id":user_id} 요청 1) curl localhost:8000/users/3 => { "user_id":3 } 반환 요청 2) curl localhost:8000/users/3.4 => 422 entity error 발생 (type 안맞아서 발생하는 error) Case 2 @app.get("/users/{user_id}/{art_id}") def get_user(user_id:in..

Python/FastAPI 2022.10.04

[FastAPI] (1) FastAPI란? (+Setting)

Fast API 란? FastAPI - https://fastapi.tiangolo.com/ FastAPI FastAPI FastAPI framework, high performance, easy to learn, fast to code, ready for production Documentation: https://fastapi.tiangolo.com Source Code: https://github.com/tiangolo/fastapi FastAPI is a modern, fast (high-performance), web framework for buil fastapi.tiangolo.com 코어 시스템 (Starlette) Wrapping을 통한 ASGI 지원과, Pydantic을 통한 간편한 유..

Python/FastAPI 2022.10.04

[Python Utils] Python 제너레이터 사용

제너레이터 동작 방식 Generator yield 문은 메모리 절약을 위한 기법으로, generator는 iterator를 생성해주고 함수 안에 yield 키워드를 이용해서 데이터를 순차적으로 반환한다. 제너레이터의 이점으로는 메모리 절약 뿐만 아니라, 자연스러운 데이터 흐름 파이프라인으로 구성이 가능하다. (ex. 긴 스트림에 대한 주기적인 처리를 할 때, 특정 단위로 반복이 가능하다.) 제너레이터의 동작방식은 아래와 같다. 예제 코드 #제네레이터 생성 def ex_func1(nums): for i in nums: yield i * i if __name__ =="__main__": generator_ex = ex_func1([1,2,3]) print(next(generator_ex)) # 1 print..

Python/Utils 2022.08.25

[Python Utils] Python Decorator 활용

Python Decorator란? 파이썬 데코레이터란 함수를 수정하지 않고 추가 적인 기능을 더하고 싶을 때 주로 사용 아래 예제 코드를 수행하면 함수 호출 전이나 후에 기능이 동작하게 할 수 있다. def trace(func): # 호출할 함수를 매개변수로 받음 def wrapper(): print(func.__name__, '함수 시작') # __name__으로 함수 이름 출력 func() # 매개변수로 받은 함수를 호출 print(func.__name__, '함수 끝') return wrapper # wrapper 함수 반환 @trace # @데코레이터 def hello(): print('hello') hello() # 함수를 그대로 호출 ##출력 결과 hello 함수 시작 hello hello 함..

Python/Utils 2022.08.25