본문 바로가기

전체 글291

do_GET+ do_POST 예제1 localhost:8000으로 접속하면 다음과 같은 화면이 나오고 hello world를 쓴뒤 Post it 버튼을 누르면 다음과 같이 나타나게 하려면 어떻게 해야할까? 1. html string을 가지는 form 변수를 만든다. form = ''' Message Board Post it! ''' 2. do_GET- form을 response로 준다. def do_GET(self): self.send_response(200) self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() self.wfile.write(form.encode()) 3. do_POST 부분 3.1. request의 entity body에 있는 me.. 2020. 7. 1.
parse_qs(POST data parsing) 클라이언트의 요청이 POST 방식이면 data는 entity body에 담겨서 온다. 따라서 별도의 작업을 해야 data를 사용할 수 있다. POST data parsing 예제 magic=mystery&secret=spooky 의 데이터를 서버에게 보냈다고 하자. 1. content lenght를 파악한다. length = int(self.headers.get('Content-length', 0)) self.headers.get은 header field에 있는 값들을 가져올 때 쓰인다. 헤더 정보 중에 키가 'Content-length'인 값을 가져오고 'Content-length'가 없을 경우에 0을 리턴하겠다는 뜻이다. 2. entity body에서 데이터 디코딩하여 "magic=mystery&se.. 2020. 7. 1.
urlparse GET 요청으로 보낼 경우에 데이터가 url 필드에 들어가게 된다. 따라서, 서버측에서는 들어온 url을 파싱하는 작업이 필요하다. 파싱할 때 사용할 수 있는 urlparse를 이해해보자. urlparse 실행방법 1. from urllib.parse import urlparse 를 통해 모듈을 가져온다. 2. 사용할 url을 지정한다. 주소창에 있는 url을 하나 가져와보자. 구글에서 urlparse를 검색하고 난 주소는 다음과 같다. url = "https://www.google.com/search?q=urlparse&oq=urlparse&aqs=chrome..69i57j0l7.1277j0j7&sourceid=chrome&ie=UTF-8" 3. urlparse(url)을 실행한다. 다음과 같은 결과가.. 2020. 7. 1.
EchoServer HelloServer에서 entity body를 쓰는 부분이 self.wfile.write() 부분인 것을 설명했다. 브라우저에 localhost:8000/helloPath! 를 치면 화면에 helloPath! 를 보여주려면 어떻게 할까? self.wfile.write(self.path[1:].encode())로 바꾸면 된다. 브라우저에 localhost:8000/helloPath! 라고 치면 우리가 작성한 코드에서 self.path에는 "/helloPath!"가 된다. 요청 -> 서버(요청한 url에서 path는 self.path로 사용가능) -> 응답 더 궁금하면 BaseHTTPRequestHandler에 대한 정보를 찾아보면 좋을 것이다. 2020. 7. 1.