SlideShare a Scribd company logo
파이썬 웹 프로그래밍
정보기술 시대에 유익한 파이썬 프로그래밍 – 제 9 강
동양미래대학교
2015.7
최용 <sk8er.choi@gmail.com>
주제
• 데이터베이스와 Python
• Python 인터넷 라이브러리
• PyCharm – Python 개발 도구
• Django 웹 프레임워크
데이터베이스와 Python
데이터베이스
• 데이터베이스: 데이터의 조직화된 모음
• 데이터베이스 모델
• 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
SQLite
• https://www.sqlite.org/
• 작고 단순한 DBMS
• 임베디드, 중소규모 웹사이트, 데이터 분석, 캐시 등에 적합
• 클라이언트가 많거나 데이터가 큰 곳에는 부적합
• SQLite Browser
• http://sqlitebrowser.org/
SQL 연습
• SQLite browser
New Database "SQL_practice.db"
• CREATE TABLE 'employees' (
'employee_number' INTEGER,
'employee_name' TEXT,
'salary' INTEGER,
PRIMARY KEY(employee_number)
);
• Execute SQL
• INSERT INTO employees (employee_number, employee_name, salary)
VALUES (1001, 'Sally Johnson', 32000);
• SELECT *
FROM employees
WHERE salary <= 52500;
http://www.techonthenet.com/sql/
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;
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 드라이버
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
ORM(Object Relational Mapper)
객체 지향
프로그래밍
관계형
데이터베이스
• SQLObject
• Storm
• Django의 ORM
• peewee
• SQLAlchemy
• PonyORM
peewee
• 작고 단순한 ORM
• https://github.com/coleifer/peewee
• 설치
> pip install peewee
peewee – CREATE
>>> from peewee import *
>>> db = SqliteDatabase('people.db')
>>> class Person(Model):
... name = CharField()
... birthday = DateField()
... is_relative = BooleanField()
...
... class Meta:
... database = db
...
>>> db.connect()
>>> db.create_tables([Person])
peewee – INSERT
>>> from datetime import date
>>> a_person = Person(name='Bob', birthday=date(1960, 1, 15),
... is_relative=True)
>>> a_person.save()
1
>>> Person.create(name='Grandma', birthday=date(1935, 3, 1),
... is_relative=True)
<__main__.Person object at 0x1022d7550>
>>> Person.create(name='Herb', birthday=date(1950, 5, 5),
... is_relative=False)
<__main__.Person object at 0x1022d78d0>
peewee – SELECT
>>> for p in Person.select():
... print(p.name, p.birthday)
...
Bob 1960-01-15
Grandma 1935-03-01
Herb 1950-05-05
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
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
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
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.
Python 인터넷 라이브러리
Python 인터넷 라이브러리
• 표준 라이브러리
• 인터넷 데이터 처리: json, base64, ...
• 구조화된 마크업 프로세싱 도구: xml.etree.ElementTree, ...
• 인터넷 프로토콜 지원: webbrowser, urllib, ...
• Requests, ...
JSON(JavaScript Object Notation)
{
"이름": "테스트",
"나이": 25,
"성별": "여",
"주소": "서울특별시 양천구 목동",
"특기": ["농구", "도술"],
"가족관계": {"#": 2, "아버지": "홍판서", "어머니": "춘
섬"},
"회사": "경기 안양시 만안구 안양7동"
}
https://ko.wikipedia.org/wiki/JSON
http://json.org/json-ko.html
json.loads()
>>> json_string = '{"first_name": "Guido", "last_name":"Rossum"}'
>>> import json
>>> parsed_json = json.loads(json_string)
>>> print(parsed_json['first_name'])
Guido
json.dumps()
>>> d = {
... 'first_name': 'Guido',
... 'second_name': 'Rossum',
... 'titles': ['BDFL', 'Developer'],
... }
>>> print(json.dumps(d))
{"first_name": "Guido", "second_name": "Rossum", "titles": ["BDFL",
"Developer"]}
Base64
• ASCII
• 7 비트 (27 = 128)
• 95개의 출력 가능한 문자 + 32개의 특수 문자 + 1개의 공백 문자
• 모든 플랫폼이 ASCII를 지원하는 것은 아님
• 8 비트 이진 데이터
• 이미지, 실행 파일, 압축 파일, ...
• Base64
• 이진 데이터  64개의 문자로 이루어진 데이터
• 데이터를 안전하게 전송
http://kyejusung.com/2015/06/it-base64란/
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='
webbrowser
> python -m webbrowser -t "http://www.python.org"
>>> import webbrowser
>>> webbrowser.open("https:/docs.python.org/3/library/webbrowser.html")
True
urllib.request
>>> import urllib.request
>>> with urllib.request.urlopen('http://www.python.org/') as f:
... print(f.read(300))
...
b'<!doctype html>n<!--[if lt IE 7]> <html class="no-js ie6 lt-ie
7 lt-ie8 lt-ie9"> <![endif]-->n<!--[if IE 7]> <html class="
no-js ie7 lt-ie8 lt-ie9"> <![endif]-->n<!--[if IE 8]>
<html class="no-js ie8 lt-ie9"> <![endif]-->n<!--[
if gt IE 8]><!--><html class="no-js"'
Requests
> pip install requests
> py -3
>>> import requests
>>> url = "http://openapi.naver.com/search"
>>> params = {'key': 'c1b406b32dbbbbeee5f2a36ddc14067f',
... 'target': 'news',
... 'query': '%EC%A3%BC%EC%8B%9D',
... 'display': '10',
... 'start': '1',
... }
>>> r = requests.get(url, params=params)
>>> r.status_code
200
>>> r.text
'<?xml version="1.0" encoding="UTF-8"?>rn<rss version="2.0"><channel><title>Na
ver Open API - news ::'sample'</title><link>http://search.naver.com</link><des
cription>Naver Search Result</description><lastBuildDate>Mon, 06 Jul 2015 11:08:
http://developer.naver.com/wiki/pages/News
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
PyCharm
PyCharm
Professional Edition
• 모든 기능
• Django, Flask, Google App
Engine 등의 개발을 지원
• Javascript, CoffeeScript 등
Community Edition
• Python 개발 위주의 경량 IDE
• 오픈 소스
PyCharm 설치
• https://www.jetbrains.com/pycharm/download/
• Community Edition 다운로드 및 설치
Django
웹 프레임워크
대표적인 Python 웹 프레임워크
• Bottle
• 간결함. 저수준의 작업이 필요
• Flask
• 민첩함, 빠른 프로토타이핑
• 웹 애플리케이션 개발을 위해 여러 도구들을 조합하여 사용
(예: Flask + Jinja2 + SQLAlchemy)
• Pyramid
• 유연성, 최소화, 속도, 신뢰성
• 프로토타이핑, API 프로젝트
• Django
• 강력함, 많은 기능, 크고 활발한 커뮤니티
http://egloos.zum.com/mcchae/v/11064660
Django의 특징
• 자체 ORM, 템플릿 언어, 요청/응답 객체 내장
• 강력하고 자동화된 관리자 인터페이스
• 뛰어난 보안성(SQL 인젝션, 교차 사이트 스크립팅 방지 등)
• 다양한 기능
• 사용자층이 두텁고 문서화가 잘 되어있음
Django – Batteries Included
• Admin(관리자)
• 사용자 인증
• Cache
• 보안(Clickjacking 방지)
• 댓글
• 국제화
• 로깅
• 페이지네이션
Django – MVC or MTV
일반적인 용어 설명 Django에서의 구현
Model 애플리케이션 데이터 Model
View 사용자 인터페이스 요소
모델로부터 얻은 정보를 사용자에게 보여줌
Template
Controller 데이터와 비즈니스 로직의 상호동작을 관리
모델의 상태를 변경.
“View” 혹은 프레임워크 자체
• MVC(Model–View–Controller)
• 소프트웨어 아키텍처
• 사용자 인터페이스로부터 비즈니스 로직을 분리
• Django에서는 model, template, view를 통해 MVC를 구현
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
Django 커뮤니티, 개발 사례, 행사
• 페이스북 (한국) Django 그룹
https://www.facebook.com/groups/django
• DjangoCon
• 유럽 http://2015.djangocon.eu/
• 미국 https://2015.djangocon.us/
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()
Django – 프로젝트 생성
• 프로젝트 생성
• PyCharm – Open D:mysite
> D:
> cd 
> django-admin startproject mysite
Django – 프로젝트 설정
• mysitemysitesettings.py
• DATABASES
• 디폴트: sqlite3 사용(파일명: db.sqlite3)
• PostgreSQL 등 다른 데이터베이스 사용 시
• 데이터베이스를 사용하기 위한 Python 드라이버 설치
• settings.py의 DATABASES 편집(사용자, 패스워드, 호스트 정보 포함)
• LANGUAGE_CODE = 'ko-kr'
• TIME_ZONE = 'KST'
Django – 서버 기동
• 개발 서버 기동
• 웹브라우저로 접속
• 개발 서버 정지: CONTROL-C
> d:
> cd mysite
> python manage.py runserver
Starting development server at http://127.0.0.1:8000/
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),
]
Django 단어장
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
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',
)
Django 단어장 – migrate, createsuperuse
• 데이터베이스 생성
D:mysite> python manage.py makemigrations
D:mysite> python manage.py migrate
• 관리자 계정 생성
D:mysite>python manage.py createsuperuser
Django 단어장 – admin.py
• Word 모델을 관리자 화면에서 볼 수 있도록 등록
• D:mysitevocabularyadmin.py 편집
from django.contrib import admin
from .models import Word
admin.site.register(Word)
Django 단어장 – admin
• runserver
• http://127.0.0.1:8000/admin
• 목록
• 추가, 변경, 삭제
Django 단어장 2
Django 단어장 2 – models.py
• 모델 변경
D:mysitevocabularymodels.py
• 마이그레이션
• admin에서 확인
from django.db import models
class Word(models.Model):
word = models.CharField(max_length=50)
meaning = models.CharField(max_length=500, null=True, blank=True)
def __str__(self):
return(self.word)
D:mysite> python manage.py makemigrations
D:mysite> python manage.py migrate
Django 단어장 2 – templates
• mysitevocabularytemplatesvocabularyindex.html
{% if word_list %}
<dl>
{% for word in word_list %}
<dt>{{ word.word }}</dt>
<dd>{{ word.meaning }}</dd>
{% endfor %}
</dl>
{% else %}
<p>No words are available.</p>
{% endif %}
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_dd_test
Django 단어장 2 – views.py
• mysitevocabularyviews.py
from django.shortcuts import render
from .models import Word
def index(request):
context = {'word_list': Word.objects.all()}
return render(request, 'vocabulary/index.html', context)
Django 단어장 2 – urls.py
• mysitevocabularyurls.py
• mysitemysiteurls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
...
urlpatterns = [
...
url(r'^vocabulary/', include('vocabulary.urls')),
]

More Related Content

PDF
Django in Production
PPTX
Java와 Python의 만남: Jython과 Sikuli
PDF
[PyConKR 2014] 30분만에 따라하는 동시성 스크래퍼
PDF
robot.txt와 meta tag를 이용한 크롤링 설정
PDF
QnA blog using Django - ORM, 회원가입, 로그인/로그아웃
PDF
Django를 Django답게, Django로 뉴스 사이트 만들기
PDF
옛날 웹 개발자가 잠깐 맛본 Vue.js 소개
PPTX
5-4. html5 offline and storage
Django in Production
Java와 Python의 만남: Jython과 Sikuli
[PyConKR 2014] 30분만에 따라하는 동시성 스크래퍼
robot.txt와 meta tag를 이용한 크롤링 설정
QnA blog using Django - ORM, 회원가입, 로그인/로그아웃
Django를 Django답게, Django로 뉴스 사이트 만들기
옛날 웹 개발자가 잠깐 맛본 Vue.js 소개
5-4. html5 offline and storage

What's hot (20)

PDF
Light Tutorial Django
PPTX
Nodejs, PhantomJS, casperJs, YSlow, expressjs
PPTX
The beginner’s guide to 웹 크롤링 (스크래핑)
PPTX
플라스크 템플릿
PDF
Node.js 심화과정
PDF
Node.js 기본과정
PPTX
웹 크롤링 (Web scraping) 의 이해
PPTX
141118 최창원 웹크롤러제작
PPTX
Node.js
PDF
Django, 저는 이렇게 씁니다.
PPTX
파이썬 언어 기초
PDF
테스트가 뭐예요?
PPTX
4-3. jquery
PDF
20141223 머하웃(mahout) 협업필터링_추천시스템구현
PPTX
Leadweb Nodejs
PPTX
[Http완벽가이드] 9장 웹로봇
PDF
[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?
PDF
Python 으로 Slackbot 개발하기
PDF
진짜기초 Node.js
PDF
Clean Front-End Development
Light Tutorial Django
Nodejs, PhantomJS, casperJs, YSlow, expressjs
The beginner’s guide to 웹 크롤링 (스크래핑)
플라스크 템플릿
Node.js 심화과정
Node.js 기본과정
웹 크롤링 (Web scraping) 의 이해
141118 최창원 웹크롤러제작
Node.js
Django, 저는 이렇게 씁니다.
파이썬 언어 기초
테스트가 뭐예요?
4-3. jquery
20141223 머하웃(mahout) 협업필터링_추천시스템구현
Leadweb Nodejs
[Http완벽가이드] 9장 웹로봇
[커빙 아키텍쳐] 커빙은 어떻게 소셜 컨텐츠를 모아올까요?
Python 으로 Slackbot 개발하기
진짜기초 Node.js
Clean Front-End Development
Ad

Similar to Python 웹 프로그래밍 (20)

PDF
[Td 2015]치즈케이크 팩토리는 알겠는데, 데이터 팩토리는 뭔가요(한기환)
PPTX
모바일 게임과 앱을 위한 오픈소스 게임서버 엔진 프로젝트 CloudBread 프로젝트
PPTX
프로그래밍 패러다임의 진화 및 Spring의 금융권 적용
PDF
Mongo db 시작하기
PDF
AWS기반 서버리스 데이터레이크 구축하기 - 김진웅 (SK C&C) :: AWS Community Day 2020
PDF
AWS기반 서버리스 데이터레이크 구축하기 - 김진웅 (SK C&C) :: AWS Community Day 2020
PPTX
Mongo db 최범균
PPTX
Html5
PDF
02.실행환경 교육교재(데이터처리)
PDF
Infiniflux introduction
PPTX
[AWSKRUG] 모바일게임 하이브 런칭기 (2018)
PDF
[2012널리세미나] 오빠~ 네이버 왜 이렇게 늦게 떠?
PDF
AWS re:Invent 2020 Awesome AI/ML Services
PDF
성공적인 게임 런칭을 위한 비밀의 레시피 #3
PPTX
Bigquery와 airflow를 이용한 데이터 분석 시스템 구축 v1 나무기술(주) 최유석 20170912
PPTX
모바일 게임 하이브 런칭기 - 최용호
PPT
Ndc2011 성능 향상을_위한_데이터베이스_아키텍쳐_구축_및_개발_가이드
PPTX
HeadFisrt Servlet&JSP Chapter 3
 
PDF
[PyCon KR 2018] 진실은 언제나 하나! : Python으로 만나보는 Digital Forensic
PDF
좌충우돌 ORM 개발기 2012 DAUM DEVON
[Td 2015]치즈케이크 팩토리는 알겠는데, 데이터 팩토리는 뭔가요(한기환)
모바일 게임과 앱을 위한 오픈소스 게임서버 엔진 프로젝트 CloudBread 프로젝트
프로그래밍 패러다임의 진화 및 Spring의 금융권 적용
Mongo db 시작하기
AWS기반 서버리스 데이터레이크 구축하기 - 김진웅 (SK C&C) :: AWS Community Day 2020
AWS기반 서버리스 데이터레이크 구축하기 - 김진웅 (SK C&C) :: AWS Community Day 2020
Mongo db 최범균
Html5
02.실행환경 교육교재(데이터처리)
Infiniflux introduction
[AWSKRUG] 모바일게임 하이브 런칭기 (2018)
[2012널리세미나] 오빠~ 네이버 왜 이렇게 늦게 떠?
AWS re:Invent 2020 Awesome AI/ML Services
성공적인 게임 런칭을 위한 비밀의 레시피 #3
Bigquery와 airflow를 이용한 데이터 분석 시스템 구축 v1 나무기술(주) 최유석 20170912
모바일 게임 하이브 런칭기 - 최용호
Ndc2011 성능 향상을_위한_데이터베이스_아키텍쳐_구축_및_개발_가이드
HeadFisrt Servlet&JSP Chapter 3
 
[PyCon KR 2018] 진실은 언제나 하나! : Python으로 만나보는 Digital Forensic
좌충우돌 ORM 개발기 2012 DAUM DEVON
Ad

More from 용 최 (6)

PDF
우분투한국커뮤니티 수학스터디결과보고
PPTX
Python on Android
PPTX
Python 활용: 이미지 처리와 데이터 분석
PPTX
Python 표준 라이브러리
PPTX
Python 내장 함수
PPTX
Python 생태계의 이해
우분투한국커뮤니티 수학스터디결과보고
Python on Android
Python 활용: 이미지 처리와 데이터 분석
Python 표준 라이브러리
Python 내장 함수
Python 생태계의 이해

Python 웹 프로그래밍

  • 1. 파이썬 웹 프로그래밍 정보기술 시대에 유익한 파이썬 프로그래밍 – 제 9 강 동양미래대학교 2015.7 최용 <sk8er.choi@gmail.com>
  • 2. 주제 • 데이터베이스와 Python • Python 인터넷 라이브러리 • PyCharm – Python 개발 도구 • Django 웹 프레임워크
  • 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
  • 5. SQLite • https://www.sqlite.org/ • 작고 단순한 DBMS • 임베디드, 중소규모 웹사이트, 데이터 분석, 캐시 등에 적합 • 클라이언트가 많거나 데이터가 큰 곳에는 부적합 • SQLite Browser • http://sqlitebrowser.org/
  • 6. SQL 연습 • SQLite browser New Database "SQL_practice.db" • CREATE TABLE 'employees' ( 'employee_number' INTEGER, 'employee_name' TEXT, 'salary' INTEGER, PRIMARY KEY(employee_number) ); • Execute SQL • INSERT INTO employees (employee_number, employee_name, salary) VALUES (1001, 'Sally Johnson', 32000); • SELECT * FROM employees WHERE salary <= 52500; http://www.techonthenet.com/sql/
  • 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
  • 10. ORM(Object Relational Mapper) 객체 지향 프로그래밍 관계형 데이터베이스 • SQLObject • Storm • Django의 ORM • peewee • SQLAlchemy • PonyORM
  • 11. peewee • 작고 단순한 ORM • https://github.com/coleifer/peewee • 설치 > pip install peewee
  • 12. peewee – CREATE >>> from peewee import * >>> db = SqliteDatabase('people.db') >>> class Person(Model): ... name = CharField() ... birthday = DateField() ... is_relative = BooleanField() ... ... class Meta: ... database = db ... >>> db.connect() >>> db.create_tables([Person])
  • 13. peewee – INSERT >>> from datetime import date >>> a_person = Person(name='Bob', birthday=date(1960, 1, 15), ... is_relative=True) >>> a_person.save() 1 >>> Person.create(name='Grandma', birthday=date(1935, 3, 1), ... is_relative=True) <__main__.Person object at 0x1022d7550> >>> Person.create(name='Herb', birthday=date(1950, 5, 5), ... is_relative=False) <__main__.Person object at 0x1022d78d0>
  • 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.
  • 20. Python 인터넷 라이브러리 • 표준 라이브러리 • 인터넷 데이터 처리: json, base64, ... • 구조화된 마크업 프로세싱 도구: xml.etree.ElementTree, ... • 인터넷 프로토콜 지원: webbrowser, urllib, ... • Requests, ...
  • 21. JSON(JavaScript Object Notation) { "이름": "테스트", "나이": 25, "성별": "여", "주소": "서울특별시 양천구 목동", "특기": ["농구", "도술"], "가족관계": {"#": 2, "아버지": "홍판서", "어머니": "춘 섬"}, "회사": "경기 안양시 만안구 안양7동" } https://ko.wikipedia.org/wiki/JSON http://json.org/json-ko.html
  • 22. json.loads() >>> json_string = '{"first_name": "Guido", "last_name":"Rossum"}' >>> import json >>> parsed_json = json.loads(json_string) >>> print(parsed_json['first_name']) Guido
  • 23. json.dumps() >>> d = { ... 'first_name': 'Guido', ... 'second_name': 'Rossum', ... 'titles': ['BDFL', 'Developer'], ... } >>> print(json.dumps(d)) {"first_name": "Guido", "second_name": "Rossum", "titles": ["BDFL", "Developer"]}
  • 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='
  • 26. webbrowser > python -m webbrowser -t "http://www.python.org" >>> import webbrowser >>> webbrowser.open("https:/docs.python.org/3/library/webbrowser.html") True
  • 27. urllib.request >>> import urllib.request >>> with urllib.request.urlopen('http://www.python.org/') as f: ... print(f.read(300)) ... b'<!doctype html>n<!--[if lt IE 7]> <html class="no-js ie6 lt-ie 7 lt-ie8 lt-ie9"> <![endif]-->n<!--[if IE 7]> <html class=" no-js ie7 lt-ie8 lt-ie9"> <![endif]-->n<!--[if IE 8]> <html class="no-js ie8 lt-ie9"> <![endif]-->n<!--[ if gt IE 8]><!--><html class="no-js"'
  • 28. Requests > pip install requests > py -3 >>> import requests >>> url = "http://openapi.naver.com/search" >>> params = {'key': 'c1b406b32dbbbbeee5f2a36ddc14067f', ... 'target': 'news', ... 'query': '%EC%A3%BC%EC%8B%9D', ... 'display': '10', ... 'start': '1', ... } >>> r = requests.get(url, params=params) >>> r.status_code 200 >>> r.text '<?xml version="1.0" encoding="UTF-8"?>rn<rss version="2.0"><channel><title>Na ver Open API - news ::'sample'</title><link>http://search.naver.com</link><des cription>Naver Search Result</description><lastBuildDate>Mon, 06 Jul 2015 11:08: http://developer.naver.com/wiki/pages/News
  • 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)
  • 50. Django 단어장 – admin • runserver • http://127.0.0.1:8000/admin • 목록 • 추가, 변경, 삭제
  • 52. Django 단어장 2 – models.py • 모델 변경 D:mysitevocabularymodels.py • 마이그레이션 • admin에서 확인 from django.db import models class Word(models.Model): word = models.CharField(max_length=50) meaning = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return(self.word) D:mysite> python manage.py makemigrations D:mysite> python manage.py migrate
  • 53. Django 단어장 2 – templates • mysitevocabularytemplatesvocabularyindex.html {% if word_list %} <dl> {% for word in word_list %} <dt>{{ word.word }}</dt> <dd>{{ word.meaning }}</dd> {% endfor %} </dl> {% else %} <p>No words are available.</p> {% endif %} http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_dd_test
  • 54. Django 단어장 2 – views.py • mysitevocabularyviews.py from django.shortcuts import render from .models import Word def index(request): context = {'word_list': Word.objects.all()} return render(request, 'vocabulary/index.html', context)
  • 55. Django 단어장 2 – urls.py • mysitevocabularyurls.py • mysitemysiteurls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] ... urlpatterns = [ ... url(r'^vocabulary/', include('vocabulary.urls')), ]