2017-02-11 9 views
4

Flask用のローカルHTTPサーバーを作成しようとしています。バイト状のオブジェクトは 'str'でなくてもかまいません

Serverが正常に起動しますが、私はlocalhostを実行しようとすると:-------------- Webブラウザでの5000を私は、このエラーに


class webserverhandler(BaseHTTPRequestHandler): 

def do_GET(self): 
    try: 
     if self.path.endswith("/"): 
      self.send_response(200) 
      self.send_header('Content-Type','text/html') 
      self.end_headers() 

      output="" 
      output+="<html><body>Hello</body></html>" 

      self.wfile.write(output) 
      print (output) 
      return 

    except IOError: 
     self.send_error(404,"File Not Found %s" % self.path) 


def main(): 
try: 
    port=5000 
    server=HTTPServer(('',port),webserverhandler) 
    print ("webserver running on %s" % port) 
    server.serve_forever() 


except KeyboardInterrupt: 
    server.socket.close() 

を取得 - - - - - - - - - - エラー - - - - - - - - - - - - - - - ------------

webserver running on 5000 
127.0.0.1 - - [11/Feb/2017 17:59:36] "GET/HTTP/1.1" 200 - 
Exception happened during processing of request from ('127.0.0.1', 54027) 
Traceback (most recent call last): 
File "C:\Users\Jordan\AppData\Local\Programs\Python\Python36-32\lib\socketserver.py", line 317, in _handle_request_noblock 
self.process_request(request, client_address) 
File "C:\Users\Jordan\AppData\Local\Programs\Python\Python36-32\lib\socketserver.py", line 348, in process_request 
self.finish_request(request, client_address) 
File "C:\Users\Jordan\AppData\Local\Programs\Python\Python36-32\lib\socketserver.py", line 361, in finish_request 
self.RequestHandlerClass(request, client_address, self) 
File "C:\Users\Jordan\AppData\Local\Programs\Python\Python36-32\lib\socketserver.py", line 696, in __init__ 
self.handle() 
File "C:\Users\Jordan\AppData\Local\Programs\Python\Python36-32\lib\http\server.py", line 418, in handle 
self.handle_one_request() 
File "C:\Users\Jordan\AppData\Local\Programs\Python\Python36-32\lib\http\server.py", line 406, in handle_one_request 
method() 
File "webserver.py", line 14, in do_GET 
self.wfile.write(output) 
File "C:\Users\Jordan\AppData\Local\Programs\Python\Python36-32\lib\socketserver.py", line 775, in write 
self._sock.sendall(b) 
TypeError: a bytes-like object is required, not 'str' 

誰も私を助けることができますか?

+3

あなたが '' self.wfile.write(output.encodeを())しようとしたしましたか? –

答えて

5

あなたはこのようbytes_objectにあなたのoutput変数をエンコードすることができます

self.wfile.write(output.encode()) 
3

Python3を使用しているようですが、デフォルトでは文字列リテラルはUnicode(str)オブジェクトです。 bytes -objectを作成するためにb -prefix

output = b"" 
output += b"<html><body>Hello</body></html>" 

を使用してください。

+0

ありがとうございました – Zordan

関連する問題