55
파파파 파 파파파파파 파파파파 파파파 파파파 파파파 파파파파파 – 파 9 파 파파파파파파파 2015.7 파파 <[email protected]>

Python 웹 프로그래밍

  • Upload
    -

  • View
    194

  • Download
    3

Embed Size (px)

Citation preview

Page 1: Python 웹 프로그래밍

파이썬 웹 프로그래밍정보기술 시대에 유익한 파이썬 프로그래밍 – 제 9 강

동양미래대학교2015.7

최용 <[email protected]>

Page 2: Python 웹 프로그래밍

주제• 데이터베이스와 Python• Python 인터넷 라이브러리• PyCharm – Python 개발 도구• Django 웹 프레임워크

Page 3: Python 웹 프로그래밍

데이터베이스와 Python

Page 4: Python 웹 프로그래밍

데이터베이스• 데이터베이스 : 데이터의 조직화된 모음• 데이터베이스 모델

• Hierarchical• Relational• Object• ...

• DBMS( 데이터베이스 관리 시스템 )• 사용자 또는 애플리케이션과 상호작용• 데이터 정의 · 생성 · 질의 · 갱신 , 관리• MySQL, PostgreSQL, Microsoft SQL Server,

Oracle, Sybase, IBM DB2, ...

https://en.wikipedia.org/wiki/Database#/media/File:Database_models.jpg

https://en.wikipedia.org/wiki/Database

Page 5: Python 웹 프로그래밍

SQLite

• https://www.sqlite.org/• 작고 단순한 DBMS• 임베디드 , 중소규모 웹사이트 , 데이터 분석 , 캐시 등에 적합• 클라이언트가 많거나 데이터가 큰 곳에는 부적합

• SQLite Browser• http://sqlitebrowser.org/

Page 6: Python 웹 프로그래밍

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 employeesWHERE salary <= 52500;

http://www.techonthenet.com/sql/

Page 7: Python 웹 프로그래밍

SQL 연습• UPDATE employeesSET salary = 33000WHERE employee_number = 1001;

• Write Changes / Revert Changes( 일반적인 RDBMS 에서는 COMMIT / ROLLBACK 명령을 사용 )

• SELECT *FROM employeesWHERE employee_name LIKE 'Sally%'

• DELETE FROM employeesWHERE employee_number = 1001;

Page 8: Python 웹 프로그래밍

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 드라이버

Page 9: Python 웹 프로그래밍

sqlite3 – SQLite3 데이터베이스 어댑터import sqlite3conn = 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 sqlite3conn = 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

Page 10: Python 웹 프로그래밍

ORM(Object Relational Mapper)

객체 지향 프로그래밍

관계형데이터베이스

• SQLObject• Storm• Django 의 ORM• peewee• SQLAlchemy• PonyORM

Page 11: Python 웹 프로그래밍

peewee

• 작고 단순한 ORM• https://github.com/coleifer/peewee • 설치> pip install peewee

Page 12: Python 웹 프로그래밍

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])

Page 13: Python 웹 프로그래밍

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>

Page 14: Python 웹 프로그래밍

peewee – SELECT

>>> for p in Person.select():... print(p.name, p.birthday)... Bob 1960-01-15Grandma 1935-03-01Herb 1950-05-05

Page 15: Python 웹 프로그래밍

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

Page 16: Python 웹 프로그래밍

peewee – SELECT ... ORDER BY

>>> for person in Person.select():... print(person.name, person.is_relative)... Bob TrueGrandma TrueHerb False

>>> for person in Person.select().order_by(Person.birthday.desc()):... print(person.name, person.birthday)... Bob 1960-01-15Herb 1950-05-05Grandma 1935-03-01

Page 17: Python 웹 프로그래밍

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

Page 18: Python 웹 프로그래밍

peewee – DELETE

>>> h = Person.select().where(Person.is_relative != True).get()

>>> h.delete_instance()

1

>>> for p in Person.select():... print(p.name)... BobGrandma L.

Page 19: Python 웹 프로그래밍

Python 인터넷 라이브러리

Page 20: Python 웹 프로그래밍

Python 인터넷 라이브러리• 표준 라이브러리• 인터넷 데이터 처리 : json, base64, ...• 구조화된 마크업 프로세싱 도구 : xml.etree.ElementTree, ...• 인터넷 프로토콜 지원 : webbrowser, urllib, ...

• Requests, ...

Page 21: Python 웹 프로그래밍

JSON(JavaScript Object Notation)

{ " 이름 ": " 테스트 ", " 나이 ": 25, " 성별 ": " 여 ", " 주소 ": " 서울특별시 양천구 목동 ", " 특기 ": [" 농구 ", " 도술 "], " 가족관계 ": {"#": 2, " 아버지 ": " 홍판서 ", " 어머니 ": " 춘섬 "}, " 회사 ": " 경기 안양시 만안구 안양 7 동 " } https://ko.wikipedia.org/wiki/JSON

http://json.org/json-ko.html

Page 22: Python 웹 프로그래밍

json.loads()

>>> json_string = '{"first_name": "Guido", "last_name":"Rossum"}'

>>> import json

>>> parsed_json = json.loads(json_string)

>>> print(parsed_json['first_name'])Guido

Page 23: Python 웹 프로그래밍

json.dumps()

>>> d = {... 'first_name': 'Guido',... 'second_name': 'Rossum',... 'titles': ['BDFL', 'Developer'],... }

>>> print(json.dumps(d)){"first_name": "Guido", "second_name": "Rossum", "titles": ["BDFL", "Devel-oper"]}

Page 24: Python 웹 프로그래밍

Base64

• ASCII• 7 비트 (27 = 128)• 95 개의 출력 가능한 문자 + 32 개의 특수 문자 + 1 개의 공백 문자• 모든 플랫폼이 ASCII 를 지원하는 것은 아님

• 8 비트 이진 데이터• 이미지 , 실행 파일 , 압축 파일 , ...

• Base64• 이진 데이터 64 개의 문자로 이루어진 데이터• 데이터를 안전하게 전송

http://kyejusung.com/2015/06/it-base64란/

Page 25: Python 웹 프로그래밍

base64

>>> s = b'Man distinguished, not only by his reason, but by this singular pas-sion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.'

>>> import base64

>>> base64.b64encode(s)b'TWFuIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1d-CBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGl-jaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcm-FuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWd-hYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9yd-CB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4='

Page 26: Python 웹 프로그래밍

webbrowser

> python -m webbrowser -t "http://www.python.org"

>>> import webbrowser

>>> webbrowser.open("https:/docs.python.org/3/library/webbrowser.html")True

Page 27: Python 웹 프로그래밍

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-ie7 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"'

Page 28: Python 웹 프로그래밍

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_code200>>> r.text'<?xml version="1.0" encoding="UTF-8"?>\r\n<rss version="2.0"><channel><title>Naver Open API - news ::\'sample\'</title><link>http://search.naver.com</link><description>Naver Search Result</description><lastBuildDate>Mon, 06 Jul 2015 11:08:

http://developer.naver.com/wiki/pages/News

Page 29: Python 웹 프로그래밍

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 RockSoybean master revives traditional flavorsEvent Cinema Revenues to Hit $1 Billion by 2019, IHS Report Says

Page 30: Python 웹 프로그래밍

PyCharm

Page 31: Python 웹 프로그래밍

PyCharm

Professional Edition

• 모든 기능• Django, Flask, Google App

Engine 등의 개발을 지원• Javascript, CoffeeScript 등

Community Edition

• Python 개발 위주의 경량 IDE• 오픈 소스

Page 32: Python 웹 프로그래밍

PyCharm 설치• https://www.jetbrains.com/pycharm/download/• Community Edition 다운로드 및 설치

Page 33: Python 웹 프로그래밍

Django웹 프레임워크

Page 34: Python 웹 프로그래밍

대표적인 Python 웹 프레임워크• Bottle

• 간결함 . 저수준의 작업이 필요• Flask

• 민첩함 , 빠른 프로토타이핑• 웹 애플리케이션 개발을 위해 여러 도구들을 조합하여 사용

( 예 : Flask + Jinja2 + SQLAlchemy)

• Pyramid• 유연성 , 최소화 , 속도 , 신뢰성• 프로토타이핑 , API 프로젝트

• Django• 강력함 , 많은 기능 , 크고 활발한 커뮤니티

http://egloos.zum.com/mcchae/v/11064660

Page 35: Python 웹 프로그래밍

Django 의 특징• 자체 ORM, 템플릿 언어 , 요청 / 응답 객체 내장• 강력하고 자동화된 관리자 인터페이스• 뛰어난 보안성 (SQL 인젝션 , 교차 사이트 스크립팅 방지 등 )• 다양한 기능• 사용자층이 두텁고 문서화가 잘 되어있음

Page 36: Python 웹 프로그래밍

Django – Batteries Included

• Admin( 관리자 )• 사용자 인증• Cache• 보안 (Clickjacking 방지 )• 댓글• 국제화• 로깅• 페이지네이션

Page 37: Python 웹 프로그래밍

Django – MVC or MTV

일반적인 용어 설명 Django 에서의 구현Model 애플리케이션 데이터 Model

View 사용자 인터페이스 요소모델로부터 얻은 정보를 사용자에게 보여줌

Template

Controller 데이터와 비즈니스 로직의 상호동작을 관리모델의 상태를 변경 .

“View” 혹은 프레임워크 자체

• MVC(Model–View–Controller)• 소프트웨어 아키텍처• 사용자 인터페이스로부터 비즈니스 로직을 분리• Django 에서는 model, template, view 를 통해 MVC 를 구현

Page 38: Python 웹 프로그래밍

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

Page 39: Python 웹 프로그래밍

Django 커뮤니티 , 개발 사례 , 행사• 페이스북 ( 한국 ) Django 그룹

https://www.facebook.com/groups/django

• DjangoCon• 유럽 http://2015.djangocon.eu/

• 미국 https://2015.djangocon.us/

Page 40: Python 웹 프로그래밍

Django – 설치• python.org 배포본 사용

• Anaconda 제거• pip 및 python 경로를 찾지 못하는 경우 PATH 환경변수의 마지막에 다음을 추가

• Django 설치 및 확인;C:\Python34;C:\Python34\Scripts

> pip install django

> python

>>> import django

>>> django.get_version()

'1.8.3'

>>> exit()

Page 41: Python 웹 프로그래밍

Django – 프로젝트 생성• 프로젝트 생성

• PyCharm – Open D:\mysite

> D:> cd \> django-admin startproject mysite

Page 42: Python 웹 프로그래밍

Django – 프로젝트 설정• mysite\mysite\settings.py• DATABASES

• 디폴트 : sqlite3 사용 ( 파일명 : db.sqlite3)• PostgreSQL 등 다른 데이터베이스 사용 시

• 데이터베이스를 사용하기 위한 Python 드라이버 설치• settings.py 의 DATABASES 편집 ( 사용자 , 패스워드 , 호스트 정보 포함 )

• LANGUAGE_CODE = 'ko-kr'• TIME_ZONE = 'KST'

Page 43: Python 웹 프로그래밍

Django – 서버 기동• 개발 서버 기동

• 웹브라우저로 접속

• 개발 서버 정지 : CONTROL-C

> d:> cd \mysite> python manage.py runserverStarting development server at http://127.0.0.1:8000/

Page 44: Python 웹 프로그래밍

Django – Hello, Django!

• New File: \mysite\mysite\views.py

• \mysite\mysite\urls.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, urlfrom django.contrib import adminfrom mysite.views import hello

urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^hello', hello),]

Page 45: Python 웹 프로그래밍

Django 단어장

Page 46: Python 웹 프로그래밍

Django 단어장 – startapp, models.py

• 앱 생성

• 모델 작성 – D:\mysite\vocabulary\models.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

Page 47: Python 웹 프로그래밍

Django 단어장 – settings.py

• 프로젝트 설정D:\mysite\mysite\settings.py

INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'vocabulary',)

Page 48: Python 웹 프로그래밍

Django 단어장 – migrate, createsupe-ruse

• 데이터베이스 생성D:\mysite> python manage.py makemigrationsD:\mysite> python manage.py migrate

• 관리자 계정 생성D:\mysite>python manage.py createsuperuser

Page 49: Python 웹 프로그래밍

Django 단어장 – admin.py

• Word 모델을 관리자 화면에서 볼 수 있도록 등록• D:\mysite\vocabulary\admin.py 편집

from django.contrib import admin

from .models import Word

admin.site.register(Word)

Page 50: Python 웹 프로그래밍

Django 단어장 – admin

• runserver• http://127.0.0.1:8000/admin • 목록• 추가 , 변경 , 삭제

Page 51: Python 웹 프로그래밍

Django 단어장 2

Page 52: Python 웹 프로그래밍

Django 단어장 2 – models.py

• 모델 변경D:\mysite\vocabulary\models.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 makemigrationsD:\mysite> python manage.py migrate

Page 53: Python 웹 프로그래밍

Django 단어장 2 – templates

• \mysite\vocabulary\templates\vocabulary\index.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

Page 54: Python 웹 프로그래밍

Django 단어장 2 – views.py

• \mysite\vocabulary\views.pyfrom django.shortcuts import render

from .models import Word

def index(request): context = {'word_list': Word.objects.all()} return render(request, 'vocabulary/index.html', context)

Page 55: Python 웹 프로그래밍

Django 단어장 2 – urls.py

• \mysite\vocabulary\urls.py

• \mysite\mysite\urls.py

from django.conf.urls import url

from . import views

urlpatterns = [ url(r'^$', views.index, name='index'),]

...

urlpatterns = [ ... url(r'^vocabulary/', include('vocabulary.urls')),]