본문 바로가기
카테고리 없음

[fastapi] uvicorn, fastapi, python 이해하기

by SIXXXX_ 2022. 11. 30.
728x90

https://m.blog.naver.com/pjt3591oo/222772705407

 

[fastapi] uvicorn, fastapi 비동기 메커니즘 이해

안녕하세요 멍개입니다. 최근에 MLOps를 공부하면서 새로운 스택을 다뤄보고 싶어서 fastapi를 다뤄보게...

blog.naver.com

 

 

ASGI 에러가 자주 나가지고 찾아봤다.

 

uvicorn은 비동기 인터페이스를 통해 구현된 ASGI 웹서버

 

ASGI : WSGI

- ASGI 는 uvicorn 을 많이 사용한다.
- 네트워크 I/O 에 대한 콜백 위주로 관리한다.

- httptools 를 httpparser 로 이용

- fastapi는 ASGI 인터페이스가 구현된 starlette 를 추상화하여 구현한 프레임워크이다.

 

 

async def / await def vs def 차이

 

async/await def는 비동기 처리 라이브러리, 외부 스레드 풀에서 실행하지 않아 블록킹된다.

아닐 경우 def 를 사용 : 외부 스레드 풀에서 다이렉트로 실행하여 서버가 블록킹되지 않는다.

 

외부 스레드 풀 : fastapi 가 가지고 있는 스레드를 의미한다.

 

uvicorn main:app --port 8000

 

결론은 python은 프로세스 기반으로 동작, node.js는 스레드 기반으로 동작

 

uvicorn --help

 

Options:
  --host TEXT                     Bind socket to this host.  [default:
                                  127.0.0.1]
  --port INTEGER                  Bind socket to this port.  [default: 8000]
  --uds TEXT                      Bind to a UNIX domain socket.
  --fd INTEGER                    Bind to socket from this file descriptor.
  --reload                        Enable auto-reload.
  --reload-dir PATH               Set reload directories explicitly, instead
                                  of using the current working directory.
  --reload-include TEXT           Set glob patterns to include while watching
                                  for files. Includes '*.py' by default; these
                                  defaults can be overridden with `--reload-
                                  exclude`. This option has no effect unless
                                  watchfiles is installed.
  --reload-exclude TEXT           Set glob patterns to exclude while watching
                                  for files. Includes '.*, .py[cod], .sw.*,
                                  ~*' by default; these defaults can be
                                  overridden with `--reload-include`. This
                                  option has no effect unless watchfiles is
                                  installed.
  --reload-delay FLOAT            Delay between previous and next check if
                                  application needs to be. Defaults to 0.25s.
                                  [default: 0.25]
  --workers INTEGER               Number of worker processes. Defaults to the
                                  $WEB_CONCURRENCY environment variable if
                                  available, or 1. Not valid with --reload.
  --loop [auto|asyncio|uvloop]    Event loop implementation.  [default: auto]
  --http [auto|h11|httptools]     HTTP protocol implementation.  [default:
                                  auto]
  --ws [auto|none|websockets|wsproto]
                                  WebSocket protocol implementation.
                                  [default: auto]
  --ws-max-size INTEGER           WebSocket max size message in bytes
                                  [default: 16777216]
  --ws-ping-interval FLOAT        WebSocket ping interval  [default: 20.0]
  --ws-ping-timeout FLOAT         WebSocket ping timeout  [default: 20.0]
  --ws-per-message-deflate BOOLEAN
                                  WebSocket per-message-deflate compression
                                  [default: True]
  --lifespan [auto|on|off]        Lifespan implementation.  [default: auto]
  --interface [auto|asgi3|asgi2|wsgi]
                                  Select ASGI3, ASGI2, or WSGI as the
                                  application interface.  [default: auto]
  --env-file PATH                 Environment configuration file.
  --log-config PATH               Logging configuration file. Supported
                                  formats: .ini, .json, .yaml.
  --log-level [critical|error|warning|info|debug|trace]
                                  Log level. [default: info]
  --access-log / --no-access-log  Enable/Disable access log.
  --use-colors / --no-use-colors  Enable/Disable colorized logging.
  --proxy-headers / --no-proxy-headers
                                  Enable/Disable X-Forwarded-Proto,
                                  X-Forwarded-For, X-Forwarded-Port to
                                  populate remote address info.
  --server-header / --no-server-header
                                  Enable/Disable default Server header.
  --date-header / --no-date-header
                                  Enable/Disable default Date header.
  --forwarded-allow-ips TEXT      Comma separated list of IPs to trust with
                                  proxy headers. Defaults to the
                                  $FORWARDED_ALLOW_IPS environment variable if
                                  available, or '127.0.0.1'.
  --root-path TEXT                Set the ASGI 'root_path' for applications
                                  submounted below a given URL path.
  --limit-concurrency INTEGER     Maximum number of concurrent connections or
                                  tasks to allow, before issuing HTTP 503
                                  responses.
  --backlog INTEGER               Maximum number of connections to hold in
                                  backlog
  --limit-max-requests INTEGER    Maximum number of requests to service before
                                  terminating the process.
  --timeout-keep-alive INTEGER    Close Keep-Alive connections if no new data
                                  is received within this timeout.  [default:
                                  5]
  --ssl-keyfile TEXT              SSL key file
  --ssl-certfile TEXT             SSL certificate file
  --ssl-keyfile-password TEXT     SSL keyfile password
  --ssl-version INTEGER           SSL version to use (see stdlib ssl module's)
                                  [default: 17]
  --ssl-cert-reqs INTEGER         Whether client certificate is required (see
                                  stdlib ssl module's)  [default: 0]
  --ssl-ca-certs TEXT             CA certificates file
  --ssl-ciphers TEXT              Ciphers to use (see stdlib ssl module's)
                                  [default: TLSv1]
  --header TEXT                   Specify custom default HTTP response headers
                                  as a Name:Value pair
  --version                       Display the uvicorn version and exit.
  --app-dir TEXT                  Look for APP in the specified directory, by
                                  adding this to the PYTHONPATH. Defaults to
                                  the current working directory.  [default: .]
  --h11-max-incomplete-event-size INTEGER
                                  For h11, the maximum number of bytes to
                                  buffer of an incomplete event.
  --factory                       Treat APP as an application factory, i.e. a
                                  () -> <ASGI app> callable.
  --help                          Show this message and exit.

 

 

[project 구조]

으렵다..

https://cha-vi.tistory.com/entry/Python-Uvicorn-%EC%9D%BC%EC%9E%90%EB%B3%84-%EB%A1%9C%EA%B7%B8-%EC%8C%93%EA%B8%B0with-FastAPI

 

[Python] Uvicorn 일자별 로그 쌓기(with. FastAPI)

Python의 ASGI(Asynchronous Server Gateway Interface) web server인 Uvicorn을 활용하여 서버를 실행 중, 일자별로 로그 파일을 생성하여 쌓는 방법을 기록합니다. 1. log.ini 파일 생성 [loggers] keys=root [handlers] keys=logf

cha-vi.tistory.com

 

나중에 들여다보기..