python http服务器求助
自己写了一个http服务器,如果客户端有请求的话,就给客户端回一段固定字符,在python3下,self.wfile.write( b'res' )里面带的必须是bytes,请教一下怎么讲变量res里面的内容带回去?
另外再请教一下,怎么获取请求报文?
python版本:python 3.3
from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer
from socketserver import ThreadingMixIn
hostIP = ''
portNum = 8080
class mySoapServer( BaseHTTPRequestHandler ):
def do_head( self ):
pass
def do_GET( self ):
try:
self.send_response( 200, message = None )
self.send_header( 'Content-type', 'text/html' )
self.end_headers()
res = '''
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><META content="IE=5.0000" http-equiv="X-UA-Compatible">
<META content="text/html; charset=gb2312" http-equiv=Content-Type>
</HEAD>
<BODY>
hello, This is a test!
</BODY>
</HTML>
'''
self.wfile.write( b'res' )
except IOError:
self.send_error( 404, message = None )
class ThreadingHttpServer( ThreadingMixIn, HTTPServer ):
pass
myServer = ThreadingHttpServer( ( hostIP, portNum ), mySoapServer )
myServer.serve_forever()
myServer.server_close()
In [40]: res = '''
...: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
...: <HTML>
...: <HEAD><META content="IE=5.0000" http-equiv="X-UA-Compatible">
...: <META content="text/html; charset=gb2312" http-equiv=Content-Type>
...: </HEAD>
...: <BODY>
...: hello, This is a test!
...: </BODY>
...: </HTML>
...: '''
In [41]: type(res)
Out[41]: builtins.str
In [42]: type(res.encode('utf-8'))
Out[42]: builtins.bytes
In [43]: type(res.encode('ascii'))
Out[43]: builtins.bytes
In [44]: res.encode?
Type: builtin_function_or_method
String Form:<built-in method encode of str object at 0x404d340>
Docstring:
S.encode(encoding='utf-8', errors='strict') -> bytes
Encode S using the codec registered for encoding. Default encoding
is 'utf-8'. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that can handle UnicodeEncodeErrors.