Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)
(시리즈 글이 2개 있습니다.)
스크립트: 41. 파이썬 - FastAPI / uvicorn 호스팅 환경에서 asyncio 사용하는 방법
; https://www.sysnet.pe.kr/2/0/13087

스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
; https://www.sysnet.pe.kr/2/0/13431




파이썬 - FastAPI / uvicorn 호스팅 환경에서 asyncio 사용하는 방법

간단한 FastAPI 예제에서 단지 asyncio를,

aiomysql
; https://pypi.org/project/aiomysql/

이렇게 사용했을 뿐인데,

# 실행 명령어
# uvicorn main:app --reload --host 0.0.0.0 --port 18003

from fastapi import FastAPI

app = FastAPI()

@app.get("/aio_func_test")
async def aio_func_test():
    import asyncio
    loop = asyncio.get_event_loop()
    loop.run_until_complete(my_func())
    return "test"


def my_func():
    return "my value"

run_until_complete 호출에서 예외가 발생합니다.

...[생략]...
  File "/mnt/d/testprj/p38fastapi/./main.py", line 51, in aio_func_test
    loop.run_until_complete(my_func())
  File "uvloop/loop.pyx", line 1495, in uvloop.loop.Loop.run_until_complete
  File "uvloop/loop.pyx", line 1488, in uvloop.loop.Loop.run_until_complete
  File "uvloop/loop.pyx", line 1377, in uvloop.loop.Loop.run_forever
  File "uvloop/loop.pyx", line 511, in uvloop.loop.Loop._run
RuntimeError: this event loop is already running.

아마도, 이미 해당 프로세스에서는 event loop를 초기화해 사용하는 듯하고, 별도의 asyncio를 사용할 수는 없는 것 같습니다.

검색해 보면,

RuntimeError: This event loop is already running in python
; https://stackoverflow.com/questions/46827007/runtimeerror-this-event-loop-is-already-running-in-python

2가지 방법을 제시하는데요, 우선 asyncio.set_event_loop 호출은,

import asyncio
asyncio.set_event_loop(asyncio.new_event_loop())

함수 호출 자체에는 오류가 없었지만 이전과 마찬가지로 run_until_complete 호출 시 "RuntimeError: this event loop is already running." 예외가 발생했습니다.

그다음 제시한 방법이 nest-asyncio를 사용하는 것인데요,

nest-asyncio
; https://pypi.org/project/nest-asyncio/

아래와 같이 사용했더니,

# pip install nest-asyncio

from fastapi import FastAPI

import nest_asyncio
nest_asyncio.apply()

app = FastAPI()

#  ...[생략]...

이번에는 nest_asyncio.apply 호출 시에 다음과 같은 오류가 발생합니다.

...[생략]...
  File "/mnt/d/testprj/p38fastapi/./main.py", line 9, in <module>
    nest_asyncio.apply()
  File "/home/testusr/.local/lib/python3.8/site-packages/nest_asyncio.py", line 17, in apply
    _patch_loop(loop)
  File "/home/testusr/.local/lib/python3.8/site-packages/nest_asyncio.py", line 174, in _patch_loop
    raise ValueError('Can\'t patch loop of type %s' % type(loop))
ValueError: Can't patch loop of type <class 'uvloop.Loop'>

처음에는 저게 무슨 소리인가 싶었는데... ^^; nest-asyncio PyPI 문서에서 이를 해결하기 위한 힌트를 얻을 수 있습니다.

Optionally the specific loop that needs patching can be given as argument to apply, otherwise the current event loop is used. An event loop can be patched whether it is already running or not. Only event loops from asyncio can be patched; Loops from other projects, such as uvloop or quamash, generally can’t be patched.


그렇다는 것은, 결국 FastAPI를 호스팅하는 응용 프로그램, 이 글에서는 uvicorn에 Event Loop를 지정하는 옵션이 있다는 것을 의미합니다. 실제로 확인해 볼까요? ^^

$ uvicorn --help
Usage: uvicorn [OPTIONS] APP

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.
  ...[생략]...
  --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]
  ...[생략]...

보면, asyncio와 uvloop를 지원하는데요, 기본 값이 auto이고 "Can't patch loop of type <class 'uvloop.Loop'>"라는 오류 메시지에서 uvloop가 선택된 것임을 알 수 있습니다.

따라서 uvicorn을 다음과 같이 실행하면,

$ uvicorn main:app --reload --host 0.0.0.0 --port 18003 --loop asyncio

이제 정상적으로 loop.run_until_complete 코드까지 실행됩니다.




재미있는 상황이 하나 더 있는데요, nest_asyncio.apply()를 호출하는 시기를 다음과 같이 늦춰도 일단 잘 실행은 됩니다.

from fastapi import FastAPI

app = FastAPI()

@app.get("/aio_func_test")
async def aio_func_test():
    import asyncio

    import nest_asyncio
    nest_asyncio.apply()

    loop = asyncio.get_event_loop()
    loop.run_until_complete(my_func())
    return "test"


def my_func():
    return "my value"

하지만, 위와 같은 상황에서 middleware를 하나 추가하면,

# ....[생략]...
from starlette.middleware.base import BaseHTTPMiddleware

class MyMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        response = await call_next(request)
        return response


app = FastAPI()
app.add_middleware(MyMiddleware)

# ....[생략]...

또는, 이렇게 추가해도,

# ....[생략]...

# https://fastapi.tiangolo.com/tutorial/middleware/#create-a-middleware

@app.middleware("http")
async def add_process_time_header(request, call_next):
    response = await call_next(request)
    return response

이번엔 다음과 같은 예외가 발생하면서 요청 처리 자체가 중단되지를 않습니다.

Exception in callback <TaskStepMethWrapper object at 0x7f5be53ebdf0>()
handle: <Handle <TaskStepMethWrapper object at 0x7f5be53ebdf0>()>
Traceback (most recent call last):
  File "/usr/lib/python3.8/asyncio/events.py", line 81, in _run
    self._context.run(self._callback, *self._args)
RuntimeError: Cannot enter into task <Task pending name='Task-6' coro=<RequestResponseCycle.run_asgi() running at /home/testusr/.local/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py:372> cb=[set.discard()]> while another task <Task pending name='starlette.middleware.base.BaseHTTPMiddleware.__call__.<locals>.call_next.<locals>.coro' coro=<BaseHTTPMiddleware.__call__.<locals>.call_next.<locals>.coro() running at /home/testusr/.local/lib/python3.8/site-packages/starlette/middleware/base.py:36> cb=[TaskGroup._spawn.<locals>.task_done() at /home/testusr/.local/lib/python3.8/site-packages/anyio/_backends/_asyncio.py:726]> is being executed.

물론, middleware가 있어도 nest_asyncio.apply 호출 자체를 초기에 실행하면 정상적으로 실행은 됩니다.

음... 이것이 어느 한 쪽의 버그인지, 아니면 원래 nest_asyncio.apply 호출을 초기에만 하는 것이 올바른 것인지는 잘 모르겠습니다. (혹시 아시는 분은 덧글 부탁드립니다. ^^)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 10/11/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2022-09-30 12시38분
[와] 정말 큰 도움 되었습니다. 감사합니다.
[guest]

... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13541정성태1/29/20249622VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20249515Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20249315개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20249922닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/202410709닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/202410321닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/202410756닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/202410146닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/202410142닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/202410193닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/202410577닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20249853닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/202410049닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/202410214Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/202410298오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/202410635닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20249768오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20249800오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20249784오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/202410616닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/202410273닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20249952오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....' [1]
13519정성태1/10/20249643닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/202410380닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20249502스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20249677닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...