Microsoft MVP성태의 닷넷 이야기
오류 유형: 776. uwsgi-plugin-python3 환경에서 MySQLdb 사용 환경 [링크 복사], [링크+제목 복사]
조회: 7680
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

uwsgi-plugin-python3 환경에서 MySQLdb 사용 환경

지난 글에 이어서,

uwsgi-plugin-python3 환경에서 "ModuleNotFoundError: No module named 'django'" 오류 발생
; https://www.sysnet.pe.kr/2/0/12883

결론 먼저 말하면, "uwsgi-plugin-python3" 구성 요소를 설치한 경우 MySQLdb 사용에 문제가 발생했을 때 이를 해결할 수 있는 방법을 모르겠습니다.

일단, pip install로 설치가 안 되었다면 "ModuleNotFoundError: No module named 'MySQLdb'" 예외가 발생할 것입니다. 지난 글에 썼듯이,

파이썬 - MySQLdb 기본 예제 코드
; https://www.sysnet.pe.kr/2/0/12851

"pip install mysqlclient" 명령어를 내리면 될 텐데요, "python:3.8-slim-buster" 이미지에 기반을 둔 컨테이너에서는 이렇게 오류가 발생합니다.

# pip install mysqlclient==2.0.3
Collecting mysqlclient==2.0.3
  Using cached mysqlclient-2.0.3.tar.gz (88 kB)
  Preparing metadata (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: /usr/local/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-w1zz1c6a/mysqlclient_467a1bf0e991450692698d99ca84297f/setup.py'"'"'; __file__='"'"'/tmp/pip-install-w1zz1c6a/mysqlclient_467a1bf0e991450692698d99ca84297f/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-lt0x_9ui
       cwd: /tmp/pip-install-w1zz1c6a/mysqlclient_467a1bf0e991450692698d99ca84297f/
  Complete output (15 lines):
  /bin/sh: 1: mysql_config: not found
  /bin/sh: 1: mariadb_config: not found
  /bin/sh: 1: mysql_config: not found
  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "/tmp/pip-install-w1zz1c6a/mysqlclient_467a1bf0e991450692698d99ca84297f/setup.py", line 15, in <module>
      metadata, options = get_config()
    File "/tmp/pip-install-w1zz1c6a/mysqlclient_467a1bf0e991450692698d99ca84297f/setup_posix.py", line 70, in get_config
      libs = mysql_config("libs")
    File "/tmp/pip-install-w1zz1c6a/mysqlclient_467a1bf0e991450692698d99ca84297f/setup_posix.py", line 31, in mysql_config
      raise OSError("{} not found".format(_mysql_config_path))
  OSError: mysql_config not found
  mysql_config --version
  mariadb_config --version
  mysql_config --libs
  ----------------------------------------
WARNING: Discarding https://files.pythonhosted.org/packages/3c/df/59cd2fa5e48d0804d213bdcb1acb4d08c403b61c7ff7ed4dd4a6a2deb3f7/mysqlclient-2.0.3.tar.gz#sha256=f6ebea7c008f155baeefe16c56cd3ee6239f7a5a9ae42396c2f1860f08a7c432 (from https://pypi.org/simple/mysqlclient/) (requires-python:>=3.5). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
ERROR: Could not find a version that satisfies the requirement mysqlclient==2.0.3 (from versions: 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.3.8, 1.3.9, 1.3.10, 1.3.11rc1, 1.3.11, 1.3.12, 1.3.13, 1.3.14, 1.4.0rc1, 1.4.0rc2, 1.4.0rc3, 1.4.0, 1.4.1, 1.4.2, 1.4.2.post1, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 2.0.0, 2.0.1, 2.0.2, 2.0.3, 2.1.0rc1, 2.1.0)
ERROR: No matching distribution found for mysqlclient==2.0.3

에러 메시지를 보면 mysql_config, mariadb_config 중의 하나는 있어야 설치가 잘 되는 것 같습니다. 이에 대해 검색해 보면 "libmysqlclient-dev"를 설치하면 된다고 합니다.

$ sudo apt-get install libmysqlclient-dev

그런데, "python:3.8-slim-buster"가 사용하는 데비안에는 이런 패키지가 없다고 합니다. ^^

# apt-get install libmysqlclient-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package libmysqlclient-dev is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
However the following packages replace it:
  libmariadb-dev-compat libmariadb-dev

E: Package 'libmysqlclient-dev' has no installation candidate

대신 메시지를 보면 "libmariadb-dev-compat, "libmariadb-dev" 패키지에 속해 있다고 하는데요, 따라서 "libmariadb-dev"를 설치를 하면 됩니다.

# apt install libmariadb-dev

이후 다시 "pip install mysqlclient==2.0.3" 설치를 시도하면 그래도 오류가 발생하지만 메시지는 바뀌었습니다.

# pip install mysqlclient==2.0.3
Collecting mysqlclient==2.0.3
  Using cached mysqlclient-2.0.3.tar.gz (88 kB)
  Preparing metadata (setup.py) ... done
Building wheels for collected packages: mysqlclient
  Building wheel for mysqlclient (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: /usr/local/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-s5mutp72/mysqlclient_c01ebe68053541e8b1468e1a5ab5dc37/setup.py'"'"'; __file__='"'"'/tmp/pip-install-s5mutp72/mysqlclient_c01ebe68053541e8b1468e1a5ab5dc37/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-oys2zgga
       cwd: /tmp/pip-install-s5mutp72/mysqlclient_c01ebe68053541e8b1468e1a5ab5dc37/
  Complete output (43 lines):
  mysql_config --version
  /bin/sh: 1: mysql_config: not found
  mariadb_config --version
  ['10.3.31']
  mariadb_config --libs
  ['-L/usr/lib/x86_64-linux-gnu/', '-lmariadb']
  mariadb_config --cflags
  ['-I/usr/include/mariadb', '-I/usr/include/mariadb/mysql']
  ext_options:
    library_dirs: ['/usr/lib/x86_64-linux-gnu/']
    libraries: ['mariadb']
    extra_compile_args: ['-std=c99']
    extra_link_args: []
    include_dirs: ['/usr/include/mariadb', '/usr/include/mariadb/mysql']
    extra_objects: []
    define_macros: [('version_info', "(2,0,3,'final',0)"), ('__version__', '2.0.3')]
  running bdist_wheel
...[생략]...
  building 'MySQLdb._mysql' extension
  creating build/temp.linux-x86_64-3.8
  creating build/temp.linux-x86_64-3.8/MySQLdb
  gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -Dversion_info=(2,0,3,'final',0) -D__version__=2.0.3 -I/usr/include/mariadb -I/usr/include/mariadb/mysql -I/usr/local/include/python3.8 -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-3.8/MySQLdb/_mysql.o -std=c99
  unable to execute 'gcc': No such file or directory
  error: command 'gcc' failed with exit status 1
  ----------------------------------------
  ERROR: Failed building wheel for mysqlclient
  Running setup.py clean for mysqlclient
Failed to build mysqlclient
Installing collected packages: mysqlclient
    Running setup.py install for mysqlclient ... error
    ERROR: Command errored out with exit status 1:
     command: /usr/local/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-s5mutp72/mysqlclient_c01ebe68053541e8b1468e1a5ab5dc37/setup.py'"'"'; __file__='"'"'/tmp/pip-install-s5mutp72/mysqlclient_c01ebe68053541e8b1468e1a5ab5dc37/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-5b6anm21/install-record.txt --single-version-externally-managed --compile --install-headers /usr/local/include/python3.8/mysqlclient
         cwd: /tmp/pip-install-s5mutp72/mysqlclient_c01ebe68053541e8b1468e1a5ab5dc37/
    Complete output (43 lines):
    mysql_config --version
    /bin/sh: 1: mysql_config: not found
    mariadb_config --version
    ['10.3.31']
    mariadb_config --libs
    ['-L/usr/lib/x86_64-linux-gnu/', '-lmariadb']
    mariadb_config --cflags
    ['-I/usr/include/mariadb', '-I/usr/include/mariadb/mysql']
    ext_options:
      library_dirs: ['/usr/lib/x86_64-linux-gnu/']
      libraries: ['mariadb']
      extra_compile_args: ['-std=c99']
      extra_link_args: []
      include_dirs: ['/usr/include/mariadb', '/usr/include/mariadb/mysql']
      extra_objects: []
      define_macros: [('version_info', "(2,0,3,'final',0)"), ('__version__', '2.0.3')]
    running install
    running build
    running build_py
    creating build
...[생략]...
    running build_ext
    building 'MySQLdb._mysql' extension
    creating build/temp.linux-x86_64-3.8
    creating build/temp.linux-x86_64-3.8/MySQLdb
    gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -Dversion_info=(2,0,3,'final',0) -D__version__=2.0.3 -I/usr/include/mariadb -I/usr/include/mariadb/mysql -I/usr/local/include/python3.8 -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-3.8/MySQLdb/_mysql.o -std=c99
    unable to execute 'gcc': No such file or directory
    error: command 'gcc' failed with exit status 1
    ----------------------------------------
ERROR: Command errored out with exit status 1: /usr/local/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-s5mutp72/mysqlclient_c01ebe68053541e8b1468e1a5ab5dc37/setup.py'"'"'; __file__='"'"'/tmp/pip-install-s5mutp72/mysqlclient_c01ebe68053541e8b1468e1a5ab5dc37/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-5b6anm21/install-record.txt --single-version-externally-managed --compile --install-headers /usr/local/include/python3.8/mysqlclient Check the logs for full command output.

음... gcc가 있어야 한다는군요. ^^; 그래도 마지막 단계이니 기쁜 마음으로 설치하고,

# apt install build-essential

이후 mysqlclient가 정상적으로 설치됩니다.

# pip install mysqlclient==2.0.3




그런데 실제로 uwsgi-plugin-python3으로 호스팅하는 파이썬 코드에서 사용해 보면 이번에는 다음과 같은 오류가 발생합니다.

NameError: name '_mysql' is not defined

검색해 보면,

NameError: name '_mysql' is not defined after setting change to mysql
; https://stackoverflow.com/questions/63109987/nameerror-name-mysql-is-not-defined-after-setting-change-to-mysql

이 오류는 mysql Native 라이브러리를 찾지 못해서인 것 같습니다.

# find / -path /mnt -prune -o -name mysql 2>/dev/null
/etc/mysql
/mnt
/usr/local/lib/python3.8/site-packages/django/db/backends/mysql
/usr/local/lib/python3.8/site-packages/django/contrib/gis/db/backends/mysql
/usr/include/mariadb/server/mysql
/usr/include/mariadb/mysql

뭔가 구성은 된 것 같은데 ^^... 어쨌든 여기서 막혔습니다. 재미있는 것은, 그냥 python 3.8 shell에서는 아무런 문제 없이 import가 잘 됩니다.

# python
Python 3.8.12 (default, Dec  3 2021, 02:23:43)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>> MySQLdb.connect("192.168.100.50", "testusr", "testpw", "testdb", charset='utf8', connect_timeout=3)
<_mysql.connection open to '192.168.100.50' at 0x556d823fb3e0>
>>>

하지만 동일한 명령어가 (내부적으로 3.7을 호스팅하는) uwsgi-plugin-python3 구성 요소의 환경에서는 오류가 발생하는 것입니다. 아무래도 이게 해결되려면 uwsgi-plugin-python3가 자체 호스팅하는 python 3.7 환경에 대해 pip install을 적용해 mysqlclient를 설치해야 하지 않을까 싶은데, 그 방법을 모르겠습니다. (혹시 아시는 분은 덧글 부탁드립니다. ^^)




하지만, 저런 노력 필요 없이 그냥 애당초 uwsgi-plugin-python3 구성 요소를 사용하지 않고 "pip install uwsgi"로 설치한 환경에서 동작시키면 잘 됩니다. ^^;




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







[최초 등록일: ]
[최종 수정일: 12/20/2021]

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

비밀번호

댓글 작성자
 




1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13581정성태3/18/20241606개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241166닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241495오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241637닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241891닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241545닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241686닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241562닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241571닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241650닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241631닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241638닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241546닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241611닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241620오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241632오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241481닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241618Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241705디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20241700오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20241931닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20241936디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242810오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20242011닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241766Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241826Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...