Skip to content
This repository was archived by the owner on Feb 21, 2024. It is now read-only.

Py3 resolve conflicts #1

Merged
merged 7 commits into from
Apr 9, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 54 additions & 37 deletions UniversalAnalytics/HTTPLog.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,47 @@
#!/usr/bin/python

###############################################################################
#
# Formatting filter for urllib2's HTTPHandler(debuglevel=1) output
# Copyright (c) 2013, Analytics Pros
#
# This project is free software, distributed under the BSD license.
# Analytics Pros offers consulting and integration services if your firm needs
#
# This project is free software, distributed under the BSD license.
# Analytics Pros offers consulting and integration services if your firm needs
# assistance in strategy, implementation, or auditing existing work.
#
###############################################################################

# Standard library imports
from __future__ import division, print_function, with_statement
import re
import sys

import sys, re, os
from cStringIO import StringIO

# Third party libraries
from six.moves import cStringIO as StringIO # Used by tests
import six


class BufferTranslator(object):
""" Provides a buffer-compatible interface for filtering buffer content.
"""
Provides a buffer-compatible interface for filtering buffer content.
"""
parsers = []

@staticmethod
def stripslashes(content):
if six.PY3:
content = content.encode('UTF-8')
return content.decode('unicode_escape')
else:
return content.decode('string_escape')

@staticmethod
def addslashes(content):
if six.PY3:
return content.encode('unicode_escape')
else:
return content.encode('string_escape')

def __init__(self, output):
self.output = output
self.encoding = getattr(output, 'encoding', None)
Expand All @@ -27,56 +50,51 @@ def write(self, content):
content = self.translate(content)
self.output.write(content)


@staticmethod
def stripslashes(content):
return content.decode('string_escape')

@staticmethod
def addslashes(content):
return content.encode('string_escape')

def translate(self, line):
for pattern, method in self.parsers:
match = pattern.match(line)
if match:
return method(match)

return line


def flush(self):
pass


class LineBufferTranslator(BufferTranslator):
""" Line buffer implementation supports translation of line-format input
even when input is not already line-buffered. Caches input until newlines
occur, and then dispatches translated input to output buffer.
"""
def __init__(self, *a, **kw):
Line buffer implementation supports translation of line-format input
even when input is not already line-buffered. Caches input until newlines
occur, and then dispatches translated input to output buffer.
"""
def __init__(self, *args, **kwargs):
self._linepending = []
super(LineBufferTranslator, self).__init__(*a, **kw)
super(LineBufferTranslator, self).__init__(*args, **kwargs)

def write(self, _input):
lines = _input.splitlines(True)
last = 0
for i in range(0, len(lines)):
last = i
if lines[i].endswith('\n'):
prefix = len(self._linepending) and ''.join(self._linepending) or ''
prefix = (len(self._linepending) and
''.join(self._linepending) or '')
self.output.write(self.translate(prefix + lines[i]))
del self._linepending[0:]
last = -1

if last >= 0:
self._linepending.append(lines[ last ])

if lines and last >= 0:
self._linepending.append(lines[last])

def __del__(self):
if len(self._linepending):
self.output.write(self.translate(''.join(self._linepending)))


class HTTPTranslator(LineBufferTranslator):
""" Translates output from |urllib2| HTTPHandler(debuglevel = 1) into
HTTP-compatible, readible text structures for human analysis.
"""
Translates output from |urllib2| HTTPHandler(debuglevel = 1) into
HTTP-compatible, readible text structures for human analysis.
"""

RE_LINE_PARSER = re.compile(r'^(?:([a-z]+):)\s*(\'?)([^\r\n]*)\2(?:[\r\n]*)$')
Expand All @@ -89,14 +107,13 @@ def spacer(cls, line):
return cls.RE_PARAMETER_SPACER.sub(r' &\1= ', line)

def translate(self, line):

parsed = self.RE_LINE_PARSER.match(line)

if parsed:
value = parsed.group(3)
stage = parsed.group(1)

if stage == 'send': # query string is rendered here
if stage == 'send': # query string is rendered here
return '\n# HTTP Request:\n' + self.stripslashes(value)
elif stage == 'reply':
return '\n\n# HTTP Response:\n' + self.stripslashes(value)
Expand All @@ -105,17 +122,17 @@ def translate(self, line):
else:
return value


return line


def consume(outbuffer = None): # Capture standard output
def consume(outbuffer=None):
"""
Capture standard output.
"""
sys.stdout = HTTPTranslator(outbuffer or sys.stdout)
return sys.stdout


if __name__ == '__main__':
consume(sys.stdout).write(sys.stdin.read())
print '\n'

# vim: set nowrap tabstop=4 shiftwidth=4 softtabstop=0 expandtab textwidth=0 filetype=python foldmethod=indent foldcolumn=4
print('\n')
Loading