상세 컨텐츠

본문 제목

[django] MySQL 연동하기

DEVELOPMENT/django

by 김도훈 2020. 10. 16. 01:51

본문

반응형

적용하기

1. MySQL 설치하기

아래 링크를 참조하여 차례대로 설치해준다.

dev.mysql.com/downloads/mysql/

 

MySQL :: Download MySQL Community Server

Select Operating System: Select Operating System… Microsoft Windows Ubuntu Linux Debian Linux SUSE Linux Enterprise Server Red Hat Enterprise Linux / Oracle Linux Fedora Linux - Generic Oracle Solaris macOS FreeBSD Source Code Select OS Version: All Wind

dev.mysql.com



Workbench가 필요하면 아래 링크에서 설치할 수 있다.

dev.mysql.com/downloads/workbench/

 

MySQL :: Download MySQL Workbench

Select Operating System: Select Operating System… Microsoft Windows Ubuntu Linux Red Hat Enterprise Linux / Oracle Linux Fedora macOS Source Code Select OS Version: All Windows (x86, 64-bit) Recommended Download: Other Downloads: Windows (x86, 64-bit), M

dev.mysql.com

이후 django에서 mySQL을 사용할수 있게 해주는 라이브러리를 설치해준다.

pipenv install mysqlclient

해준다

(project) kimdoehoon@gimdohun-ui-MacBookPro unifolio % pipenv install mysqlclient
Installing mysqlclient…
Adding mysqlclient to Pipfile's [packages]…
✔ Installation Succeeded 
Installing dependencies from Pipfile.lock (3aa65c)…
An error occurred while installing mysqlclient==2.0.1 --hash=sha256:3f39855a4ad22805361e782cc4d1010ac74796225fa2d1c03cc16673ccdc983a --hash=sha256:a6b5648f648b16335e3b1aaec93dc3fcc81a9a661180e306936437cc522c810b --hash=sha256:edd42ccaa444b00702d5374b2f5f7585c9d0ce201917f15339f1c3cf91c1b1ed --hash=sha256:fb2f75aea14722390d2d8ddf384ad99da708c707a96656210a7be8af20a2c5e5! Will try again.
  🐍   ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 18/18 — 00:00:02
Installing initially failed dependencies…
[pipenv.exceptions.InstallError]:   File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pipenv/core.py", line 1992, in do_install
[pipenv.exceptions.InstallError]:       skip_lock=skip_lock,
[pipenv.exceptions.InstallError]:   File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pipenv/core.py", line 1253, in do_init
[pipenv.exceptions.InstallError]:       pypi_mirror=pypi_mirror,
[pipenv.exceptions.InstallError]:   File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pipenv/core.py", line 859, in do_install_dependencies
[pipenv.exceptions.InstallError]:       retry_list, procs, failed_deps_queue, requirements_dir, **install_kwargs
[pipenv.exceptions.InstallError]:   File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pipenv/core.py", line 763, in batch_install
[pipenv.exceptions.InstallError]:       _cleanup_procs(procs, not blocking, failed_deps_queue, retry=retry)
[pipenv.exceptions.InstallError]:   File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pipenv/core.py", line 681, in _cleanup_procs
[pipenv.exceptions.InstallError]:       raise exceptions.InstallError(c.dep.name, extra=err_lines)
[pipenv.exceptions.InstallError]: ['Collecting mysqlclient==2.0.1', '  Using cached mysqlclient-2.0.1.tar.gz (87 kB)']
[pipenv.exceptions.InstallError]: ['ERROR: Command errored out with exit status 1:', '     command: /Users/kimdoehoon/.local/share/virtualenvs/project-Z0k_OmvG/bin/python -c \'import sys, setuptools, tokenize; sys.argv[0] = \'"\'"\'/private/var/folders/_f/_7x2949j4v50k7k6nq9yx0z40000gn/T/pip-install-ngc34ts9/mysqlclient/setup.py\'"\'"\'; __file__=\'"\'"\'/private/var/folders/_f/_7x2949j4v50k7k6nq9yx0z40000gn/T/pip-install-ngc34ts9/mysqlclient/setup.py\'"\'"\';f=getattr(tokenize, \'"\'"\'open\'"\'"\', open)(__file__);code=f.read().replace(\'"\'"\'\\r\\n\'"\'"\', \'"\'"\'\\n\'"\'"\');f.close();exec(compile(code, __file__, \'"\'"\'exec\'"\'"\'))\' egg_info --egg-base /private/var/folders/_f/_7x2949j4v50k7k6nq9yx0z40000gn/T/pip-install-ngc34ts9/mysqlclient/pip-egg-info', '         cwd: /private/var/folders/_f/_7x2949j4v50k7k6nq9yx0z40000gn/T/pip-install-ngc34ts9/mysqlclient/', '    Complete output (12 lines):', '    /bin/sh: mysql_config: command not found', '    /bin/sh: mariadb_config: command not found', '    /bin/sh: mysql_config: command not found', '    Traceback (most recent call last):', '      File "<string>", line 1, in <module>', '      File "/private/var/folders/_f/_7x2949j4v50k7k6nq9yx0z40000gn/T/pip-install-ngc34ts9/mysqlclient/setup.py", line 15, in <module>', '        metadata, options = get_config()', '      File "/private/var/folders/_f/_7x2949j4v50k7k6nq9yx0z40000gn/T/pip-install-ngc34ts9/mysqlclient/setup_posix.py", line 65, in get_config', '        libs = mysql_config("libs")', '      File "/private/var/folders/_f/_7x2949j4v50k7k6nq9yx0z40000gn/T/pip-install-ngc34ts9/mysqlclient/setup_posix.py", line 31, in mysql_config', '        raise OSError("{} not found".format(_mysql_config_path))', '    OSError: mysql_config not found', '    ----------------------------------------', 'ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.']
ERROR: ERROR: Package installation failed...
  ☤  ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 0/1 — 00:00:00

안된다. 그래서 다시 방법을 찾아보기로 한다.

 

Homebrew 설치하기

brew.sh/index_ko

 

Homebrew

The Missing Package Manager for macOS (or Linux).

brew.sh

whitepaek.tistory.com/3

 

Homebrew(홈브류) 설치 및 사용법, MacOS에서 프로그램을 쉽게 다운로드 및 삭제할 수 있는 패키지 관

Homebrew 설치 및 사용법 macOS를 새롭게 구입 또는 클린 설치를 하고 나서 가장 먼저 설치하는 MacOS 용 패키지 관리자입니다! 많은 맥 유저분들이 아직 Homebrew를 터미널에서 사용하는 방식이 익숙하

whitepaek.tistory.com

여기서 엔터를 눌러주면 설치가 계속 진행된다. 설명을 잘 읽어보면 된다.

그러다가 나는 중간에 멈춰섰다.

Downloading Command Line Tools for Xcode

라는 문구에서 멈춘 것인데, 기다리다보니까 되었다.

긴 시간(10분?) 끝에 설치가 시작되었다. 중간의 ㅍ는 이것저것 눌러서 반응을 확인하다 보니 생긴 흔적

찾고보니 나같은 사람도 역시나 많았다.

discourse.brew.sh/t/stuck-at-downloading-command-line-tools-for-xcode/7311/5

 

Stuck at "Downloading Command Line Tools for Xcode"

Mine took a while, I thought it was stuck too, but finally it continued the installation. The problem is that there is no progress indicator while downloading the command line tools for Xcode. Just give it some minutes to complete the download or you can r

discourse.brew.sh

비밀번호 적으라면 적고 엔터 누르라면 누르고 그러면 설치 완료!

 

설치를 완료했다면, 먼저 아래의 명령어를 입력해주자.

brew install mysql

그다음 아래의 명령어로 OpenSSL을 설치해 준다.

brew install openssl

 

OpenSSL이란?

OpenSSL은 네트워크를 통한 데이터 통신에 쓰이는 프로토콜인 TLS와 SSL의 오픈 소스 구현판이다. C 언어로 작성되어 있는 중심 라이브러리 안에는, 기본적인 암호화 기능 및 여러 유틸리티 함수들이 구현되어 있다.
OpenSSL은 Eric A. Young과 Tim Hudson이 만든 SSLeay에 그 근거를 두고 있다. SSLeay의 개발은 Young과 Hudson이 RSA Security로 적을 옮긴 1998년 12월 이래 비공식적으로 중단되어 있다.
거의 모든 버전의 유닉스 계열 운영 체제(솔라리스, 맥 OS X, 리눅스, BSD 포함) 및 OpenVMS, 윈도우에서 OpenSSL을 이용할 수 있다.

설치가 완료된 후, 프로젝트 디렉터리로 이동 후 아래의 명령어로 mysqlclient를 설치해 준다.

LDFLAGS=-L/usr/local/opt/openssl/lib pip install mysqlclient

아까와는 다르게 설치가 제대로 완료되는 것을 볼 수 있다.

 

 

프로젝트 파일의 setting.py 파일 속 DATABASE 부분을 찾아 아래의 코드처럼 바꿔주자.

스키마 이름에 본인이 원하는 데이터베이스 스키마 이름을 적어주면 되고, 계정에 계정 ID, 계정 비밀번호에 계정의 비밀번호를 적어두면 된다. 만약 MySQL 설치 시 포트번호를 다르게 설정해 주었다면, PORT 항목을 변경해 주면 된다.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '스키마 이름',
        'USER': '계정',
        'PASSWORD': '계정 비밀번호',
        'HOST': 'localhost',
        'PORT': '3306',
        'OPTIONS': {
            'init_command': 'SET sql_mode="STRICT_TRANS_TABLES"'
        }
    }
}

이런 식으로 개발을 진행하게 되면, 버전 관리를 통해 해당 DataBase 스키마 이름과 계정 정보가 유출이 될 수 있다.

 

Window에서 설치 시 오류

이럴때는 윈도우 바이너리 를 다운로드 받아 pip3에 등록, 설치하면 된다.

 

www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient.Then

 

Python Extension Packages for Windows - Christoph Gohlke

by Christoph Gohlke, Laboratory for Fluorescence Dynamics, University of California, Irvine. Updated on 16 January 2021 at 01:59 UTC. This page provides 32- and 64-bit Windows binaries of many scientific open-source extension packages for the official CPyt

www.lfd.uci.edu

 

설치되어 있는 파이썬을 확인하여 다운로드를 받는다.

 

콘솔창을 열어 해당 파일이 있는 폴더로 접근한다.

 

그리고 pip3 install 을 이용해 설치한다.

 

pip3 install mysqlclient-1.3.13-cp37-cp37m-win_amd64.whl

 

반응형

관련글 더보기

댓글 영역