처음 장고를 만져보고 싶다고 생각한 것

10276 단어 파이썬장고

소개



Python의 경험이 거의 제로 상태에서,
뭔가 평판이 높은 장고이라는 웹 애플리케이션 개발 프레임 워크를 만져 보았습니다.

지금까지, Ruby on Rails, Nest.js, ASP.Net Core, Laravel 근처를 만진 적이 있기 때문에, 그들과 어쩐지 비교하면서, 개인적으로 좋다고 생각한 부분만 정리합니다.

만진 것



공식 튜토리얼 를 한번에 해 보았습니다.

튜토리얼 내용


  • Part 1: Requests and responses
  • Part 2: Models and the admin site
  • Part 3: Views and templates
  • Part 4: Forms and generic views
  • Part 5: Testing
  • Part 6: Static files
  • Part 7: Customizing the admin site
  • Advanced Tutorials: How to write reusable apps
  • Advanced Tutorials: Writing your first patch for Django

  • 튜토리얼을 마친 소스 코드



    좋다고 생각한 것



    CLI 명령이 풍부



    장고가 활성화 된 파이썬 가장 환경에서,
    python manage.py {コマンド名}
    

    에서 다양한 명령을 실행할 수 있습니다.

    유효한 명령의 예로,
  • runserver : 서버 시작
  • test : 테스트 실행
  • check : 소스 코드에 문제가 있는지 확인
  • shell : rails console와 같은 느낌으로, REPL 환경에서 django의 모델 등을 만지다
  • makemigration/migrate : 마이그레이션 관련
  • sqlmigrate : 마이그레이션이 실행될 SQL을 인쇄하고 확인할 수 있음
  • createsuperuser : 쉘상에서 인터랙티브하게 유저명·패스워드등을 입력하는 것으로 유저가 만들 수 있다. 초기 사용자 생성 등에 편리함


  • 외래 키로 관계 표현



    polls/models
    from django.db import models
    
    
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
    
    
    class Choice(models.Model):
        question = models.ForeignKey(Question, on_delete=models.CASCADE)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)
    

    이 예제에서는 Choice 모델에 외래 키로 question를 설정하여 이를 기반으로 관계를 만듭니다.
    외래 키 제약을 붙이는 것을 잊지 않아도 좋다고 생각했습니다.

    관리 화면



    이것이 개인적으로 1번 좋다고 생각했습니다.

    처음에는, 「블로그 서비스를 만드는 것도 아닌데 관리 화면은 필요 없어」정도로 생각하고 있었습니다만,



    위 그림과 같이, UI상에서 다양한 모델 인스턴스의 신규 작성·편집 등을 간단하게 실시할 수 있습니다.
    이 예제에서와 같이 Question has many Choices와 같은 관계 관계에서,Question 생성 화면에서 연결하기 Choice 인스턴스 생성도 동시에 생성할 수 있는 UI 사용자 지정이 매우 쉽고 훌륭했습니다.

    테스트가 쉽습니다.



    예를 들어 모델 테스트라면

    model_tests.py
    import datetime
    
    from django.test import TestCase
    from django.utils import timezone
    
    from .models import Question
    
    
    class QuestionModelTests(TestCase):
    
        def test_was_published_recently_with_future_question(self):
            """
            was_published_recently() returns False for questions whose pub_date
            is in the future.
            """
            time = timezone.now() + datetime.timedelta(days=30)
            future_question = Question(pub_date=time) # テスト用のモデルインスタンスの生成
            self.assertIs(future_question.was_published_recently(), False) # インスタンスのプロパティにアクセスしてアサーション
    

    View 테스트라면

    view_tests.py
    # テスト用のヘルパー関数
    def create_question(question_text, days):
        """
        Create a question with the given `question_text` and published the
        given number of `days` offset to now (negative for questions published
        in the past, positive for questions that have yet to be published).
        """
        time = timezone.now() + datetime.timedelta(days=days)
        return Question.objects.create(question_text=question_text, pub_date=time)
    
    
    class QuestionIndexViewTests(TestCase):
        def test_no_questions(self):
            """
            If no questions exist, an appropriate message is displayed.
            """
            response = self.client.get(reverse('polls:index')) # `/polls` にリクエストを投げる
            self.assertEqual(response.status_code, 200) # ステータスコードのチェック
            self.assertContains(response, "No polls are available.") # レンダーされたレスポンステキストのチェック
            self.assertQuerysetEqual(response.context['latest_question_list'], []) # コントローラーがテンプレートに渡している変数の中身のチェック
    

    어느 쪽이든 테스트를 실행할 때,
  • 테스트용 DB 생성
  • 각 테스트를 실행하기 전에 DB를 깨끗한 상태로 되돌리기
  • 각 테스트 실행

  • 라는 것을 자동으로 해줍니다.

    db cleaner적인 것을 자발적으로 구현해야 하는 프레임워크도 상당히 많기 때문에 이것은 꽤 좋은 인상이었습니다.

    요약



    「응? 이것은 어떨까?」라는 부분이 없었던 것도 아니기 때문에,
    그것도 정리할까라고 검토했습니다만, 이라고는 해도 실무로 아직 사용한 적이 없기 때문에 무지를 노출할 수 없고, 이 기사에서는 포지티브인 부분에만 머물렀습니다.

    튜토리얼의 소요 시간은 2시간 정도?이므로 흥미가 솟은 분은 꼭 해 봅시다!

    좋은 웹페이지 즐겨찾기