본문 바로가기

Develop

장고로 프로젝트 시작할 때 내가 설치하는 필수 패키지

흥미유발 할 수 있는 자료

들어가며

미묘하지만 django와 같은 web framework 으로 개발하는 과정과 부모 클래스를 상속받아 클래스를 재정의하는 과정이 다르지 않습니다. django를 이용해 손쉽게 몇 줄의 코드만 추가하면 로그인 기능이 살아나고, 또 몇줄의 설정을 추가하면 rest api 기능이 작동하는 프로젝트를 얻을 수 있습니다. 부모 클래스의 속성값을 변경하거나 method를 재정의하는 과정과 같다고도 볼 수 있습니다.

웹서비스 개발에 필요한 왠만한 문제들을 손쉽게 해결하기 위해 django가 나타났습니다. 시간이 흐르고 덩치가 흐르다 보니 django의 기능 자체를 배우고 활용하는 과정이 예전과 달리 더 어렵고 아득해 보입니다.

그래서 나타났습니다. django-extensions는 django를 더 쉽고 넓게 사용하는데 아주 유용한 툴이라고 생각해서 여러분께 공유하고자 합니다. django extensions도 코드가 성숙하면서 많은 기능들이 포함되어 왔는데요, 그 중에서 세가지만 소개드리겠습니다. 여러분 필요에 따라 다양한 sub command를 시도해 보시기 바랍니다.

Django Extensions is a collection of custom extensions for the Django Framework.

설치

$ pip install django-extensions

실행예

$ python manage.py 

[django_extensions]
    admin_generator
    clean_pyc
    clear_cache
    compile_pyc
    create_command
    create_jobs
    create_template_tags
    delete_squashed_migrations
    describe_form
    drop_test_database
    dumpscript
    export_emails
    find_template
    generate_password
    generate_secret_key
    graph_models
    mail_debug
    merge_model_instances
    notes
    passwd
    pipchecker
    print_settings
    print_user_for_session
    reset_db
    reset_schema
    runjob
    runjobs
    runprofileserver
    runscript
    runserver_plus
    set_default_site
    set_fake_emails
    set_fake_passwords
    shell_plus
    show_template_tags
    show_templatetags
    show_urls
    sqlcreate
    sqldiff
    sqldsn
    sync_s3
    syncdata
    unreferenced_files
    update_permissions
    validate_templates

추천 명령어 3개

shell_plus

Django shell with autoloading of the apps database models and subclasses of user-defined classes.

장고에서 제공하는 shell의 향상된 버전입니다. custom models에서 추가적인 import 없이 사용할 수 있고, tab 키를 이용한 자동 완성 기능도 훌륭합니다.

$ python manage.py shell_plus --ipython

# Shell Plus Model Imports
from actstream.models import Action, Follow
from admin_interface.models import Theme
from allauth.account.models import EmailAddress, EmailConfirmation

# Shell Plus Django Imports
from django.core.cache import cache
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import transaction
from django.db.models import Avg, Case, Count, F, Max, Min, Prefetch, Q, Sum, When, Exists, OuterRef, Subquery
from django.utils import timezone
from django.urls import reverse

Python 3.7.5 (default, Feb 26 2020, 16:28:00) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.12.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]:                                                             

create_command

Creates a command extension directory structure within the specified application. This makes it easy to get started with adding a command extension to your application.

커스텀 명령어 작업을 쉽게 시작하기 위한 템플릿을 제공합니다.

$ python manage.py create_command your_app

$ cat your_app/management/commands/sample.py 

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = "My shiny new management command."

    def add_arguments(self, parser):
        parser.add_argument('sample', nargs='+')

    def handle(self, *args, **options):
        raise N

graph_models

Creates a GraphViz dot file. You need to send this output to a file yourself. Great for graphing your models. Pass multiple application names to combine all the models into a single dot file.

진행 중이던 django 프로젝트에 참여하게 되었을 때, 그 프로젝트를 가장 빨리 이해하는 방법은 models.py를 파악하는 것입니다. 대부분의 로직들이 models에서 관리되기 때문입니다. 코드를 단순히 읽는 것보다도 graph로 각 모델 간의 관계를 그림으로 표현해 준다면 더욱 쉽게 이해를 할 수 있을 텐데요. 이 기능을 위해서는 필수라고 생각합니다.

$ python manage.py graph_models your_app your_model -o /tmp/models.png

맺음말

이상으로 django-extensions 에서 유용한 명령어 세 가지, shell_plus, create_command, graph_models 를 살펴보았습니다. 이 기능을 활용해서 작업 완성하는 시간이 상단히 단축되었고, 특히 graph_models에서 나온 결과물은 새로운 시스템을 짧은 시간에 이해하는 데 아주 큰 도움이 되었습니다. 이 외에도 show_urls 와 같이 이 글에서 포함하지 않았지만 재밌는 기능들이 많으니 경험해 보기를 적극 추천합니다.
제가 언급하지는 않았지만, 여러분들이 생각하시는 유용한 기능을 댓글에 알려주세요. 저도 적극 활용해 보겠습니다.
Django 잘 써서 칼퇴근 합시다.

참고

 

https://youtu.be/sZdEH-qwZZ8 

 

반응형