170305_TIL

|

오늘 한 일

  • 기초 튼튼 코드 튼튼 다 함께 프로그래밍 을 읽었다.
    프로그래밍의 절차는 1) 테마 정하기(핵심기능) 2) 줄거리 만들기(순서중요) 3) 시나리오 작성하기(구체적으로) 4) 프로그래밍 언어로 바꾸기 5) 움직여보기 6) 확인하기 7) 버전업 으로 나뉜다고 한다. 그 중에서 1,2,3번이 가장 중요한데, 미니프로젝트에 기능을 추가 할 때 적용해 봐야겠다고 생각했다.
  • 그림으로 배우는 HTTP & Network Basic을 읽었다.
    말로만 듣던 TCP/IP에 대해서 읽었는데 쉽게 잘 설명되어 있었다. 그래도 아직은 크게 공감이 가거나 분명하게 이해가 가지는 않는다.
  • 기초 알고리즘 문제를 풀었다.
    문제를 풀다보니 내장함수 기능을 더 알고 싶어서 점프투파이썬 내장함수 부분을 읽었다. 나중에 찾기 쉽게 구글독스에 정리하고 있는데 괜찮은것 같다.
  • django 강의를 들었다.
    에러 발생시 404 페이지 표시를 위해서 예외처리 (try-except)를 사용했는데, 오랜만에 다시 보는 코드라 예전에 작성한 글을 읽었더니 도움이 많이 된다. get_object_or_404()는 많이 사용된다고 하니, 장고 가이드 문서를 읽어야겠다.

내일 할 일

  • 장고강의 듣기
  • 점프투파이썬 읽기 (정규표현식, 튜플 자료형, 모듈)
  • 장고걸스 가이드 읽기

django 06. 두번째 장고앱 7 - 404 핸들링

|

django 06. 두번째 장고앱 7 - 404 핸들링

파이썬 웹 프로그래밍 - Django로 웹 서비스 개발하기

템플릿 파일 작성 - detail.html

  • 위치 : app2/polls/templates/polls/detail.html
  • detail.html 코드내용

{{ question }}

views.py 와 templates 의 detail.html 파일 연결

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from .models import Question

# url을 views 의 메소드들과 연결해주는 것 >> function based view
def detail(request, question_id):
    q = Question.objects.get(pk = question_id)
    return render(request, 'polls/detail.html', {'question' : q})

404 페이지 표시 - try-except 예외처리 사용

  • 에러가 날 경우에는 예외처리를 통해서 404 페이지를 표시하는 것이 좋다.
  • django.http의 Http404 함수를 import 한다.
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse, Http404
from .models import Question

def detail(request, question_id):
    # 예외처리
    try:
        q = Question.objects.get(pk = question_id) # 에러가 발생할지 모르는 코드
    except Question.DoesNotExist: #DoesNotExist 에러가 발행하면
        raise Http404("Question %s does not exist" % question_id)

    return render(request, 'polls/detail.html', {'question' : q})

404 페이지 표시 - shortcuts 사용

  • 예외처리를 통한 404 페이지 표시는 아주 많이 사용되는 기능이다.
  • 따라서 장고에서는 get_object_or_404 등의 통해 간단하게 기능을 구현할 수 있다.
  • get_list_or_404 함수도 있다. 관련문서
from django.shortcuts import render, get_object_or_404

# Create your views here.
from django.http import HttpResponse
from .models import Question

def detail(request, question_id):
    q = get_object_or_404(Question, pk = question_id)
    return render(request, 'polls/detail.html', {'question' : q})

django 06. 두번째 장고앱 6 - template 연동

|

django 06. 두번째 장고앱 6 - template 연동

파이썬 웹 프로그래밍 - Django로 웹 서비스 개발하기

templates 폴더 작성

  • 폴더위치 (앱폴더 내부) : app2/polls/templates/polls/index.html
  • index.html 작성

{% if latest_question_list %}
  <ul>
    {% for question in latest_question_list %}
    <li><a href="/polls/{{question.id}}">{{question.question_text}}</a></li>
    {% endfor %}
  </ul>
{% else %}
  <p>No polls are available.</p>
{% endif %}

views.py 와 templates 의 index.html 파일 연결

  • order_by를 통해서 오름차순, 내림차순으로 모델클래스를 가져올 수 있다.
  • dic 형식으로 models 클래스의 데이터를 index.html로 보내줄 수 있다.
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from .models import Question

def index(request):
    # 모델클래스 Question을 가져온다. (pub_date 내림차순으로)
    latest_question_list = Question.objects.order_by('-pub_date')[:3]
    return render(request, 'polls/index.html',{'latest_question_list' : latest_question_list})

django 06. 두번째 장고앱 5 - views.py 및 urls.py 수정 2

|

django 06. 두번째 장고앱 5 - views.py 및 urls.py 수정 2

파이썬 웹 프로그래밍 - Django로 웹 서비스 개발하기

urls.py 수정

  • 프로젝트 폴더의 urls.py 가 아닌, include 시킨 앱 폴더 내의 urls.py 를 수정한다.
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    # 숫자로 이루어진 question_id를 매개변수로 저장해서 views.py에 넘긴다
    url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
    url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

views.py 수정

  • function based view : url을 views의 메소드와 연결하는 것
  • 다음 시간에 class based view에 대해서 알아본다.
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse

def index(request):
    return HttpResponse('hello, siwa')

def detail(request, question_id):
    return HttpResponse("You're looking at question %s" % question_id)

def results(request, question_id): #question_id를 파라미터로 받는다.
    return HttpResponse("You're looking at the results of question %s" % question_id)

def vote(request, question_id):
    return HttpResponse("You're voting on question %s" % question_id)
views
url-views 연결 화면

level 1. x만큼 간격이 있는 n개의 숫자

|

level 1. x만큼 간격이 있는 n개의 숫자

출처

문제

number_generator함수는 x와 n을 입력 받습니다. 2와 5를 입력 받으면 2부터 시작해서 2씩 증가하는 숫자를 5개 가지는 리스트를 만들어서 리턴합니다. [2,4,6,8,10]

4와 3을 입력 받으면 4부터 시작해서 4씩 증가하는 숫자를 3개 가지는 리스트를 만들어서 리턴합니다. [4,8,12]

이를 일반화 하면 x부터 시작해서 x씩 증가하는 숫자를 n개 가지는 리스트를 리턴하도록 함수 number_generator를 완성하면 됩니다.

풀이 (python)

python

# 풀이 1
def number_generator(x, n):
    result = [x]
    for i in range(2, n+1):
        result.append(x * i)
    return result

# 풀이 2 - list comprehension 활용
def number_generator(x, n):
    return [x*i for i in range(1, n+1)]


# 풀이 3 - list() 함수 활용
def number_generator(x, n):
    return list(range(x, x*n+1, x))