WeniVooks

검색

웹/네트워크/HTTP 베이스캠프

실습

5.1.1 Python 서버 구동

import socket
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
 
class CustomHTTPRequestHandler(BaseHTTPRequestHandler):
    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")
        self.end_headers()
 
    def do_GET(self):
        self.send_response(200)
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Content-type", "text/plain")  # 실습1
        # self.send_header("Content-type", "text/html")  # 실습2
        # -- 실습3 --
        # data = { # 실습3
        #     "message": "Hello, World!",
        #     "status": "success"
        # }
        # json_data = json.dumps(data)
        # self.send_header('Content-type', 'application/json')
        # -- //실습3 --
        self.end_headers()
        self.wfile.write(b"<h1>Hello, World!</h1>")
        # self.wfile.write(json_data.encode()) # 실습3
 
        print(
            f"Received GET request from {self.client_address[0]}:{self.client_address[1]}"
        )
        print(f"Request Headers:\n{self.headers}")
        print(f"Request Method: {self.command}")
        print(f"Request Path: {self.path}")
        print(f"Request Version: {self.request_version}")
 
    def do_POST(self):
        content_length = int(self.headers["Content-Length"])
        post_data = self.rfile.read(content_length)
 
        self.send_response(200)
        self.send_header("Access-Control-Allow-Origin", "*")
        # self.send_header("Content-type", "text/plain") # 실습1
        # self.send_header("Content-type", "text/html") # 실습2
        self.send_header("Content-type", "application/json")
        self.end_headers()
        # self.wfile.write(b"Received POST request") # 실습1
        # self.wfile.write(b"<h1>Hello, World!</h1>") # 실습2
        data = {"message": "Received POST request", "status": "success"}
        json_data = json.dumps(data)
        self.wfile.write(json_data.encode())
 
        print(
            f"Received POST request from {self.client_address[0]}:{self.client_address[1]}"
        )
        print(f"Request Headers:\n{self.headers}")
        print(f"Request Method: {self.command}")
        print(f"Request Path: {self.path}")
        print(f"Request Version: {self.request_version}")
        print(f"Request Body:\n{post_data.decode()}")
 
def run_server(port=8000):
    server_address = ("", port)
    httpd = HTTPServer(server_address, CustomHTTPRequestHandler)
    print(f"Starting server on port {port}")
    httpd.serve_forever()
 
if __name__ == "__main__":
    run_server()
 
import socket
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
 
class CustomHTTPRequestHandler(BaseHTTPRequestHandler):
    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")
        self.end_headers()
 
    def do_GET(self):
        self.send_response(200)
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Content-type", "text/plain")  # 실습1
        # self.send_header("Content-type", "text/html")  # 실습2
        # -- 실습3 --
        # data = { # 실습3
        #     "message": "Hello, World!",
        #     "status": "success"
        # }
        # json_data = json.dumps(data)
        # self.send_header('Content-type', 'application/json')
        # -- //실습3 --
        self.end_headers()
        self.wfile.write(b"<h1>Hello, World!</h1>")
        # self.wfile.write(json_data.encode()) # 실습3
 
        print(
            f"Received GET request from {self.client_address[0]}:{self.client_address[1]}"
        )
        print(f"Request Headers:\n{self.headers}")
        print(f"Request Method: {self.command}")
        print(f"Request Path: {self.path}")
        print(f"Request Version: {self.request_version}")
 
    def do_POST(self):
        content_length = int(self.headers["Content-Length"])
        post_data = self.rfile.read(content_length)
 
        self.send_response(200)
        self.send_header("Access-Control-Allow-Origin", "*")
        # self.send_header("Content-type", "text/plain") # 실습1
        # self.send_header("Content-type", "text/html") # 실습2
        self.send_header("Content-type", "application/json")
        self.end_headers()
        # self.wfile.write(b"Received POST request") # 실습1
        # self.wfile.write(b"<h1>Hello, World!</h1>") # 실습2
        data = {"message": "Received POST request", "status": "success"}
        json_data = json.dumps(data)
        self.wfile.write(json_data.encode())
 
        print(
            f"Received POST request from {self.client_address[0]}:{self.client_address[1]}"
        )
        print(f"Request Headers:\n{self.headers}")
        print(f"Request Method: {self.command}")
        print(f"Request Path: {self.path}")
        print(f"Request Version: {self.request_version}")
        print(f"Request Body:\n{post_data.decode()}")
 
def run_server(port=8000):
    server_address = ("", port)
    httpd = HTTPServer(server_address, CustomHTTPRequestHandler)
    print(f"Starting server on port {port}")
    httpd.serve_forever()
 
if __name__ == "__main__":
    run_server()
 

5.1.2 HTML/JavaScript 코드를 통해 요청(request)

주로 HTML이나 JavaScript에서 서버로 통신을 보내기에 이번 챕터에서는 Python으로 실습하진 않습니다.

  • 아래 JavaScript 코드로 GET을 보내는 것 확인

    fetch('http://127.0.0.1:8000/')
      .then((response) => response.json())
      .then((json) => console.log(json))
      .catch((error) => console.error(error));
    fetch('http://127.0.0.1:8000/')
      .then((response) => response.json())
      .then((json) => console.log(json))
      .catch((error) => console.error(error));
  • 아래 JavaScript 코드로 POST를 보내는 것 확인

    fetch('http://127.0.0.1:8000/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        title: 'test',
        content: 'test',
      }),
    })
      .then((response) => response.json())
      .then((json) => console.log(json))
      .catch((error) => console.error(error));
    fetch('http://127.0.0.1:8000/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        title: 'test',
        content: 'test',
      }),
    })
      .then((response) => response.json())
      .then((json) => console.log(json))
      .catch((error) => console.error(error));
  • 아래 HTML 코드로 GET과 POST를 보내는 것 확인

    <h2>POST</h2>
    <form action="http://127.0.0.1:8000" method="post">
        <input type="text" name="username" value="hellopost">
        <input type="password" name="password" value="worldpost">
        <input type="submit" value="Login">
    </form>
     
    <h2>GET</h2>
    <form action="http://127.0.0.1:8000" method="get">
        <input type="text" name="username" value="helloget">
        <input type="password" name="password" value="worldget">
        <input type="submit" value="Login">
    </form>
    <h2>POST</h2>
    <form action="http://127.0.0.1:8000" method="post">
        <input type="text" name="username" value="hellopost">
        <input type="password" name="password" value="worldpost">
        <input type="submit" value="Login">
    </form>
     
    <h2>GET</h2>
    <form action="http://127.0.0.1:8000" method="get">
        <input type="text" name="username" value="helloget">
        <input type="password" name="password" value="worldget">
        <input type="submit" value="Login">
    </form>
5.1 HTTP란?6장 HTTP 메시지 구조