[Django Install] 3. Django Install and Project 생성

[Python 가상환경 설정]



[파이썬 mysqlclient Install - ubuntu 18.04]

workon virtual_name
가상화 환경에 들어간다.

pip install mysqlclient
(MySQL을 사용 시 설치 필요)

아래 에러가 나면 libmysqlclient-dev가 없기 때문이다.

sudo apt-get install libmysqlclient-dev
우분투에 libmysqlclient-dev를 설치한다.

pip install mysqlclient
Collecting mysqlclient
  Downloading https://files.pythonhosted.org/packages/d0/97/7326248ac8d5049968bf4ec708a5d3d4806e412a42e74160d7f266a3e03a/mysqlclient-1.4.6.tar.gz (85kB)
     |████████████████████████████████| 92kB 1.5MB/s 
    ERROR: Command errored out with exit status 1:
     command: /home/ubuntu/.virtualenvs/aipass/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-g7lp5qsx/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-g7lp5qsx/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 /tmp/pip-install-g7lp5qsx/mysqlclient/pip-egg-info
         cwd: /tmp/pip-install-g7lp5qsx/mysqlclient/
    Complete output (12 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-g7lp5qsx/mysqlclient/setup.py", line 16, in <module>
        metadata, options = get_config()
      File "/tmp/pip-install-g7lp5qsx/mysqlclient/setup_posix.py", line 61, in get_config
        libs = mysql_config("libs")
      File "/tmp/pip-install-g7lp5qsx/mysqlclient/setup_posix.py", line 29, in mysql_config
        raise EnvironmentError("%s not found" % (_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.

아래 에러가 나면 libssl-dev가 없기 때문이다.

sudo apt-get install libssl-dev
우분트에 libssl-dev를 설치한다. (20.04 LTS는 이미 설치되어져 있음)

    /usr/bin/ld: cannot find -lssl
    /usr/bin/ld: cannot find -lcrypto
    collect2: error: ld returned 1 exit status
    error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
    ----------------------------------------

ERROR: Command errored out with exit status 1: /home/ubuntu/.virtualenvs/aipass/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-fihia5em/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-fihia5em/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-2j5bnj14/install-record.txt --single-version-externally-managed --compile --install-headers /home/ubuntu/.virtualenvs/aipass/include/site/python3.6/mysqlclient Check the logs for full command output.


[파이썬 mysqlclient Install - Mac OS]



brew install mysql-client

~/.bash_profile 에 아래 내용 추가

# mysql-client is not on the `PATH` by default
export PATH="/usr/local/opt/mysql-client/bin:$PATH"
# openssl is not on the link path by default

export LIBRARY_PATH="$LIBRARY_PATH:/usr/local/opt/openssl/lib/"

workon virtual_name
가상화 환경에 들어간다.

pip install mysqlclient
(MySQL을 사용 시 설치 필요)


[Django Install]

pip install django
장고 설치

django-admin startproject projectname
장고 프로젝트 생성


project directory 구조


projectname/
    manage.py
    projectname/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py


[Visual Code simpleFTP Setting]

PC에 Visual Code를 설치한다. (사이트에서 설치 : https://code.visualstudio.com )

Visual Code의 Extensions에서 "ftp-simple"을 설치한다.



"FTP-simple"설치 후 "F1"를 눌러서 "ftp-simple : Config - FTP connection setting"을 선택한다.


아래의 내용처럼 추가하고 저장한다.

[
  {
        "name": "projectname",
        "host": "ec2-13-209-72-174.ap-northeast-2.compute.amazonaws.com",  # domain or IP
        "port": 22,
        "type": "sftp",
        "username": "ubuntu",
        "path": "/home/ubuntu/projectname", # 접속 디렉토리
        "autosave": true,
        "confirm": true,
        "privateKey": "/Users/iDongkil/dev/key/prefity2019.pem"  # 키페어 파일 (PC내 위치)

  }
]

다시 "F1"키를 눌러서 "ftp : Remote directory open to workspace"를 선택한다.



그리고 해당 프로젝트의 디렉토리를 선택하고 ". current directory"를 선택한다.
그러면 해당 디렉로리의 파일들이 PC에 저장되고 수정할 수 있게 된다.
파일들을 수정하고 저장하면 자동으로 서버에 저장된다.

aws Ubuntu 22.04 버전에서는 접속이 되지 않아 20.04나 18.04로 설치 필요.


[MySQL Install]

aws에서 rds 를 설치하거나, 서버에 Mysql을 설치한다.
version은 5.x 최신버전 설치

aws 설치 시 옵션에서 반드시 퍼블릭 접근을 ""로 한다.
Inbound 포트는 "3306"만 열어둔다.

수작업 사용자, 데이터베이스, 권한 설정

$ mysql -uroot -p (루트권한으로 접근)
mysql> use mysql;
mysql> create user [user명]@'%' identified by 'nadaimma';
mysql> create database [database명] default character set utf8;
mysql> grant all privileges on [database명].* to [사용자명]@'%';
mysql> flush privileges;


[mysql client Install]

mysql workbench를 설치하고 mysql에 접속한다.
mysql workbench에서 database를 확인한다.
접속이 되지 않는 경우, security group의 inbound에 3306 포트 허용 추가


[Django Settings]

vi projectname/projectname/settings.py
아래 내용으로 변경하기 (빨간색 변경/추가)


--- 아래 시작 ---

import os

ALLOWED_HOSTS = '*'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'projectname',
        'USER': 'admin',
        'PASSWORD': 'nadaimma',
        'HOST': 'aipass.clajxw7ifxvz.ap-northeast-2.rds.amazonaws.com',
        'PORT': '3306',
        'OPTIONS': {
            "init_command": "SET foreign_key_checks = 0;SET sql_mode='STRICT_TRANS_TABLES';",
        },
    }
}


# logging Settings

import logging.config
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    "formatters": {
        "basic": {
        "format": "%(asctime)s - %(module)s - [%(levelname)s] %(message)s",
        "datefmt": "%Y-%m-%d %H:%M:%S"
        }
    },
    "handlers": {
        "file_log": {
        "class": "logging.FileHandler",
        "level": "INFO",
        "formatter": "basic",
        "filename": "/home/ubuntu/projectname/logs/server.log"
        }
    },
    "loggers": {
        "django": {
        "level": "INFO",
        "handlers": ["file_log"],
        "propagate": False
        },
        "projectname": {
        "level": "INFO",
        "handlers": ["file_log"],
        "propagate": False
        }
    }
}

logging.config.dictConfig(LOGGING)

LANGUAGE_CODE='ko'
TIME_ZONE = 'Asia/Seoul'

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'staticfiles'),
)
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Redirect Settings

LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"

--- 아래 끝 ---

mkdir $HOME/project/log (로그 디렉토리를 생성한다)


view, model, form에서 log는 아래와 같이 활용

--- 아래 시작 ---

import logging 


logger = logging.getLogger('projectname')

logger.info('message')

--- 아래 끝 ---


[Django default schema 생성]

python manage.py migrate 
(django 기본 스키마 생성)

아래의 에러는 Django 3.x 버전에서는 settings.py의 Korean LANGUAGE_CODE='ko'로 변경됨 (3.0 이전 버전은 'ko-kr'임)

ERRORS:
?: (translation.E004) You have provided a value for the LANGUAGE_CODE setting that is not in the LANGUAGES setting.


[Django admin shell 생성]

vi $VIRTUAL_ENV/bin/postactivate

빨간 아래 내용 2줄 추가
export PRJ_HOME=/home/ubuntu/projectname
export PATH=$PATH:$PRJ_HOME/bin

source $VIRTUAL_ENV/bin/postactivate

mkdir /home/ubuntu/projectname/bin

cd $PRJ_HOME/bin

echo python $PRJ_HOME/manage.py makemigrations >> mk.sh

echo python $PRJ_HOME/manage.py migrate >> mg.sh

echo python $PRJ_HOME/manage.py showmigrations >> sh.sh

echo python $PRJ_HOME/manage.py shell >> shell.sh

echo python $PRJ_HOME/manage.py runserver 0.0.0.0:8080 >> run.sh

echo "nohup python $PRJ_HOME/manage.py runserver 0.0.0.0:8080 > $PRJ_HOME/logs/nohup_server.log &" >> server.sh

chmod 777 *.sh

run.sh (실행)
server.sh (백그라운드 실행)

브라우저에서 접속 테스트  : http://ip:8000 접속 (장고 화면 나오면)


[Django admin user 생성]

cd $PRJ_HOME
python manage.py createsuperuser
(관리자 id 생성)

Admin URL : http://ip:8000/admin
















댓글

이 블로그의 인기 게시물

[Django Install] 11. Install Python3 for Centos8/RedhatLinux8

[windows] filebeat 스케쥴링 테스트

[Django Install] 9.1 sc제일은행 nginx-django 연결