Python script 에서 Django 환경 이용

in #programming7 years ago

Facebook TDD Django 스터디 그룹을 위해 작성된 글입니다.
교재 Test driven development with Python (번역서 : 파이선을 이용한 클린코드를 위한 테스트 주도 개발)
http://www.obeythetestinggoat.com/

Django App 내에서는 Django 환경을 모두 이용할 수 있습니다.
간혹 Django app 이 아니면서도 Django 모듈을 써야할 경우가 있습니다.
자동화 스크립트를 만들고 싶을 때 이러한 스크립트가 필요합니다.
이 스크립트의 요구조건은

  1. Virtual env 를 불러와서 가상환경을 가져와야 합니다.
  2. django.setup() 을 불러야 하고
  3. Django app 모듈을 자유롭게 불러와야 합니다.
  4. 이 스크립트는 실행위치에 따른 의존성이 없는 것이 좋습니다.
    (어떤 경로에 스크립트가 있어도 실행이 가능해야 한다는 의미입니다)

1번은 의외로 간단합니다.
가상환경의 python 실행 경로를 첫줄에 적어주면 됩니다.

2번은 os 환경변수설정을 하고 django.setup() 을 호출 합니다.
django.setup() 에서 상대경로를 인식할 수 있도록
sys.path 에 프로젝트 루트 경로를 추가합니다.
manage.py 가 하는 역할이 바로 ...

3번, 4번은 sys.path 에 경로 추가로 해결

아래 스크립트는 교재에 있는 Item list 를 모두 가져오는 스크립트입니다.
경로 위치는 각각 환경에 맞도록 수정해야겠지요?

#!/Users/agile/dev/tdd/vtdd/bin/python

import os
import sys

PROJECT_ROOT='/Users/agile/dev/tdd/tddjango/superlists/'
sys.path.append(os.path.dirname(PROJECT_ROOT))

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "superlists.settings")
import django
django.setup()

from lists.models import Item
for item in Item.objects.all():
    print(item.text)

Sort:  

This post has been ranked within the top 80 most undervalued posts in the first half of Feb 27. We estimate that this post is undervalued by $3.90 as compared to a scenario in which every voter had an equal say.

See the full rankings and details in The Daily Tribune: Feb 27 - Part I. You can also read about some of our methodology, data analysis and technical details in our initial post.

If you are the author and would prefer not to receive these comments, simply reply "Stop" to this comment.

Coin Marketplace

STEEM 0.18
TRX 0.13
JST 0.029
BTC 58522.98
ETH 3089.61
USDT 1.00
SBD 2.41