Microsoft MVP성태의 닷넷 이야기
오류 유형: 776. uwsgi-plugin-python3 환경에서 MySQLdb 사용 환경 [링크 복사], [링크+제목 복사]
조회: 7691
글쓴 사람
정성태 (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)
13429정성태10/27/20232932닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233003닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233187닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233352스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233162닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233145스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233283닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233333닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235495스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233163스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233854닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233405닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233202오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233689닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233464디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233659닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20236944닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233445Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20234963닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233818닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233799Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233552닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233515VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
13405정성태9/3/20233950닷넷: 2138. C# - async 메서드 호출 원칙
13404정성태8/29/20233460오류 유형: 876. Windows - 키보드의 등호(=, Equals sign) 키가 눌리지 않는 경우
13403정성태8/21/20233299오류 유형: 875. The following signatures couldn't be verified because the public key is not available: NO_PUBKEY EB3E94ADBE1229CF
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...