10. 웹

2016. 11. 29. 17:08Programming Languages/PYTHON

1)파이썬 표준 웹 라이브러리

파이썬3에서는 웹 클라이언트와 서버 모듈을 묶어 httpurllib의 두 개의 패키지로 제공한다.


http는 클라이언트 부분의 관리, 웹 서버 작성, 방문 데이터를 저장한 쿠키의 관리 기능을 제공한다.

http위에서 실행되는 urllib는 클라이언트의 요청 처리, 서번의 응답 처리, URL분석 기능을 제공한다.



urllib의 request 모듈은 클라이언트의 요청을 처리하는데 사용되는데, 아래 예제를 통해 실제 사용법을 살펴보자.

1
2
3
4
5
6
7
import urllib.request as ur
url='http://www.example.com'
conn=ur.urlopen(url)
print(conn)
#<http.client.HTTPResponse object at 0x000002641FCDE518>
data=conn.read()
print(data)
cs

위의 코드를 실행하면 아래와 같은 출력물을 얻을 수 있다.

b'<!doctype html>\n<html>\n<head>\n    <title>Example Domain</title>\n\n    <meta charset="utf-8" />\n    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />\n    <meta name="viewport" content="width=device-width, initial-scale=1" />\n    <style type="text/css">\n    body {\n        background-color: #f0f0f2;\n        margin: 0;\n        padding: 0;\n        font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;\n        \n    }\n    div {\n        width: 600px;\n        margin: 5em auto;\n        padding: 50px;\n        background-color: #fff;\n        border-radius: 1em;\n    }\n    a:link, a:visited {\n        color: #38488f;\n        text-decoration: none;\n    }\n    @media (max-width: 700px) {\n        body {\n            background-color: #fff;\n        }\n        div {\n            width: auto;\n            margin: 0 auto;\n            border-radius: 0;\n            padding: 1em;\n        }\n    }\n    </style>    \n</head>\n\n<body>\n<div>\n    <h1>Example Domain</h1>\n    <p>This domain is established to be used for illustrative examples in documents. You may use this\n    domain in examples without prior coordination or asking for permission.</p>\n    <p><a href="http://www.iana.org/domains/example">More information...</a></p>\n</div>\n</body>\n</html>\n'


크롬 등의 브라우저를 통해 http://www.example.com/에 접속해서 위의 코드의 출력물과 브라우저의 출력물을 비교해 보면,  (앞 뒤의 복잡한 용어들은 이해하지 못하더라도) 그 둘이 같은 페이지를 표현하고 있음을 확인 할 수 있다.



아래와 같이 .status로 응답코드를 확인하거나 (성공시 200대의 숫자가 출력될 것이다) getheader로 데이터의 포멧을 확인할 수도 있다.

1
2
3
4
print(conn.status)
#200
print(conn.getheader('Content-Type'))
#text/html




cs





2)파이썬 웹 서버

파이썬에서 웹 서버를 구현하는 방법에는 여러가지가 있다.

처음 시도하는 용도로 사용할 간단한 웹서버는 표준 파이썬에 포함된 간단한 코드로 실행할 수 있다.


cmd를 실행한 뒤 다음과 같이 입력해 보자.

python -m http.server

위의 명령어를 입력하면 간단한 서버가 구현된다. 그 뒤에 인터넷 브라우저의 주소창에 http://localhost:8000 또는 http://127.0.0.1:8000/를 입력하면, cmd창에서 python 명령을 실행했던 디렉터리의 내용이 쭈루룩 뜰 것이다.



그 뒤에 다시 cmd창을 보면 

127.0.0.1 - - [29/Nov/2016 16:55:54] "GET / HTTP/1.1" 200 -

와 같은 메시지가 떠있음을 확인할 수 있다. 127.0.0.1의 IP주소를 가진 클라이언트가 서버에 접속했음을 알려주는 메시지이다.





3)웹 프레임워크

파이썬에서는 기본제공되는 웹 서버 외에 여러 유용한 웹 프레임워크를 사용할 수 있다.

책에서는 DB지원이 필요 없는 작은 웹 서버를 만들기 위해 쓰는 bottle과 flask의 예제를 알려주었다. 나는 두 가지 외에 가장 자주 보이는 Django를 이용해 웹 서버를 구현하고자 한다. 

--> Django 카테고리로!

  (http://doongkibangki.tistory.com/category/PYTHON/Django)