Python 114

[Pytest] 2. Pytest 명령어 옵션 (command)

Pytest 명령어 옵션 1. 해당 디렉토리 내 모든 test_.py, *_test.py 실행 $ pytest 2. 특정 디렉토리 내부 실행 $ python -m pytest / 3. 특정 테스트 함수만 실행시 (k 옵션) $ pytest .py -k 4. 하나라도 Fail시 멈추고 싶을 때 $ pytest -x 5. 각 테스트 함수 결과 출력 (보다 자세히) $ pytest -vv 6. . 모든 test 실행 결과 출력 pytest -rA (pass포함) pytest -ra (pass 제외) 7. 결과에 Color 입히고 싶을때 (kernel 창 등에서 쓰기 좋음) $ pytest --color=yes 8. 캐시 파일 초기화 - 정확성에 대한 CI 과정에 사용 권장 (clear-cache ) $ pyt..

Python/Advanced 2022.11.05

[Pytest] 1. Pytest란? (+ 프레임워크 별 사용)

Pytest란? Python 코드를 단위 테스트 (= 유닛테스트) 하기 위한 TEST Framework로, Python 기반 프로젝트의 TDD (Test Driven Development)에 주로 사용 과거 TDD 종류 기반 정리 글 링크 [SW 개발] 테스트 중심의 개발 TDD (with. Unit, E2E, Integration) "의도하지 않은 결함 수가 많아지면 개발자는 변경을 주저한다" 테스트 주도 개발 (TDD) 란? Test Driven Development 의 약자로 테스트 주도 개발이란는 뜻을 가지는 소프트웨어 개발 방법론 중 하나이 yubi5050.tistory.com Pytest 특징 테스트를 작성하는 데 있어 함수만 정의하면 되므로 편리 (단, pytest만의 고유한 방식을 익혀야 ..

Python/Advanced 2022.11.04

[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