티스토리 뷰

728x90

- C 언어와의 접착성

- 콜백 함수

- 람다 함수

- 이터레이터

- 제너레이터

 

인터프로터당 1개의 스레드만 허용하는 GIL(Global Interpreter Lock) 특성으로 인해 속도 측면에서 우려...

파이썬 토네이도(tornado) 프레임워크를 사용하여 웹 서버에 5개의 인스턴스를 띄우고, 동시 접속으로 10만개 이상의 요청 처리해 냄!

 

HTTP(S) 프로토콜

request

response

 

웹브라우저

curl http://www.example.com

telnet www.example.com  80

 

 

 

### HTTP 프로토콜

HTTP(Hypertext Transfer Protocol) 웹서버와 웹 클라이언트 사이에서 데이터를 주고받기 위해 사용하는 통신 방식으로,

TCP/IP 프로토콜 위에서 동작: IP 주소를 반드시 가져야 함

 

- 이미지

- 음성

- 동영상

- 자바스크립트

- PDF

 

Start Line: `request` or `status`

Header: 생략가능

Blank Line: 헤더의 끝을 빈줄로 식별

Body: 생략가능

 

CRLF(Carriage Return Line Feed)

헤더와 바디는 빈 줄로 구분

`text` or `binary`

 

GET http://www.example.com:8080?test=1234 HTTP/1.1
POST http://www.example.com:8080 HTTP/1.1

test=1234
HTTP/1.1 200 OK
Content-Type: application/xhtml+xml; charset=utf-8

<html>
...
</html>

 

URI: Uniform Resource Indentifier

URL: Uniform Resource Locator

URN: Uniform Resource Name

웹 프로그래밍에서는 `URI == URL` 동일의미로 사용해도 무방

 

GET 취득 Read
POST 생성, 추가 Create
PUT 변경 Update
DELETE 삭제 Delete
HEAD 메타데이터 취득  
OPTIONS 메소드 취득  
TRACE 루프백 시험  
CONNECT 프록시 동작의 터널 접속으로 변경  

 

Status Code

1xx Informational
2xx Success
3xx Redirection
4xx Client Error
5xx Server Error

 

RPC(Remote Procedure Call)

REST(Representational State Transfer)

 

정적: HTML, JS, CSS, image <- 웹 서버

- 캐시

- 프록시

- 인증제어 & 암호화

- HTTP(S) 제어

 

동적: 프로그래밍 코드 <- 웹 어플리케이션 서버

- Java: tomcat

- Python: uWSGI

 

CGI(Common Gateway Interface): 별도의 프로그램과 웹 서버 사이에 정보를 주고 받는 규칙을 정의

독립적인 별도의 프로세스

프로세스가 많아질수록 비례적으로 프로세스가 점유하는 메모리 요구량도 커짐

현재는 CGI 방식을 거의 사용하지 않음

 

WSGI(Web Server Gateway Interface): 웹서버에 내장 시켜서 오버헤드를 줄임

Apache(httpd): mod_wsgi

Nginx: uwsgi

별개의 어플리케이션 전용 데몬으로 동작한다는 점에서 웹 애플리케이션 서버임

동적 페이지를 처리하는 경우, 수 배에서, 수십 배의 메모리를 소비

L4/L7을 활용하여 웹 처리 용량을 높인다.

 

 

 

### Django 기본 개념

cd /usr/local/src
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py

pip3 install Django
pip3 install Django --upgrade

pyton -m django --version

python manage.py runserver

MVC(Model-View-Controller)

MVT(Model-View-Template)

 

ORM(Object-Relational Mapping): 객체관계 매핑

SQL 문장을 사용하지 않고도 테이블을 조작할 수 있음

 

자동으로 구성되는 Admin

콘텐츠 데이터베이스에 대한 관리 기능

 

우아한 URL 설계

Elegant URL

1:1 매핑

 

다국어 지원

날짜, 시간, 숫자 포맷

타임존의 지정 등과 같은 다국어 환경

 

풍부한 개발 환경

웹 서버가 없어도 테스트를 진행

에러를 쉽게 파악하고 해결할 수 있ㄷ로고 아주 상세한 메시지

 

자체 템플릿 시스템

캐시 시스템

소스 변경사항 자동 반영

django-admin startproject web
settings.py

urls.py
wsgi.py

models.py
views.py

admin.py
apps.py
ALLOWED_HOSTS = ['localhost', '127.0.0.1', '0.0.0.0']

INSTALLED_APPS = [
	...
    'web.apps.WebConfig'
]

DAABASES = {
	'default': {
    	'ENGINE': ...,
        'NAME': ...,
        'UESR': ...,
        'PASSWORD': ...,
        'HOST': ...,
        'PORT': ...
    }
}

TIME_ZONE = 'Asia/Seoul'
USE_TZ = True # autoset
python3 manage.py makemigrations
python3 manage.py migrate
python3 manage.py migrate -fake image # rename prefix class Meta db_table = "image"

python manage.py sqlmigrate image 0001



python3 manage.py runserver 0:8000

python3 manage.py runserver 0:8000 &
nohup python3 manage.py runserver 0:8000 > /dev/null 2>&1 &

python3 manage.py createsuperuser
python3 manage.py shell

 

### Table

# web/image/models.py

from django.db import models
from django.db.models import Q


class Image(models.Modexl):
    id = models.BigIntegerField(primary_key=True)

    type = models.CharField(max_length=20)
    url = models.CharField(max_length=255, unique=True)
    ref = models.CharField(max_length=255)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    is_display = models.CharField(max_length=1)

    class Meta:
        db_table = "image"

    @classmethod
    def gif(cls, start, display):
        return Image.objects\
                   .filter(type='image/gif') \
                   .exclude(Q(is_display='N')) \
                   .exclude(Q(url__contains='/thumb/'))\
                   .order_by('-id')[start:display]

- PK 는 자동으로 생성됨 (id)

# admin.py

from django.contrib import admin
from web.image.models import Image

admin.site.register(Image)

 

### pycharm import

- sys.path

- PYTHONPATH

 

### URLconf

- 모듈을 계층적으로 구성하는 것이 변경도 쉬워지고, 확장도 용이함

- `app_name` 변수는 URL 패턴의 이름이 충돌나느 것을 방지하기 위한 이름공간 (namespace) 역할을 함

# web/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
	path('admin/', admin.site.urls),
    path('image/', include('image.urls'))
]



# web/image/urls.py
from django.urls import path
from . import views

app_name = 'image'
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:id>/', views.image, name='image'),
    path('<int:id>_file', views.file, name='file'),
]

 

### Admin

- 룩앤필(look and fill): 기본적인 CRUD 제공

- http://0.0.0.0:8000/admin

# web/image/admin.py

from django.contrib import admin
from image.models import Image


class ImageAdmin(admin.ModelAdmin):
    fieldsets = [
        (None, {
            'fields': [
                'id',
                'type',
                'is_display'
            ]
        }),
        ('link', {
            'fields': [
                'url',
                'ref'
            ],
            'classes': ['collapse']
        })
    ]
    list_display = ('id', 'type', 'is_display', 'url', 'ref')
    list_filter = ['type', 'is_display']
    search_fields = ['url', 'ref']

admin.site.register(Image, ImageAdmin)

 

### Query

Image.objects.get(id=1)

Image.objects.all()[:5]
Image.objects.all()[5:10]
Image.objects.all()[:10:2]

Image.filter(id=1).udpate(url='http://seunggabi.com')
Image.filter(is_display='N').delete()

 

 

### Template

- UI(User Interface)

- 변수 값으로 출력

- https://docs.djangoproject.com/en/2.1/ref/templates/builtins

{{ variable }}
{{ name|lower }}
{{ text|escape|linebreaks }}
{{ bio|truncatewords:30 }}
{{ list|join:" // " }}
{{ value|default:"nothing" }}
{{ value|length }}
{{ value|striptags }}
{{ value|pluralize }}
{{ value|pluralize:"es" }}
{{ value|pluralize:"ies" }}
{{ value|add:"2" }}
{{ first|add:second }}

 

### {% for %}

- forloop.counter

- forloop.counter0

- forloop.revcounter

- forloop.revcounter0

- forloop.firtst

- forloop.last

- forloop.parentloop

- forloop.parentloop.counter

 

### {% if %}

- if

- elif

- else

- endif

 

### {% if %}

- if

- elif

- else

- endif

 

### {% csrf_token %}

- CSRF(Cross Site Request Forgery) 

<form action="." method="post">{% csrf_token %}

 

### {% csrf_token %}

- CSRF(Cross Site Request Forgery) 

 

### {% url 'namespace:view-name' arg1 arg2 %}

 

### {% with %}

- 큰 동작의 결과를 저장해 둠으로써, 다시 동일한 동작이 필요한 경우에는 저장해 둔 결과를 활용하여 부하를 줄이기 위함

{% with total=business.employees.count %}
	{{ total }} people works at business
{% endwith %}

### {% load %}

- 사용자 정의 태그 & 필터 로딩 

 

### HTML escape

- XSS(Cross-Site Scripting)

- 입력받은 값을 제대로 검사하지 않고 사용할 경우

- {{ data|safe }}

{% autoescape off %}
Hello {{ name }}
{% endautoescape %}

{{ data|default:"3 < 5" }}
{{ data|default:"3 &lt; 5" }}

 

### LOG

# setting.py
LOGGING_CONFIG = 'logging.config.dictConfig'
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s',
            'datefmt': '%d/%b/%Y %H:%M:%S'
        }
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': os.path.join(BASE_DIR, 'logs', 'umzzal-kim.log'),
            'formatter': 'verbose'
        },
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG'
        },
        'logger': {
            'handlers': ['console'],
            'level': 'INFO'
        }
    }
}


# views.py
logger = logging.getLogger('logger')


def index(request):
    logger.error('redirect!!')
    return redirect('/image/')

 

728x90
댓글