본문 바로가기
+ Development/Python

[Python] HTTP - 일반적인 Response Header 파싱 코드(Lv.2)

by 염불법사 2019. 8. 21.
728x90
반응형
Python 을 이용한 HTTP 패킷 파싱하기 2회차

HTTP 패킷 Header 파일을 파싱하는 코드를 공유합니다.

※  Response Header  


네이버 검색하는 패킷 Header 입니다

HTTP/1.1 200 OK
X-Powered-By: BLOOD
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Max-Age: 1000
Date: Tue, 22 Jan 2019 15:32:42 GMT
Connection: keep-alive
Transfer-Encoding: chunked

 

※  Response Header  파싱 코드 


import os
from io import BytesIO
import urllib

import http
from http.client import HTTPResponse


class FakeSocket():
    def __init__(self, response_str):
        self._file = response_str

    def makefile(self, *args, **kwargs):
        return self._file

    def __del__(self):
        try:
            if self._file:
                self._file.close()
        except Exception:
            pass

globals().update(http.HTTPStatus.__members__)


class HTTPResponseHeader(HTTPResponse):
    """
      status :  200, 300

    """
    file_dir = None

    def __init__(self, file_dir):
        self.file_dir = file_dir
        socket = self.read_header()
        super(HTTPResponseHeader, self).__init__(socket)
        self.begin()

    def status_obj(self):
        return http.HTTPStatus(self.status)

    def read_header(self):
        try:
            response_file = os.path.join(self.file_dir, 'response.head')
            if os.path.exists(response_file):
                source = FakeSocket(open(response_file, 'rb'))
                return source
            else:
                print("Http Response - Read Header {0}".format(os.path.join(session_dir, 'response.head')))
                raise FileNotFoundError
        except IOError as e:
            print("Http Response - Read Header {0}".format(e))
            raise FileNotFoundError

    @property
    def content_type(self):
        return self.headers.get("Content-Type", None)

if __name__ == '__main__':
    response_header = HTTPResponseHeader("./")
    print(response_header.content_type)
    k= response_header.status_obj()
    print(k)
    print(k.value)
    print(k.phrase)
    print(k.description)

 

◈  파싱된 출력 내용.


첨부파일 

→  response.head    :  응답 Header 내용 

→  response.py    :   응답 Header 파일 파싱 코드

response.head
0.00MB
response.py
0.00MB

728x90
반응형

댓글


loading