StringBuilder 이슈

import time


BIG_NUM = 1000000

def time_measurement(func):
    def wrap(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        diff = time.time() - start
        print(diff)
        return result


@time_measurement
def func_loop():
    char = ''
    for i in range(BIG_NUM):
        char += 'a'
    return char

@time_measurement
def func_list():
    l = []
    for i in range(BIG_NUM):
        l.append('a')
    return ''.join(l)


@time_measurement
def func_list_compre():
    return ''.join(['a' for i in range(BIG_NUM)])


@time_measurement
def func_multi():
    return 'a' * BIG_NUM

인스타그램 프로젝트

1. post 뷰 생성

Post List를 보여주는 화면을 구성

1. View에 post_list 함수 작성
2. Template에 post_list.html 파일 작성
3. View에서 post_list.html을 render한 결과를 리턴하도록 함
4. instagram/urls.py에 post/urls.py를 연결시킴 (app_name은 post)
5. '/post/'로 접속했을 때, post_list View에 연결되도록 post/urls.py에 내용을 작성
6. 전체 Post를 가져오는 쿼리셋을 context로 넘기도록 post_list뷰에 구현
7. post_list.html에서 {% for %}{% endfor %}** 태그를 사용해 post_list의 내용을 순회하며 표현
8. post_list.html에서 전달받은 object를 사용해 comment 목록을 추가

2. 파일 업로드

ImageField로 사용하기 위해 몇 가지 설정이 필요하다.

  • setting 파일에 업로드된 파일을 저장할 디렉토리 full path로 MEDIA_ROOT를 정의한다.
  • (성능 향상을 위해 파일은 데이터 베이스에 저장되지 않는다.)
  • 디렉토리의 기본 공개 URL로 MEDIA_URL을 정의한다.
  • 모델의 ImageFieldupload_to옵션을 정의한다. upload_to 옵션은 MEDIA_ROOT의 하위디렉토리를 지정한다.
  • 템플릿에서 ``을 사용하려면, TEMPLATEScontext_processorsdjango.template.context_processors.media를 추가한다.
기본동작 : client > URL click > request > urls.py > 해당 view
미디어 URL : client > 미디어 URLL click > request > MEDIA_ROOT 폴더

urls.py를 거치지 않고 MEDIA_ROOT로 이동한다.
# instagram/settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            TEMPLATES_DIR
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            # 이 곳에 등록된 메서드들은 템플릿이 렌더링 될 때,
            # 기본적으로 포함하여 렌더링하게 된다.
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                # MEDIA_URL을 템플릿에서 사용하기 위함
                # External Libraries/site-packages/django/template/context_processors.py
                'django.template.context_processors.media',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

MEDIA_URL = '/media/'
<img src=""><br>

개발환경에서도 정상적으로 이미지 파일 경로가 동작하려면 설정이 필요하다. Serving files uploaded by a user during development

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(
    settings.MEDIA_URL,
    document_root=settings.MEDIA_ROOT
)

3. 포스트 상세보기 기능 구현

Post Detail (하나의 Post에 대한 상세화면) 구성

1. View에 post_detail 함수 작성
2~4. 위와 같음
5. '/post/<숫자>/'로 접속했을 때 post_detail View에 연결되도록 post/urls.py에 내용 작성
이 때, post_id 라는 패턴명을 가지도록 정규표현식 작성
6. url인자로 전달받은 post_id에 해당하는 Post객체를 context에 넘겨 post_detail 화면을 구성

4. 댓글 달기

Post Detail에 댓글 작성기능 추가

1. request.method에 따라 로직 분리되도록 if/else 블록 추가
2. request.method가 POST일 경우, request.POST에서 'content' 키의 값을 가져옴
3. 현재 로그인한 유저는 request.user로 가져오며 Post의 id값은 post_id 인자로 전달되므로 두 내용을 사용
4. 위 내용들과 content를 사용해서 Comment 객체 생성 및 저장
5. 다시 아까 페이지 (Post Detail)로 redirect