'프로그래밍/Python'에 해당되는 글 10건

  • 2018.09.19 django + gunicorn + nginx 구축1
  • 2017.12.21 heroku에 django 앱배포하기1
  • 2017.09.27 Django에서 manage.py shell 사용 않고 모델 사용해서 스크립트 작성 할 때
  • 2016.09.02 django + celery + rabbitmq 사용해보자!!!
  • 2016.06.01 Django ForeignKey로 연결된 모델의 필드로 필터할 때 참조
  • 2015.12.09 Django 데이터 마이그레이션
  • 2015.07.22 django 웹 어플리케이션 쉽게 백그라운드로 돌리기
  • 2015.05.29 Django + Apache 쉬운 연동방법!!! How to use Django with Apache and mod_wsgi
  • 2015.05.29 django STATIC_ROOT 설정
  • 2015.05.28 python3.x 에서 django database를 mysql로 사용 할 때 선행 되어야 할것들

django 2.1 버전

python 3.6.x


로컬에서

django 프로젝트를 pycharm을 사용해서


만들어주고


git 사용해서 버전관리


python3 manage.py startapp app이름


해서 앱 만들어주고 settings.py에 추가


settings.py에

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')


추가


gunicorn 설치

pip install gunicorn


gunicorn 설치 후 서비스에 등록해주기

/etc/systemd/system에

gunicorn.service 만들기


[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=root
Group=root
WorkingDirectory=프로젝트루트
ExecStart=/usr/local/bin/gunicorn \
--workers 7 \
--bind unix:/프로젝트루트/프로젝트명.sock \

프로젝트명.wsgi:application

[Install]
WantedBy=multi-user.target


User, Group은 사용할 계정과 그룹으로 지정하고

WorkingDirectory는 프로젝트루트로


django 사용해 보신분들은 이해하실듯

프로젝트루트밑에 프로젝트명으로 폴더 하나더있는데 프로젝트루트 경로로 해야함

bind 시킬 위치는 저 위치로 안해도 상관없음 나중에 nginx에서 경로 잘 설정해주면 됨

wsgi.py가 있는 프로젝트명폴더가 abc면

abc.wsgi:application으로 해야함


통상 워커 수는

1 + 2 * 코어수


위와 같이 만든 후


sudo systemctl enable gunicorn 하면

스크립트에 설정된 multi-user.taget 디렉토리에

심볼릭링크가 걸림


링크 만들어지는거 확인하고

sudo systemctl start gunicorn

sudo systemctl status gunicorn 해서

active 상태인지 확인하기


active 상태이면

nginx 설정


/etc/nginx/site-available에서

설정 하나 만든 후 /etc/nginx/site-enabled에 ln -s로 심볼릭링크걸기


서버 블락 밑에

location /static {

          alias /static폴더 경로;

}


location / {

          include proxy_params;

          proxy_pass http://unix:bind시킨소켓경로

}


static 경로는 위에 settings.py에서 설정한 경로이고

static 폴더를 생성 하려면 python3 manage.py collectstatic 해주면 자동으로 생성됨


간혹 static 폴더를 찾을 수 없다하는데

설정이 제대로 되어있는지 확인하기


location /static/ 이렇게 스면 안되고 /static으로

root 로 static 경로를 지정해주는 경우가 있는데 alias로

static 폴더 퍼미션 확인하기


// 그 외
pycharm을 사용 할 경우
상단 메뉴중에
File -> Settings -> Project Interpreter에서 원격으로 쉽게 패키지 추가 할 수 있음

코드를 수정하고 git pull로 배포 한 후

sudo systemctl restart gunicorn을 해야 반영이 됨


Posted by ㅇ_ㅎ
현재 브라우저에서는 댓글을 표시할 수 없습니다.
IE9 이상으로 브라우저를 업그레이드하거나, 크롬, 파이어폭스 등 최신 브라우저를 이용해주세요.

파이챰에서 프로젝트 생성

Django -> More Setting에서 앱도 하나 만들기



메뉴 Settings -> Project Interpreter에서 pip에서 패키지들 추가


djangorestframework

django-rest-swagger

django-debug-toolbar


패키지추가 하고


프로젝트에 settings.py에서

모든 호스트를 허용하고

ALLOWED_HOSTS = ['*']


INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Portfolio.apps.PortfolioConfig',
'rest_framework',
'rest_framework_swagger',
'debug_toolbar',
]

rest_framework랑 rest_framework_swagger, debug_toolbar 추가


///

static 파일 관련해서 한번 읽어보기

https://devcenter.heroku.com/articles/django-assets


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

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

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, 'static'),
]

# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'


MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
]


디버그 툴바 셋팅

# Debug ToolBar
DEBUG_TOOLBAR_PANELS = [
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.sql.SQLPanel',
'debug_toolbar.panels.staticfiles.StaticFilesPanel',
'debug_toolbar.panels.templates.TemplatesPanel',
'debug_toolbar.panels.cache.CachePanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
'debug_toolbar.panels.redirects.RedirectsPanel',
]

def show_toolbar(request):
return True


DEBUG_TOOLBAR_CONFIG = {
"SHOW_TOOLBAR_CALLBACK": show_toolbar,
}


urls.py에서


from django.conf.urls import url, include
from django.contrib import admin
from rest_framework_swagger.views import get_swagger_view

from DjangoProject import settings
from Portfolio.apis import TestAPI

schema_view = get_swagger_view(title='API')

urlpatterns = [
url(r'^$', schema_view),
url(r'^test$', TestAPI.as_view()),
url(r'^admin/', admin.site.urls),
]

if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns

TestAPI 클래스 하나 만들어서

테스트 해보기


runserver 해서 로컬에서 돌려보고


이제 로컬 준비 끝났으면


-------------- 헤로쿠에 올려야함!! ------------


쉘에서 헤로쿠 로그인

heroku login


아이디 / 비번 입력 후


쟝고 프로젝트 루트에서 깃 초기화

git init


쟝고 프로젝트 루트에 아래 3개 파일을 만들어야함

Procfile

web: gunicorn 프로젝트명.wsgi


pip freeze > requirements.txt

requirements.txt (사용하는 패키지들 모두 적기... 의존하는 패키지들인거 같은데 따로 확인 안해봄..)

Django==1.11.1
Jinja2==2.10
MarkupSafe==1.0
certifi==2017.11.5
chardet==3.0.4
coreapi==2.3.3
coreschema==0.0.4
dj-database-url==0.4.1
django-debug-toolbar==1.9.1
django-rest-swagger==2.1.2
djangorestframework==3.7.7
gunicorn==19.6.0
idna==2.6
itypes==1.1.0
openapi-codec==1.3.2
psycopg2==2.6.2
pytz==2017.3
requests==2.18.4
simplejson==3.13.2
sqlparse==0.2.4
uritemplate==3.0.0
urllib3==1.22
whitenoise==3.2



runtime.txt

python-3.6.3



모든 소스 add 시킨 후

git add -A


커밋

git commit -m "init"


헤로쿠 앱 만들기

heroku apps:create 앱이름 (이미 사용중인 이름은 만들수가 없음!!!!)



헤로쿠에 푸쉬

git push heroku master


푸쉬중에

 Error while running '$ python manage.py collectstatic --noinput'.

remote:        See traceback above for details.

remote:

remote:        You may need to update application code to resolve this error.

remote:        Or, you can disable collectstatic for this application:

remote:

remote:           $ heroku config:set DISABLE_COLLECTSTATIC=1

remote:

remote:        https://devcenter.heroku.com/articles/django-assets

remote:  !     Push rejected, failed to compile Python app.

remote:

remote:  !     Push failed


위와 같이 메시지가 뜨면


heroku config:set DISABLE_COLLECTSTATIC=1


한 후 다시 git push heroku master


Verifying deploy... done. 이 뜨면


heroku config:unset DISABLE_COLLECTSTATIC


한 후


heroku run python manage.py collectstatic



heroku ps로 돌아가는지 확인


heroku open으로 앱 잘 돌아가는지 확인


스케일을 늘리거나 줄여서 앱 구동 / 정지

heroku ps:scale web=1

heroku ps:scale web=0



마이그레이트를 해야하는 경우

heroku run python manage.py migrate 해주기


쉘에 접속해서 테스트 해봐야 하는 경우

heroku run python manage.py shell




* Cannot run more than 1 Free size dynos 라고 뜨는 경우

heroku ps

실행중인 프로세스 넘버 확인 후

heroku ps:stop run.프로세스넘버


* dyno 시간 확인


남은 할당량 확인

heroku ps -a 앱이름








Posted by ㅇ_ㅎ
현재 브라우저에서는 댓글을 표시할 수 없습니다.
IE9 이상으로 브라우저를 업그레이드하거나, 크롬, 파이어폭스 등 최신 브라우저를 이용해주세요.

manage.py와 같은 위치에 스크립트 작성


예를 들어 example.py을 만들고


import os
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "프로젝트 명.settings")
django.setup()

한 후


from 앱명.models import 모델 클래스


import 해주고~


모델 사용~


queryset = 모델 클래스.objects.all()


Posted by ㅇ_ㅎ
현재 브라우저에서는 댓글을 표시할 수 없습니다.
IE9 이상으로 브라우저를 업그레이드하거나, 크롬, 파이어폭스 등 최신 브라우저를 이용해주세요.

* 작업환경

django 버전 : 1.10.1

celery : 3.1.23


celery, rabbitmq 설치 방법은 워낙 많이 있어서 생략하겠음...



1. 쟝고 프로젝트를 만든 후

(SampleProject로 부르겠음)


SampleProject 폴더 하위에


다음 두 파일을 생성

 - celery.py


from __future__ import absolute_import

from celery import Celery

app = Celery('SampleProject',
broker='amqp://',
backend='amqp://guest:guest@localhost:5672//',
include=['SampleProject.tasks'])

 - tasks.py


from __future__ import absolute_import

from SampleProject.celery import app


@app.task
def add(x, y):
return x + y


@app.task
def mul(x, y):
return x * y


@app.task
def xsum(numbers):
return sum(numbers)

만든 후


2. celery worker 서버 구동!

shell 에서 


$ celery -A SampleProject worker --loglevel=info 로 서버로 구동


위 명령어를 입력했는데  서버가 제대로 동작을 하지 않는 경우가 있음



-------------- celery@juju-pjdc-lcy02-machine-4 v3.1.6 (Cipater)
---- **** -----
--- * *** * -- Linux-3.13.0-32-generic-x86_64-with-Ubuntu-14.04-trusty
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> broker: amqp://guest@localhost:5672//
- ** ---------- .> app: ~~~
- ** ---------- .> concurrency: 1 (prefork)
- *** --- * --- .> events: OFF (enable -E to monitor this worker)
-- ******* ----
--- ***** ----- [queues]
 -------------- .> celery exchange=celery(direct) key=celery

Segmentation fault (core dumped)

위 처럼 뜨는 경우가 있는데


sudo apt-get remove python-librabbitmq 한 후

sudo pip install librabbitmq 하면 해결!!

여기 참조했음

https://bugs.launchpad.net/ubuntu/+source/python-librabbitmq/+bug/1353269


3. 서버 실행 잘 됐으면

shell 창 하나 더 열어서

python3 manage.py shell

from SampleProject.tasks import *

add.delay(4,4) 해보면

worker서버 창에

[2016-09-02 08:54:41,147: INFO/MainProcess] Received task: SampleProject.tasks.add[50ad03b8-8c1f-41d2-aeac-c4f575da499f]

[2016-09-02 08:54:41,154: INFO/MainProcess] Task SampleProject.tasks.add[50ad03b8-8c1f-41d2-aeac-c4f575da499f] succeeded in 0.00638406700091s: 8


위와 같이 잘 뜨면 성공!!!



Posted by ㅇ_ㅎ
현재 브라우저에서는 댓글을 표시할 수 없습니다.
IE9 이상으로 브라우저를 업그레이드하거나, 크롬, 파이어폭스 등 최신 브라우저를 이용해주세요.

Django ForeignKey로 연결된 모델의 필드로 필터할 때 참조


모델.objects.filter(관련된모델__필드__contains="패턴")


Posted by ㅇ_ㅎ
현재 브라우저에서는 댓글을 표시할 수 없습니다.
IE9 이상으로 브라우저를 업그레이드하거나, 크롬, 파이어폭스 등 최신 브라우저를 이용해주세요.

앱에서 모델을 수정한 후 디비에 반영 할 때 참조


1. 마이그레이션 파일을 만듦

python3 manage.py makemigrations 특정앱


2. 마이그레이트!~

python3 manage.py migrate --database=디비이름


* 디비이름을 지정하지 않을 경우 settings.py에서 디폴트로 지정한 디비에 적용되는 듯??


* 특정 마이그레이션을 건너 뛰려면

python3 manage.py migrate --database=디비이름 --fake


결과를 확인 하려면 디비에서 migration 테이블을 확인 한 후 

건너 뛴 마이그레이션 정보들이 잘 들어가있는지 확인!!




Posted by ㅇ_ㅎ
현재 브라우저에서는 댓글을 표시할 수 없습니다.
IE9 이상으로 브라우저를 업그레이드하거나, 크롬, 파이어폭스 등 최신 브라우저를 이용해주세요.

작업 환경

우분투 , python 3.x


& 붙여도 백그라운드에서 안 돌길래...


screen

python3 manage.py runserver

screen -d




Posted by ㅇ_ㅎ
현재 브라우저에서는 댓글을 표시할 수 없습니다.
IE9 이상으로 브라우저를 업그레이드하거나, 크롬, 파이어폭스 등 최신 브라우저를 이용해주세요.

Django로 개발한 웹어플리케이션을 쉽게 아파치로 돌리는 방법

테스트환경 : ubuntu, python3.x, django1.8.x


먼저

apache2를 설치하고

  • apache2-mpm-prefork
  • apache2-prefork-dev
위 두개도 설치

설치 한 후

pip install mod_wsgi

로 파이썬 패키지 추가하고


settings.py에서 

앱을 추가

INSTALLED_APPS = (
    ...
    'mod_wsgi.server',
)


끝으로

shell에서

python3 manage.py collectstatic
python3 manage.py runmodwsgi

명령을 실행하면 8000 포트로 웹서비스가 돌아감

출처

https://github.com/GrahamDumpleton/mod_wsgi

Posted by ㅇ_ㅎ
현재 브라우저에서는 댓글을 표시할 수 없습니다.
IE9 이상으로 브라우저를 업그레이드하거나, 크롬, 파이어폭스 등 최신 브라우저를 이용해주세요.
STATIC_ROOT = os.path.join(BASE_DIR, 'static')


Posted by ㅇ_ㅎ
현재 브라우저에서는 댓글을 표시할 수 없습니다.
IE9 이상으로 브라우저를 업그레이드하거나, 크롬, 파이어폭스 등 최신 브라우저를 이용해주세요.

django에서 디비를 mysql로 설정 할 경우

python3.x 환경에서는 

MySQLdb 임포트 에러를 뿜어내는데


윈도우 환경에서는


pip install mysqlclient


우분투/ 데비안 환경에서

sudo apt-get install python-dev libmysqlclient-dev 

설치 한 후

pip install mysqlclient


문제 해결~!





Posted by ㅇ_ㅎ
현재 브라우저에서는 댓글을 표시할 수 없습니다.
IE9 이상으로 브라우저를 업그레이드하거나, 크롬, 파이어폭스 등 최신 브라우저를 이용해주세요.