本文整理汇总了Python中http_parser.parser.HttpParser.get_method方法的典型用法代码示例。如果您正苦于以下问题:Python HttpParser.get_method方法的具体用法?Python HttpParser.get_method怎么用?Python HttpParser.get_method使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类http_parser.parser.HttpParser
的用法示例。
在下文中一共展示了HttpParser.get_method方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_appropriate_response
# 需要导入模块: from http_parser.parser import HttpParser [as 别名]
# 或者: from http_parser.parser.HttpParser import get_method [as 别名]
def get_appropriate_response(self):
try:
# try to use the fast C parser
from http_parser.parser import HttpParser
except ImportError:
# fall back to the Python parser
from http_parser.pyparser import HttpParser
p = HttpParser()
nparsed = p.execute(self.content.encode('utf-8'), len(self.content))
if not p.is_headers_complete():
return HttpResponseBadRequest(content_f=BAD_REQUEST_HTML)
# check method
if p.get_method() not in SUPPORTED_METHODS:
return HttpResponseNotImplemented(content_f=NOT_IMPLEMENTED_HTML)
base_filepath = ''
try:
base_filepath = settings.HOSTS[p.get_headers()['Host'].split(':')[0]]
except KeyError:
base_filepath = settings.HOSTS['default']
req_file = self.content.split(' ')[1]
if req_file == '/':
req_file = '/index.html'
try:
full_path = base_filepath + req_file
open(full_path)
if p.get_method() == 'HEAD':
return HttpResponse(content_f=full_path, method='HEAD')
if 'Range' in p.get_headers():
return HttpResponsePartialContent(content_f=full_path, h_range=p.get_headers()['Range'])
return HttpResponse(content_f=full_path)
except IOError as err:
if err.errno == 13:
return HttpResponseForbidden(content_f=FORBIDDEN_HTML)
elif err.errno == 2:
return HttpResponseNotFound(content_f=NOT_FOUND_HTML)
return HttpResponseServerError(content_f=SERVER_ERROR_HTML)
示例2: parseData
# 需要导入模块: from http_parser.parser import HttpParser [as 别名]
# 或者: from http_parser.parser.HttpParser import get_method [as 别名]
def parseData(self, data, fd):
p = HttpParser()
nparsed = p.execute(data,len(data))
resp = Response()
if self.debugging:
print p.get_method(),p.get_path(),p.get_headers()
if (p.get_method() == 'GET'):
resp = self.handleGet(p, resp)
elif (p.get_method() == 'DELETE'):
resp.setCode(501)
else:
resp.setCode(400)
self.clients[fd].send(str(resp))
try:
self.clients[fd].send(resp.body)
except:
pass
示例3: __init__
# 需要导入模块: from http_parser.parser import HttpParser [as 别名]
# 或者: from http_parser.parser.HttpParser import get_method [as 别名]
def __init__(self, raw):
self.raw = raw
req = HttpParser()
req.execute(raw.request, len(raw.request))
self.headers = req.get_headers()
self.body = b"".join(req._body)
self.url = req.get_url()
self.path = req.get_path()
self.method = req.get_method()
self.arguments = req.get_query_string()
self.slug = [a for a in self.path.split('/') if a != '']
示例4: proxy
# 需要导入模块: from http_parser.parser import HttpParser [as 别名]
# 或者: from http_parser.parser.HttpParser import get_method [as 别名]
def proxy(data):
"""
the function called by tproxy to determine where to send traffic
tproxy will call this function repeatedly for the same connection, as we
receive more incoming data, until we return something other than None.
typically our response tells tproxy where to proxy the connection to, but
may also tell it to hang up, or respond with some error message.
"""
log = logging.getLogger("proxy")
bytes_received = len(data)
parser = HttpParser()
bytes_parsed = parser.execute(data, bytes_received)
if bytes_parsed != bytes_received:
return { 'close':
'HTTP/1.0 400 Bad Request\r\n\r\nParse error' }
if not parser.is_headers_complete():
if bytes_received > MAX_HEADER_LENGTH:
return { 'close':
'HTTP/1.0 400 Bad Request\r\n'
'\r\nHeaders are too large' }
return None
headers = parser.get_headers()
# the hostname may be in the form of hostname:port, in which case we want
# to discard the port, and route just on hostname
route_host = headers.get('HOST', None)
if route_host:
match = _HOST_PORT_REGEXP.match(route_host)
if match:
route_host = match.group(1)
try:
log.debug("Routing %r" % ( parser.get_url(), ))
return _ROUTER.route(
route_host,
parser.get_method(),
parser.get_path(),
parser.get_query_string())
except Exception, err:
log.error("error routing %r, %s" % (
parser.get_url(), traceback.format_exc(), ))
gevent.sleep(ERROR_DELAY)
return { 'close':
'HTTP/1.0 502 Gateway Error\r\n'
'\r\nError routing request' }
示例5: _handle
# 需要导入模块: from http_parser.parser import HttpParser [as 别名]
# 或者: from http_parser.parser.HttpParser import get_method [as 别名]
def _handle(self, source, dest, to_backend, on_between_handle,
data_sent=False):
buffer_size = self.option('buffer')
# Getting the HTTP query and sending it to the backend.
parser = HttpParser()
if not data_sent:
while not parser.is_message_complete():
data = self._get_data(source, buffer_size)
if not data:
return self._close_both(source, dest)
nparsed = parser.execute(data, len(data))
assert nparsed == len(data)
if self.option('overwrite_host_header'):
data = HOST_REPLACE.sub('\r\nHost: %s\r\n'
% self.proxy.backend, data)
dest.sendall(data)
keep_alive_src = parser.should_keep_alive()
method = parser.get_method()
if on_between_handle():
# Getting the HTTP response and sending it back to the source.
parser = HttpParser()
while not (parser.is_message_complete() or
(method == 'HEAD' and parser.is_headers_complete())):
data = self._get_data(dest, buffer_size)
if not data:
return self._close_both(source, dest)
nparsed = parser.execute(data, len(data))
assert nparsed == len(data)
source.sendall(data)
keep_alive_dst = parser.should_keep_alive()
# do we close the client ?
if not keep_alive_src or not self.option('keep_alive'):
source.close()
source._closed = True
if (not keep_alive_dst or not self.option('reuse_socket') or not
self.option('keep_alive')):
dest.close()
dest._closed = True
else:
keep_alive_dst = False
return keep_alive_dst and self.option('keep_alive')
示例6: handleData
# 需要导入模块: from http_parser.parser import HttpParser [as 别名]
# 或者: from http_parser.parser.HttpParser import get_method [as 别名]
def handleData(self,fd):
self.debug("Entering handleData")
if '\r\n\r\n' not in self.con_cache[fd]:
self.debug("Partial message - Exiting handleData")
return
p = HttpParser()
nparsed = p.execute(self.con_cache[fd],len(self.con_cache[fd]))
method = p.get_method()
path = p.get_path()
headers = p.get_headers()
debugStr = "\nMethod: %s\nPath: %s\nHeaders: %s\n" % (method,path,headers)
#self.debug(debugStr)
rangeRequest = None
if 'Range' in headers:
rangeRequest = headers['Range']
self.debug("Range: %s" % (rangeRequest))
validMethods = ['GET','HEAD','PUT','DELETE','POST']
isValid = False
if method not in validMethods:
response = self.makeError('400','Bad Request')
elif method != 'GET' and method != 'HEAD':
response = self.makeError('501','Not Implemented')
else:
if path == '/':
path = '/index.html'
path = self.hosts['default'] + path
(isValid,response) = self.makeResponse(path,rangeRequest)
self.clients[fd].send(response)
self.debug("PATH:%s"%(path))
if isValid and not rangeRequest and method != "HEAD":
self.sendAll(path,fd)
elif isValid and rangeRequest and method != "HEAD":
(start,end) = self.getByteRange(rangeRequest)
self.send(path,fd,start,end)
self.debug("Exiting handleData")
示例7: test_constructor
# 需要导入模块: from http_parser.parser import HttpParser [as 别名]
# 或者: from http_parser.parser.HttpParser import get_method [as 别名]
def test_constructor(self):
''' Instance attributes autosubstitution.
'''
headers = {
'Host': 'httpbin.org',
'Connection': 'close',
}
hc = HttpCompiler(method='PATCH', headers=headers)
qs = '/path/to/check'
req = hc.build_raw(qs)
p = HttpParser()
p.execute(req, len(req))
result_hdrs = p.get_headers()
self.assertTrue(p.get_method(), 'PATCH')
self.assertTrue(all(
[result_hdrs[h] == headers[h] for h in headers.keys()]))
示例8: HttpStream
# 需要导入模块: from http_parser.parser import HttpParser [as 别名]
# 或者: from http_parser.parser.HttpParser import get_method [as 别名]
class HttpStream(object):
""" An HTTP parser providing higher-level access to a readable,
sequential io.RawIOBase object. You can use implementions of
http_parser.reader (IterReader, StringReader, SocketReader) or
create your own.
"""
def __init__(self, stream, kind=HTTP_BOTH, decompress=False):
""" constructor of HttpStream.
:attr stream: an io.RawIOBase object
:attr kind: Int, could be 0 to parseonly requests,
1 to parse only responses or 2 if we want to let
the parser detect the type.
"""
self.parser = HttpParser(kind=kind, decompress=decompress)
self.stream = stream
def _check_headers_complete(self):
if self.parser.is_headers_complete():
return
while True:
try:
next(self)
except StopIteration:
if self.parser.is_headers_complete():
return
raise NoMoreData("Can't parse headers")
if self.parser.is_headers_complete():
return
def _wait_status_line(self, cond):
if self.parser.is_headers_complete():
return True
data = []
if not cond():
while True:
try:
d = next(self)
data.append(d)
except StopIteration:
if self.parser.is_headers_complete():
return True
raise BadStatusLine(b"".join(data))
if cond():
return True
return True
def _wait_on_url(self):
return self._wait_status_line(self.parser.get_url)
def _wait_on_status(self):
return self._wait_status_line(self.parser.get_status_code)
def url(self):
""" get full url of the request """
self._wait_on_url()
return self.parser.get_url()
def path(self):
""" get path of the request (url without query string and
fragment """
self._wait_on_url()
return self.parser.get_path()
def query_string(self):
""" get query string of the url """
self._wait_on_url()
return self.parser.get_query_string()
def fragment(self):
""" get fragment of the url """
self._wait_on_url()
return self.parser.get_fragment()
def version(self):
self._wait_on_status()
return self.parser.get_version()
def status_code(self):
""" get status code of a response as integer """
self._wait_on_status()
return self.parser.get_status_code()
def status(self):
""" return complete status with reason """
status_code = self.status_code()
reason = status_reasons.get(int(status_code), 'unknown')
return "%s %s" % (status_code, reason)
def method(self):
""" get HTTP method as string"""
self._wait_on_status()
return self.parser.get_method()
#.........这里部分代码省略.........
示例9: HTTPProtocol
# 需要导入模块: from http_parser.parser import HttpParser [as 别名]
# 或者: from http_parser.parser.HttpParser import get_method [as 别名]
class HTTPProtocol(FlowControlMixin, asyncio.Protocol):
def __init__(self, stream_reader, callback, loop=None):
super().__init__(loop=loop)
self._stream_reader = stream_reader
self._stream_writer = None
self._callback = callback
self._task = None
self._server = None
def connection_made(self, transport):
self._parser = HttpParser()
self._stream_reader.set_transport(transport)
self._stream_writer = asyncio.StreamWriter(
transport,
self,
self._stream_reader,
self._loop,
)
# Grab the name of our socket if we have it
self._server = transport.get_extra_info("sockname")
def connection_lost(self, exc):
if exc is None:
self._stream_reader.feed_eof()
else:
self._stream_reader.set_exception(exc)
super().connection_lost(exc)
def data_received(self, data):
# Parse our incoming data with our HTTP parser
self._parser.execute(data, len(data))
# If we have not already handled the headers and we've gotten all of
# them, then invoke the callback with the headers in them.
if self._task is None and self._parser.is_headers_complete():
coro = self.dispatch(
{
"server": self._server,
"protocol": b"HTTP/" + b".".join(
str(x).encode("ascii")
for x in self._parser.get_version()
),
"method": self._parser.get_method().encode("latin1"),
"path": self._parser.get_path().encode("latin1"),
"query": self._parser.get_query_string().encode("latin1"),
"headers": self._parser.get_headers(),
},
self._stream_reader,
self._stream_writer,
)
self._task = asyncio.Task(coro, loop=self._loop)
# Determine if we have any data in the body buffer and if so feed it
# to our StreamReader
if self._parser.is_partial_body():
self._stream_reader.feed_data(self._parser.recv_body())
# Determine if we've completed the end of the HTTP request, if we have
# then we should close our stream reader because there is nothing more
# to read.
if self._parser.is_message_complete():
self._stream_reader.feed_eof()
def eof_received(self):
# We've gotten an EOF from the client, so we'll propagate this to our
# StreamReader
self._stream_reader.feed_eof()
@asyncio.coroutine
def dispatch(self, request, request_body, response):
# Get the status, headers, and body from the callback. The body must
# be iterable, and each item can either be a bytes object, or an
# asyncio coroutine, in which case we'll ``yield from`` on it to wait
# for it's value.
status, resp_headers, body = yield from self._callback(
request,
request_body,
)
# Write out the status line to the client for this request
# TODO: We probably don't want to hard code HTTP/1.1 here
response.write(b"HTTP/1.1 " + status + b"\r\n")
# Write out the headers, taking special care to ensure that any
# mandatory headers are added.
# TODO: We need to handle some required headers
for key, values in resp_headers.items():
# In order to handle headers which need to have multiple values
# like Set-Cookie, we allow the value of the header to be an
# iterable instead of a bytes object, in which case we'll write
# multiple header lines for this header.
if isinstance(values, (bytes, bytearray)):
values = [values]
#.........这里部分代码省略.........
示例10: HttpParser
# 需要导入模块: from http_parser.parser import HttpParser [as 别名]
# 或者: from http_parser.parser.HttpParser import get_method [as 别名]
while True:
(clientsocket, address) = serversocket.accept()
parser = HttpParser()
body = []
while True:
data = clientsocket.recv(1024)
if not data:
break
recved = len(data)
nparsed = parser.execute(data, recved)
assert nparsed == recved
if parser.is_headers_complete():
print parser.get_method()
print parser.get_path()
if parser.is_partial_body():
body.append(parser.recv_body())
if parser.is_message_complete():
break
print ''.join(body)
result = process_request(parser.get_method(),
parser.get_path(),
dict([x.split('=') for x in ''.join(body).split('&') if len(x.split('=')) == 2]))
result += '\n'
clientsocket.send(response + str(result))
示例11: handle_read
# 需要导入模块: from http_parser.parser import HttpParser [as 别名]
# 或者: from http_parser.parser.HttpParser import get_method [as 别名]
def handle_read(self):
try:
logging.debug('Connection.handle_read - id=%d' % self.id)
b = self.sock.recv(2048)
logging.debug('Connection.handle_read - received buffer size is %d bytes' % len(b))
logging.debug('Connection.handle_read - received buffer is : \n%s' % b)
if not len(b):
logging.debug('Connection.handle_read - 0 bytes received on %d. closing' %
self.id)
self.close()
return
self.read_buf += b
except socket.error as err:
if err.args[0] not in NONBLOCKING:
self.handle_error('%s' % args[1])
else :
logging.error('Connection.handle_read - NONBLOCKING event on read : %s' % args[1])
else:
# check if we have a full http request
parser = HttpParser()
recved = len(self.read_buf)
nparsed = parser.execute(self.read_buf, recved)
assert nparsed == recved
if not parser.is_message_complete():
# we got a partial request keep on reading
logging.debug(
'Connection.handle_read - partial buffer received : \n%s' %
self.read_buf)
self.reset(pyev.EV_READ)
else :
# we got a full request
self.read_buf = ''
# match the verb with URI and call
# after that register for write to send response
verb = parser.get_method()
url = parser.get_path()
logging.debug('Connection.handle_read - id %d - method is %s and url %s' %
(self.id, verb, url))
call, keyword_args = register.get_callable(url, verb)
if not call :
err = HttpResponse()
err.status_code = 404
err.status_string = 'Not Found'
err.headers['Content-Type'] = 'application/txt'
err.body = 'URI Not Found\r\n'
self.write_buf = err.to_string()
else :
keyword_args['http_request'] = parser
logging.debug('Connection.handle_read - kargs=%s' % keyword_args)
try :
response = call(*[register.handler,], **keyword_args)
self.write_buf = response.to_string()
except :
err = HttpResponse()
err.status_code = 500
err.status_string = 'Internal Server Error'
err.headers['Content-Type'] = 'application/txt'
err.body = 'Upsssss.\r\n'
self.write_buf = err.to_string()
logging.debug('Connection.handle_read - requesting write %d' % self.id)
self.reset(pyev.EV_WRITE)
示例12: handleRequest
# 需要导入模块: from http_parser.parser import HttpParser [as 别名]
# 或者: from http_parser.parser.HttpParser import get_method [as 别名]
def handleRequest(self,data):
"""Prcess the request made by the client and send the response"""
Debug.dprint("POLLER::handleRequest()")
self.headers = {}
self.headers['Server'] = "SimpleHTTP/0.6 Python/2.7.9"
self.headers['Date'] = strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime())
#self.headers['Connection'] = "close"
p = HttpParser()
nparsed = p.execute(data,len(data))
method = p.get_method()
path = p.get_path()
headers = p.get_headers()
Debug.dprint("POLLER::handleClient()::get_method= " + str(p.get_method()))
Debug.dprint("POLLER::handleClient()::get_path= " + str(p.get_path()))
Debug.dprint("POLLER::handleClient()::get_headers= " + str(p.get_headers()))
"""Check the Method, if not GET return 501"""
if method != 'GET':
return self.response501()
"""Determine Host"""
if headers.has_key('Host'):
Debug.dprint("POLLER::Host= " + headers['Host'])
RootDir = ""
if headers['Host'].find("localhost") != -1 and configHost.has_key('localhost'):
RootDir = configHost['localhost']
else:
RootDir = configHost['default']
else:
RootDir = configHost['default']
"""Find requested Resource"""
if path == "/":
path = "/index.html"
try:
dataType = ""
if path.find('.') != -1:
pathObjects = path.split('.')
dataType = str(pathObjects[len(pathObjects) - 1])
if configMedia.has_key(dataType):
self.headers['Content-Type'] = configMedia[dataType]
else:
self.headers['Content-Type'] = "text/plain"
fileName = RootDir + path
"""See if the requested file actually exists"""
if not os.path.isfile(fileName):
return self.response404()
"""Check if we have permissions to open the file"""
if not os.access(fileName, os.R_OK):
return self.response403()
fileReader = open(fileName, 'rb')
body = fileReader.read()
self.headers['Content-Length'] = os.stat(fileName).st_size
self.headers['Last-Modified'] = strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime(os.stat(fileName).st_mtime))
response = "HTTP/1.1 200 OK\r\n"
for key in self.headers:
response += str(key) + ": " + str(self.headers[key]) + "\r\n"
Debug.dprint("POLLER::responseHeader: " + str(key) + ": " + str(self.headers[key]))
"""response += "Date: " + str(self.headers['Date']) + "\r\n"
response += "Server: " + str(self.headers['Server']) + "\r\n"
response += "Content-Type: " + str(self.headers['Content-Type']) + "\r\n"
response += "Content-Length: " + str(self.headers['Content-Length']) + "\r\n"
response += "Last-Modified: " + str(self.headers['Last-Modified']) + "\r\n"""
response += "\r\n"
response += str(body)
return response
except IOError:
return self.response500()
示例13: handleRequest
# 需要导入模块: from http_parser.parser import HttpParser [as 别名]
# 或者: from http_parser.parser.HttpParser import get_method [as 别名]
def handleRequest(self, data):
#should only get here if the request is completed to the double line return
Debug.dprint("POLLER::handleRequest:data->" + str(data) + "<-data")
#create and serve the clients request
self.respHeaders = {}
self.respHeaders['Server'] = "SimpleHTTP/0.6 Python/2.7.9"
self.respHeaders['Date'] = strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime())
#parse the data (GET header)
try:
from http_parser.parser import HttpParser
except ImportError:
from http_parser.pyparser import HttpParser
p = HttpParser()
nparsed = p.execute(data,len(data))
#print basic debug from http parser
Debug.dprint("POLLER::handleRequest:HttpParser:get_method()->" + p.get_method())
Debug.dprint("POLLER::handleRequest:HttpParser:get_path()->" + p.get_path())
Debug.dprint("POLLER::handleRequest:HttpParser:get_headers()\n")
dataHeaders = p.get_headers()
for i in dataHeaders:
Debug.dprint(i + ":" + dataHeaders[i])
#assign from http parser, headers grabbed previously
method = p.get_method();
path = p.get_path();
#check for GET, if not return 501
if method != 'GET':
return self.code501();
#identify host
if dataHeaders.has_key('Host'):
#if a host key is present
Debug.dprint("POLLER::handleRequest:Host->" + dataHeaders['Host'])
#check for the host key in the config dictionary
if configHost.has_key(dataHeaders['Host']):
#if the specified host is in the config dictionary, make the root directory the path assiated with requested host
rootDir = configHost[dataHeaders['Host']]
else:
#if the specified host is not in the config dictionary, set to default??? THIS MAY NEED TO BE AN ERROR
rootDir = configHost['default']
else:
#if a host key is not present
rootDir = configHost['default']
#identify requested file
#for the case of an empty path, point to index
if path =="/":
#if the path is blank, set the path to index.html
path = "/index.html"
#attempt to retreive the file
try:
#identify the type of file
fileType = ""
if path.find('.') != -1:
#split at the file extention period and isolate the filetype
pathSplit = path.split('.')
fileType = str(pathSplit[len(pathSplit) - 1])
Debug.dprint("POLLER::handleRequest:fileType->" + str(fileType));
#assign a MIME type from the condif dictionary
if configMedia.has_key(fileType):
self.respHeaders['Content-Type'] = configMedia[fileType]
else:
self.respHeaders['Content-Type'] = "test/plain"
#check if the file excists, if not throw code 404
#create filepath
filePath = rootDir + path
Debug.dprint("POLLER::handleRequest:filePath->" + str(filePath));
if not os.path.isfile(filePath):
return self.code404()
#check for permissions, if not throw code 403
if not os.access(filePath, os.R_OK):
return self.code403()
#read file as binary into a body variable
fileReader = open(filePath, 'rb')
respBody = fileReader.read()
except IOError:
return self.code500()
#.........这里部分代码省略.........
示例14: HttpProxyProtocol
# 需要导入模块: from http_parser.parser import HttpParser [as 别名]
# 或者: from http_parser.parser.HttpParser import get_method [as 别名]
class HttpProxyProtocol(asyncio.Protocol):
''' Implement HTTP(S) proxy behavior. '''
def __init__(self, loop, config, token_store):
''' Constructor. '''
self._parser = HttpParser()
self._body = b''
self._config = config
self._loop = loop
self._mitm = None
self._mitm_host = None
self._token_store = token_store
self._instagram = InstagramApi(
client_id=config['Instagram']['ClientID'],
client_secret=config['Instagram']['ClientSecret'],
)
self._twitter = TwitterApi(
consumer_key=config['Twitter']['ConsumerKey'],
consumer_secret=config['Twitter']['ConsumerSecret'],
app_token=config['Twitter']['AppToken'],
app_token_secret=config['Twitter']['AppTokenSecret'],
)
def connection_made(self, transport):
''' Save a reference to the transport so that we can send a reply. '''
log.debug('Connection opened.')
self._transport = transport
def connection_lost(self, exc):
log.debug('Connection closed.')
def data_received(self, data):
''' Parse incoming HTTP request. '''
log.debug('Data received: {}'.format(data))
self._parser.execute(data, len(data))
if self._parser.is_partial_body():
self._body += self._parser.recv_body()
if self._parser.is_message_complete():
method = self._parser.get_method()
uri = self._parser.get_url()
version = self._parser.get_version()
headers = self._parser.get_headers()
content_type = headers.get('Content-type', '')
charset = _get_charset(content_type)
body = self._body.decode(charset)
log.debug('Client charset: {}'.format(charset))
log.debug('Client status: method={} uri={} version={}' \
.format(method, uri, version))
log.debug('Client headers: {}'.format(headers))
log.debug('Client body: {}...'.format(body[:1000]))
if method == 'CONNECT':
asyncio.async(self._start_mitm(uri, version))
self._parser = HttpParser()
else:
asyncio.async(
self._request_upstream(
method,
uri,
version,
headers,
body
)
)
def start_tls(self, version):
'''
Initiate TLS session with the client.
This part is completely hacky! We mess around with the
transport's internals in order to wrap the current transport in TLS.
Python doesn't have an official way to do this, although it *might*
get fixed in 3.6: http://bugs.python.org/issue23749
'''
log.debug('The proxy is starting TLS with its client.')
status_line = 'HTTP/{}.{} {} {}\r\n\r\n' \
.format(version[0], version[1], 200, 'OK')
self._transport.write(status_line.encode('ascii'))
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
ssl_context.set_ciphers('HIGH:!aNull:!eNull')
ssl_context.load_cert_chain('ssl/server.crt', 'ssl/server.key')
original_socket = self._transport._sock
self._transport = self._loop._make_ssl_transport(
original_socket,
self,
ssl_context,
server_side=True
)
#.........这里部分代码省略.........
示例15: parseRequest
# 需要导入模块: from http_parser.parser import HttpParser [as 别名]
# 或者: from http_parser.parser.HttpParser import get_method [as 别名]
def parseRequest(self, data):
if (self.debug):
print "entering parse Request--------\n"
# Create a parser object
try:
from http_parser.parser import HttpParser
except ImportError:
from http_parser.pyparser import HttpParser
parser = HttpParser()
nparser = parser.execute(data, len(data))
response = None
path = None
host = None
isRangeReq = None
isHeadReq = False
# Get Protocol Version
version = "HTTP/1.1"
#check if request is valid
method = parser.get_method()
if method not in self.validMethods:
if (self.debug):
print "received a non valid method: %s\n" %method
response = self.createError("400", "Bad Request")
elif method != "GET" and method != "HEAD":
if (self.debug):
print "received a method which we do not implement\n"
response = self.createError("501", "Not Implemented")
else:
if method == "HEAD":
isHeadReq = True
url = parser.get_path()
# Check for url errors
if (url == ""):
if self.debug:
print "url is empty\n"
resposne = self.createError("400", "Bad Request")
elif (url == "/"):
url = "/index.html"
headers = parser.get_headers()
if "Range" in headers:
isRangeReq = headers["Range"]
if self.debug:
print "Range Request = %s" %isRangeReq
#get Host
if "Host" in headers:
host = headers["Host"].split(':')[0]
if (self.debug):
print "host is: %s\n"%host
# Handle errors in host
if host not in self.hosts:
if 'default' not in self.hosts:
if self.debug:
print " not host or default\n"
response = self.createError("400", "Bad Request")
else:
# Use the default host
if self.debug:
print "using default host\n"
path = self.hosts['default']
if (self.debug):
print "path is: %s\n"%path
path += url
if (self.debug):
print "full path is: %s\n"%path
response = self.createResponse(path, isRangeReq)
else: #use given host
path = self.hosts[host]
if (self.debug):
print "path is: %s\n"%path
path += url
if (self.debug):
print "full path is: %s\n"%path
response = self.createResponse(path, isRangeReq)
if isHeadReq:
path = None
#.........这里部分代码省略.........