4. 데이터베이스
• 데이터베이스: 데이터의 조직화된 모음
• 데이터베이스 모델
• Hierarchical
• Relational
• Object
• ...
• DBMS(데이터베이스 관리 시스템)
• 사용자 또는 애플리케이션과 상호작용
• 데이터 정의·생성·질의·갱신, 관리
• MySQL, PostgreSQL, Microsoft SQL Server,
Oracle, Sybase, IBM DB2, ...
https://en.wikipedia.org/wiki/Database#/media/File:Database_models.jpghttps://en.wikipedia.org/wiki/Database
7. SQL 연습
• UPDATE employees
SET salary = 33000
WHERE employee_number = 1001;
• Write Changes / Revert Changes
(일반적인 RDBMS에서는 COMMIT / ROLLBACK 명령을 사용)
• SELECT *
FROM employees
WHERE employee_name LIKE 'Sally%'
• DELETE FROM employees
WHERE employee_number = 1001;
8. Python의 주요 데이터베이스 어댑터
• SQLite
• pysqlite2: Python 표준 라이브러리에 ‘sqlite3’라는 이름으로 포함
• PostgreSQL
• psycopg2 http://initd.org/psycopg/
• MySQL
• MySQLdb https://github.com/farcepest/MySQLdb1
• mysqlclient https://github.com/PyMySQL/mysqlclient-python
• MySQLdb의 fork, Python 3 지원 (Django와 함께 사용할 때에 추천)
• MySQL Connector/Python http://dev.mysql.com/downloads/connector/python
• Oracle의 순수 Python 드라이버
9. sqlite3 – SQLite3 데이터베이스 어댑터
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("CREATE TABLE stocks (date text, trans text, symbol text, qty real, price
real)")
c.execute("INSERT INTO stocks VALUES ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)")
conn.commit()
conn.close()
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("SELECT * FROM stocks WHERE symbol = 'RHAT'")
print(c.fetchone())
conn.close()
('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
https://docs.python.org/3/library/sqlite3.html
14. peewee – SELECT
>>> for p in Person.select():
... print(p.name, p.birthday)
...
Bob 1960-01-15
Grandma 1935-03-01
Herb 1950-05-05
15. peewee – SELECT ... WHERE ...
>>> bob = Person.select().where(Person.name == 'Bob').get()
>>> print(bob.birthday)
1960-01-15
>>> for p in Person.select().where(Person.name << ['Bob', 'Sam', 'Paul']):
... print(p.name)
...
Bob
>> herb = Person.get(Person.name == 'Herb')
>>> print(herb.is_relative)
False
16. peewee – SELECT ... ORDER BY
>>> for person in Person.select():
... print(person.name, person.is_relative)
...
Bob True
Grandma True
Herb False
>>> for person in Person.select().order_by(Person.birthday.desc()):
... print(person.name, person.birthday)
...
Bob 1960-01-15
Herb 1950-05-05
Grandma 1935-03-01
17. peewee – UPDATE
>>> gm = Person.select().where(Person.name == 'Grandma').get()
>>> gm.name = 'Grandma L.'
>>> gm.save()
1
>>> for p in Person.select():
... print(p.name, p.birthday)
...
Bob 1960-01-15
Grandma L. 1935-03-01
Herb 1950-05-05
18. peewee – DELETE
>>> h = Person.select().where(Person.is_relative != True).get()
>>> h.delete_instance()
1
>>> for p in Person.select():
... print(p.name)
...
Bob
Grandma L.
24. Base64
• ASCII
• 7 비트 (27 = 128)
• 95개의 출력 가능한 문자 + 32개의 특수 문자 + 1개의 공백 문자
• 모든 플랫폼이 ASCII를 지원하는 것은 아님
• 8 비트 이진 데이터
• 이미지, 실행 파일, 압축 파일, ...
• Base64
• 이진 데이터 64개의 문자로 이루어진 데이터
• 데이터를 안전하게 전송
http://kyejusung.com/2015/06/it-base64란/
25. base64
>>> s = b'Man distinguished, not only by his reason, but by this si
ngular passion from other animals, which is a lust of the mind, tha
t by a perseverance of delight in the continued and indefatigable g
eneration of knowledge, exceeds the short vehemence of any carnal p
leasure.'
>>> import base64
>>> base64.b64encode(s)
b'TWFuIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBie
SB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBp
cyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGV
saWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb2
4gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55I
GNhcm5hbCBwbGVhc3VyZS4='
29. xml.etree
>>> import xml.etree.ElementTree as et
>>> root = et.fromstring(r.content)
>>> root.tag
'rss'
>>> for child in root:
... print(child.tag, child.attrib)
...
channel {}
>>> channel = root[0]
>>> for item in channel.findall('item'):
... print(item.find('title').text)
...
Eyelike: Joy Williams, Neil Young + Promise of the Real, Pete Rock
Soybean master revives traditional flavors
Event Cinema Revenues to Hit $1 Billion by 2019, IHS Report Says
31. PyCharm
Professional Edition
• 모든 기능
• Django, Flask, Google App
Engine 등의 개발을 지원
• Javascript, CoffeeScript 등
Community Edition
• Python 개발 위주의 경량 IDE
• 오픈 소스
34. 대표적인 Python 웹 프레임워크
• Bottle
• 간결함. 저수준의 작업이 필요
• Flask
• 민첩함, 빠른 프로토타이핑
• 웹 애플리케이션 개발을 위해 여러 도구들을 조합하여 사용
(예: Flask + Jinja2 + SQLAlchemy)
• Pyramid
• 유연성, 최소화, 속도, 신뢰성
• 프로토타이핑, API 프로젝트
• Django
• 강력함, 많은 기능, 크고 활발한 커뮤니티
http://egloos.zum.com/mcchae/v/11064660
35. Django의 특징
• 자체 ORM, 템플릿 언어, 요청/응답 객체 내장
• 강력하고 자동화된 관리자 인터페이스
• 뛰어난 보안성(SQL 인젝션, 교차 사이트 스크립팅 방지 등)
• 다양한 기능
• 사용자층이 두텁고 문서화가 잘 되어있음
36. Django – Batteries Included
• Admin(관리자)
• 사용자 인증
• Cache
• 보안(Clickjacking 방지)
• 댓글
• 국제화
• 로깅
• 페이지네이션
37. Django – MVC or MTV
일반적인 용어 설명 Django에서의 구현
Model 애플리케이션 데이터 Model
View 사용자 인터페이스 요소
모델로부터 얻은 정보를 사용자에게 보여줌
Template
Controller 데이터와 비즈니스 로직의 상호동작을 관리
모델의 상태를 변경.
“View” 혹은 프레임워크 자체
• MVC(Model–View–Controller)
• 소프트웨어 아키텍처
• 사용자 인터페이스로부터 비즈니스 로직을 분리
• Django에서는 model, template, view를 통해 MVC를 구현
38. Django 버전
릴리스 시리즈 최종 릴리스 지원 종료* 연장 지원 종료**
1.8 LTS*** 1.8.3 2015.12 2018.4
1.7 1.7.9 2015.4.1 2015.12
1.6 1.6.11 2014.9.2 2015.4.1
1.5 1.5.12 2013.11.6 2014.9.2
1.4 LTS 1.4.21 2013.2.26 2015.10.1
1.3 1.3.7 2012.3.23 2013.2.26
* 보안 픽스, 데이터 손실 버그, 크래시 버그, 주요 신기능의 버그, 이전 버전 관련
** 보안 픽스, 데이터 손실 버그
*** LTS: Long Term Support Release
39. Django 커뮤니티, 개발 사례, 행사
• 페이스북 (한국) Django 그룹
https://www.facebook.com/groups/django
• DjangoCon
• 유럽 http://2015.djangocon.eu/
• 미국 https://2015.djangocon.us/
40. Django – 설치
• python.org 배포본 사용
• Anaconda 제거
• pip 및 python 경로를 찾지 못하는 경우 PATH 환경변수의 마지막에 다음을 추가
• Django 설치 및 확인
;C:Python34;C:Python34Scripts
> pip install django
> python
>>> import django
>>> django.get_version()
'1.8.3'
>>> exit()
41. Django – 프로젝트 생성
• 프로젝트 생성
• PyCharm – Open D:mysite
> D:
> cd
> django-admin startproject mysite
42. Django – 프로젝트 설정
• mysitemysitesettings.py
• DATABASES
• 디폴트: sqlite3 사용(파일명: db.sqlite3)
• PostgreSQL 등 다른 데이터베이스 사용 시
• 데이터베이스를 사용하기 위한 Python 드라이버 설치
• settings.py의 DATABASES 편집(사용자, 패스워드, 호스트 정보 포함)
• LANGUAGE_CODE = 'ko-kr'
• TIME_ZONE = 'KST'
43. Django – 서버 기동
• 개발 서버 기동
• 웹브라우저로 접속
• 개발 서버 정지: CONTROL-C
> d:
> cd mysite
> python manage.py runserver
Starting development server at http://127.0.0.1:8000/
44. Django – Hello, Django!
• New File: mysitemysiteviews.py
• mysitemysiteurls.py 편집
• runserver 및 http://127.0.0.1:8000/hello 접속
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello, Django!")
from django.conf.urls import include, url
from django.contrib import admin
from mysite.views import hello
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^hello', hello),
]
46. Django 단어장 – startapp, models.py
• 앱 생성
• 모델 작성 – D:mysitevocabularymodels.py 편집
from django.db import models
class Word(models.Model):
word = models.CharField(max_length=50)
def __str__(self):
return(self.word)
D:mysite> python manage.py startapp vocabulary
47. Django 단어장 – settings.py
• 프로젝트 설정
D:mysitemysitesettings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'vocabulary',
)
48. Django 단어장 – migrate, createsuperuse
• 데이터베이스 생성
D:mysite> python manage.py makemigrations
D:mysite> python manage.py migrate
• 관리자 계정 생성
D:mysite>python manage.py createsuperuser
49. Django 단어장 – admin.py
• Word 모델을 관리자 화면에서 볼 수 있도록 등록
• D:mysitevocabularyadmin.py 편집
from django.contrib import admin
from .models import Word
admin.site.register(Word)