Microsoft MVP성태의 닷넷 이야기
오류 유형: 776. uwsgi-plugin-python3 환경에서 MySQLdb 사용 환경 [링크 복사], [링크+제목 복사]
조회: 7595
글쓴 사람
정성태 (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)
13398정성태8/3/20234135스크립트: 55. 파이썬 - pyodbc를 이용한 SQL Server 연결 사용법
13397정성태7/23/20233642닷넷: 2134. C# - 문자열 연결 시 string.Create를 이용한 GC 할당 최소화
13396정성태7/22/20233341스크립트: 54. 파이썬 pystack 소개 - 메모리 덤프로부터 콜 스택 열거
13395정성태7/20/20233311개발 환경 구성: 685. 로컬에서 개발 중인 ASP.NET Core/5+ 웹 사이트에 대해 localhost 이외의 호스트 이름으로 접근하는 방법
13394정성태7/16/20233255오류 유형: 873. Oracle.ManagedDataAccess.Client - 쿼리 수행 시 System.InvalidOperationException
13393정성태7/16/20233420닷넷: 2133. C# - Oracle 데이터베이스의 Sleep 쿼리 실행하는 방법
13392정성태7/16/20233297오류 유형: 872. Oracle - ORA-01031: insufficient privileges
13391정성태7/14/20233369닷넷: 2132. C# - sealed 클래스의 메서드를 callback 호출했을 때 인라인 처리가 될까요?
13390정성태7/12/20233339스크립트: 53. 파이썬 - localhost 호출 시의 hang 현상
13389정성태7/5/20233322개발 환경 구성: 684. IIS Express로 호스팅하는 웹을 WSL 환경에서 접근하는 방법
13388정성태7/3/20233513오류 유형: 871. 윈도우 탐색기에서 열리지 않는 zip 파일 - The Compressed (zipped) Folder '[...].zip' is invalid. [1]파일 다운로드1
13387정성태6/28/20233533오류 유형: 870. _mysql - Commands out of sync; you can't run this command now
13386정성태6/27/20233601Linux: 61. docker - 원격 제어를 위한 TCP 바인딩 추가
13385정성태6/27/20233820Linux: 60. Linux - 외부에서의 접속을 허용하기 위한 TCP 포트 여는 방법
13384정성태6/26/20233566.NET Framework: 2131. C# - Source Generator로 해결하는 enum 박싱 문제파일 다운로드1
13383정성태6/26/20233313개발 환경 구성: 683. GPU 런타임을 사용하는 Colab 노트북 설정
13382정성태6/25/20233356.NET Framework: 2130. C# - Win32 API를 이용한 윈도우 계정 정보 (예: 마지막 로그온 시간)파일 다운로드1
13381정성태6/25/20233741오류 유형: 869. Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
13380정성태6/24/20233195스크립트: 52. 파이썬 3.x에서의 동적 함수 추가
13379정성태6/23/20233209스크립트: 51. 파이썬 2.x에서의 동적 함수 추가
13378정성태6/22/20233094오류 유형: 868. docker - build 시 "CANCELED ..." 뜨는 문제
13377정성태6/22/20236895오류 유형: 867. 파이썬 mysqlclient 2.2.x 설치 시 "Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually" 오류
13376정성태6/21/20233283.NET Framework: 2129. C# - Polly를 이용한 클라이언트 측의 요청 재시도파일 다운로드1
13375정성태6/20/20232984스크립트: 50. Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과
13374정성태6/20/20233110오류 유형: 866. 파이썬 - <class 'AttributeError'> module 'flask.json' has no attribute 'JSONEncoder'
13373정성태6/19/20234398오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...