WSGI 오류 해결: write() 인자는 bytes 타입이어야 함

오류 메시지:

C:\Users\Dmail\AppData\Local\Programs\Python\Python37\python.exe "E:/s9/day60/06 jinja2版web服务端示例.py"
나는 8090 포트에서 기다리고 있어...
Traceback (most recent call last):
  File "C:\Users\Dmail\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 138, in run
    self.finish_response()
  File "C:\Users\Dmail\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 184, in finish_response
    self.write(data)
  File "C:\Users\Dmail\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 279, in write
    "write() argument must be a bytes instance"
AssertionError: write() argument must be a bytes instance
127.0.0.1 - - [29/Sep/2019 13:13:30] "GET /index/ HTTP/1.1" 500 59
127.0.0.1 - - [29/Sep/2019 13:13:30] "GET /favicon.ico HTTP/1.1" 200 14

문제가 되는 코드:

from wsgiref.simple_server import make_server
from jinja2 import Template

def main_page():
    with open('06jinja2版web框架.html','r',encoding='utf-8')as f:
        content = f.read()
    template = Template(content) # 템플릿 파일 생성
    result = template.render({"user_name":"Dmail","interests":['프로그래밍','대검술']}) # 데이터를 템플릿에 적용
    return [result.encode('utf-8'),]



url_routes = [
    ('/index/',main_page)]

def application(environ,start_response):
    start_response('200 OK',[('Content-Type','text/html;charset=utf-8')])
    path = environ['PATH_INFO'] # 사용자가 요청한 URL 가져오기
    #print(path)
    matched_func = None
    for route in url_routes:
        if route[0] == path:
            matched_func = route[1]
            break
    if matched_func:
        response_data = matched_func()
    else:
        response_data = b'404 not found!'
    return response_data

if __name__ == '__main__':
    server = make_server('127.0.0.1',8090,application)
    print('나는 8090 포트에서 기다리고 있어...')
    server.serve_forever()

application 함수가 실행되어 response_data = matched_func(): ... return [result.encode('utf-8'),] 반환값이 리스트 형태임을 발견 반환값이 bytes 형태여야 한다는 것을 깨달음 마지막 반환값 코드를 다음과 같이 수정 return result.encode('utf-8') 127.0.0.1:8090/index/ 접속 후 정상적으로 접속 가능했지만, 여전히 오류 발생 application 함수의 return 문을 다음과 같이 수정 return [response_data,] 이제 정상적으로 접속되고 오류도 발생하지 않음.

수정된 코드:

from wsgiref.simple_server import make_server
from jinja2 import Template

def main_page():
    with open('06jinja2版web框架.html','r',encoding='utf-8')as f:
        content = f.read()
    template = Template(content) # 템플릿 파일 생성
    result = template.render({"user_name":"Dmail","interests":['프로그래밍','대검술']}) # 데이터를 템플릿에 적용
    return result.encode('utf-8')


url_routes = [
    ('/index/',main_page)]

def application(environ,start_response):
    start_response('200 OK',[('Content-Type','text/html;charset=utf-8')])
    path = environ['PATH_INFO'] # 사용자가 요청한 URL 가져오기
    #print(path)
    matched_func = None
    for route in url_routes:
        if route[0] == path:
            matched_func = route[1]
            break
    if matched_func:
        response_data = matched_func()
    else:
        response_data = b'404 not found!'
    return [response_data,]

if __name__ == '__main__':
    server = make_server('127.0.0.1',8090,application)
    print('나는 8090 포트에서 기다리고 있어...')
    server.serve_forever()

서버 로그:

C:\Users\Dmail\AppData\Local\Programs\Python\Python37\python.exe "E:/s9/day60/06 jinja2版web服务端示例.py"
나는 8090 포트에서 기다리고 있어...
127.0.0.1 - - [29/Sep/2019 13:27:37] "GET /index/ HTTP/1.1" 200 213
127.0.0.1 - - [29/Sep/2019 13:27:37] "GET /favicon.ico HTTP/1.1" 200 14
127.0.0.1 - - [29/Sep/2019 13:27:40] "GET /index/ HTTP/1.1" 200 213
127.0.0.1 - - [29/Sep/2019 13:27:40] "GET /favicon.ico HTTP/1.1" 200 14

참고: 오류의 정확한 원인은 명확하지 않았지만, 검색과 수정을 통해 문제를 해결했습니다. 비슷한 오류가 다시 발생할 경우를 대비해 기록으로 남깁니다.

태그: WSGI python 웹 프레임워크 오류 해결

6월 27일 06:36에 게시됨