Fix python3 compatibility issue

This change fix python3 compatibility:
* replace except obj, name with except obj as name
* use print function
* replace iteritems by six.iteritems
* replace xrange by range
* convert items() result to list

Change-Id: I70364e47541274d446c4449f820dce3e0b331b27
This commit is contained in:
Tristan Cacqueray 2019-09-25 14:42:32 +00:00 committed by Monty Taylor
parent 2d4b0ebee6
commit 9b854e7729
18 changed files with 64 additions and 40 deletions

View File

@ -3,8 +3,9 @@
jobs: jobs:
- tox-pep8 - tox-pep8
- tox-py27 - tox-py27
- tox-py36
gate: gate:
jobs: jobs:
- tox-pep8 - tox-pep8
- tox-py27 - tox-py27
- tox-py36

View File

@ -64,7 +64,7 @@ class LodgeIt(object):
except NotFound: except NotFound:
handler = get_controller('static/not_found') handler = get_controller('static/not_found')
resp = handler() resp = handler()
except HTTPException, e: except HTTPException as e:
resp = e.get_response(environ) resp = e.get_response(environ)
else: else:
expires = datetime.utcnow() + timedelta(days=31) expires = datetime.utcnow() + timedelta(days=31)

View File

@ -8,6 +8,7 @@
:copyright: 2007-2010 by Armin Ronacher, Christopher Grebs. :copyright: 2007-2010 by Armin Ronacher, Christopher Grebs.
:license: BSD :license: BSD
""" """
import six
import sys import sys
from types import ModuleType from types import ModuleType
import sqlalchemy import sqlalchemy
@ -46,7 +47,7 @@ ModelBase.query = session.query_property()
def _make_module(): def _make_module():
db = ModuleType('db') db = ModuleType('db')
for mod in sqlalchemy, orm: for mod in sqlalchemy, orm:
for key, value in mod.__dict__.iteritems(): for key, value in six.iteritems(mod.__dict__):
if key in mod.__all__: if key in mod.__all__:
setattr(db, key, value) setattr(db, key, value)

View File

@ -11,6 +11,7 @@
import os import os
from babel import Locale, dates, UnknownLocaleError from babel import Locale, dates, UnknownLocaleError
from babel.support import Translations from babel.support import Translations
from six import text_type
from lodgeit import local from lodgeit import local
@ -65,7 +66,7 @@ def list_languages():
continue continue
try: try:
locale = Locale.parse(filename) locale = Locale.parse(filename)
except UnknownLocaleError: except (UnknownLocaleError, ValueError):
continue continue
languages.append((str(locale), locale.display_name)) languages.append((str(locale), locale.display_name))
@ -109,7 +110,7 @@ class _TranslationProxy(object):
return bool(self.value) return bool(self.value)
def __dir__(self): def __dir__(self):
return dir(unicode) return dir(text_type)
def __iter__(self): def __iter__(self):
return iter(self.value) return iter(self.value)
@ -121,7 +122,7 @@ class _TranslationProxy(object):
return str(self.value) return str(self.value)
def __unicode__(self): def __unicode__(self):
return unicode(self.value) return text_type(self.value)
def __add__(self, other): def __add__(self, other):
return self.value + other return self.value + other
@ -169,7 +170,7 @@ class _TranslationProxy(object):
def __repr__(self): def __repr__(self):
try: try:
return 'i' + repr(unicode(self.value)) return 'i' + repr(text_type(self.value))
except ValueError: except ValueError:
return '<%s broken>' % self.__class__.__name__ return '<%s broken>' % self.__class__.__name__

View File

@ -24,6 +24,11 @@ try:
except ImportError: except ImportError:
from sha import new as sha1 from sha import new as sha1
try:
xrange
except NameError:
xrange = range
resource_path = abspath(join(dirname(__file__), pardir, 'res')) resource_path = abspath(join(dirname(__file__), pardir, 'res'))

View File

@ -8,6 +8,8 @@
:copyright: 2008 by Christopher Grebs. :copyright: 2008 by Christopher Grebs.
:license: BSD. :license: BSD.
""" """
import six
from lodgeit.i18n import _ from lodgeit.i18n import _
from lodgeit.utils import render_template from lodgeit.utils import render_template
@ -71,7 +73,7 @@ class Filterable(object):
return ret return ret
def get_objects(self): def get_objects(self):
for field, filter in self.filters.iteritems(): for field, filter in six.iteritems(self.filters):
action, value = filter action, value = filter
if value: if value:
func = ACTIONS_MAP[action] func = ACTIONS_MAP[action]

View File

@ -9,6 +9,7 @@
:license: BSD :license: BSD
""" """
import re import re
import six
import pygments import pygments
import csv import csv
from operator import itemgetter from operator import itemgetter
@ -195,7 +196,7 @@ def get_style(request=None, name_only=False):
request = request or local.request request = request or local.request
if not request: if not request:
style_name = DEFAULT_STYLE style_name = DEFAULT_STYLE
elif isinstance(request, basestring): elif isinstance(request, six.string_types):
style_name = request style_name = request
else: else:
style_name = request.cookies.get('style') style_name = request.cookies.get('style')
@ -251,6 +252,6 @@ def get_known_alias(lexer, default='text'):
def list_languages(): def list_languages():
"""List all languages.""" """List all languages."""
languages = LANGUAGES.items() languages = list(LANGUAGES.items())
languages.sort(key=lambda x: x[1].lstrip(' _-.').lower()) languages.sort(key=lambda x: x[1].lstrip(' _-.').lower())
return languages return languages

View File

@ -42,7 +42,7 @@ class JSONRequestHandler(object):
'data': self.funcs[method_name](*args, **kwargs), 'data': self.funcs[method_name](*args, **kwargs),
'error': None 'error': None
} }
except Exception, e: except Exception as e:
response = {'data': None, 'error': str(e).decode('utf-8')} response = {'data': None, 'error': str(e).decode('utf-8')}
body = dumps(response, indent=local.request.is_xhr and 2 or 0) body = dumps(response, indent=local.request.is_xhr and 2 or 0)
return Response(body + '\n', mimetype='application/json') return Response(body + '\n', mimetype='application/json')

View File

@ -9,6 +9,7 @@
:license: BSD. :license: BSD.
""" """
import inspect import inspect
import six
from lodgeit.models import Paste from lodgeit.models import Paste
from lodgeit.database import db from lodgeit.database import db
from lodgeit.lib.xmlrpc import XMLRPCRequestHandler from lodgeit.lib.xmlrpc import XMLRPCRequestHandler
@ -39,7 +40,7 @@ def get_public_methods():
global _public_methods global _public_methods
if _public_methods is None: if _public_methods is None:
result = [] result = []
for name, f in json.funcs.iteritems(): for name, f in six.iteritems(json.funcs):
if name.startswith('system.') or f.hidden: if name.startswith('system.') or f.hidden:
continue continue
args, varargs, varkw, defaults = inspect.getargspec(f) args, varargs, varkw, defaults = inspect.getargspec(f)
@ -130,14 +131,14 @@ def pastes_get_last():
def pastes_get_languages(): def pastes_get_languages():
"""Get a list of supported languages.""" """Get a list of supported languages."""
# this resolves lazy translations # this resolves lazy translations
return dict((key, unicode(value)) for return dict((key, six.text_type(value)) for
key, value in LANGUAGES.iteritems()) key, value in six.iteritems(LANGUAGES))
@exported('styles.getStyles') @exported('styles.getStyles')
def styles_get_styles(): def styles_get_styles():
"""Get a list of supported styles.""" """Get a list of supported styles."""
return STYLES.items() return list(STYLES.items())
@exported('styles.getStylesheet') @exported('styles.getStylesheet')

View File

@ -10,7 +10,10 @@
""" """
import sys import sys
import re import re
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher try:
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
except ImportError:
from xmlrpc.server import SimpleXMLRPCDispatcher
from werkzeug import Response from werkzeug import Response
from lodgeit import local from lodgeit import local

View File

@ -11,6 +11,7 @@
import time import time
import difflib import difflib
from datetime import datetime from datetime import datetime
from six import string_types
from werkzeug import cached_property from werkzeug import cached_property
from lodgeit import local from lodgeit import local
@ -56,7 +57,7 @@ class Paste(db.Model):
"""Return the paste for an identifier. Private pastes must be loaded """Return the paste for an identifier. Private pastes must be loaded
with their unique hash and public with the paste id. with their unique hash and public with the paste id.
""" """
if isinstance(identifier, basestring) and not identifier.isdigit(): if isinstance(identifier, string_types) and not identifier.isdigit():
query = Paste.query.filter_by(private_id=identifier) query = Paste.query.filter_by(private_id=identifier)
else: else:
query = Paste.query.filter_by(paste_id=int(identifier)) query = Paste.query.filter_by(paste_id=int(identifier))

View File

@ -8,6 +8,7 @@
:copyright: 2007-2008 by Christopher Grebs. :copyright: 2007-2008 by Christopher Grebs.
:license: BSD :license: BSD
""" """
import base64
import re import re
import time import time
from os import path from os import path
@ -49,14 +50,16 @@ jinja_environment.globals['url_for'] = url_for
def generate_user_hash(): def generate_user_hash():
"""Generates an more or less unique SHA1 hash.""" """Generates an more or less unique SHA1 hash."""
return sha1('%s|%s' % (random(), time.time())).hexdigest() hash_base = '%s|%s' % (random(), time.time())
return sha1(hash_base.encode()).hexdigest()
def generate_paste_hash(): def generate_paste_hash():
"""Generates a more or less unique-truncated SHA1 hash.""" """Generates a more or less unique-truncated SHA1 hash."""
while 1: while 1:
digest = sha1('%s|%s' % (random(), time.time())).digest() hash_base = '%s|%s' % (random(), time.time())
val = _word_only(digest.encode('base64').strip())[:20] digest = sha1(hash_base.encode()).digest()
val = _word_only(str(base64.b64encode(digest)).strip())[:20]
# sanity check. number only not allowed (though unlikely) # sanity check. number only not allowed (though unlikely)
if not val.isdigit(): if not val.isdigit():
return val return val

View File

@ -24,7 +24,7 @@
</p> </p>
<pre class="sample">{% filter escape %} <pre class="sample">{% filter escape %}
>>> paste = s.pastes.getPaste(23) >>> paste = s.pastes.getPaste(23)
>>> print paste['code'] >>> print(paste['code'])
'{{ "{% if users %}" }}\n...' '{{ "{% if users %}" }}\n...'
{% endfilter %}</pre> {% endfilter %}</pre>
<h3>{% trans %}JSON Quickstart{% endtrans %}</h3> <h3>{% trans %}JSON Quickstart{% endtrans %}</h3>

View File

@ -1,3 +1,4 @@
six
Jinja2 Jinja2
Werkzeug<0.16 Werkzeug<0.16
Pygments Pygments

View File

@ -22,8 +22,10 @@
2006 Matt Good <matt@matt-good.net>, 2006 Matt Good <matt@matt-good.net>,
2005 Raphael Slinckx <raphael@slinckx.net> 2005 Raphael Slinckx <raphael@slinckx.net>
""" """
from __future__ import print_function
import os import os
import sys import sys
from six import text_type
from optparse import OptionParser from optparse import OptionParser
@ -39,7 +41,7 @@ _server_name = None
def fail(msg, code): def fail(msg, code):
"""Bail out with an error message.""" """Bail out with an error message."""
print >> sys.stderr, 'ERROR: %s' % msg print('ERROR: %s' % msg, file=sys.stderr)
sys.exit(code) sys.exit(code)
@ -83,14 +85,14 @@ def load_default_settings():
def make_utf8(text, encoding): def make_utf8(text, encoding):
"""Convert a text to UTF-8, brute-force.""" """Convert a text to UTF-8, brute-force."""
try: try:
u = unicode(text, 'utf-8') u = text_type(text, 'utf-8')
uenc = 'utf-8' uenc = 'utf-8'
except UnicodeError: except UnicodeError:
try: try:
u = unicode(text, encoding) u = text_type(text, encoding)
uenc = 'utf-8' uenc = 'utf-8'
except UnicodeError: except UnicodeError:
u = unicode(text, 'iso-8859-15', 'ignore') u = text_type(text, 'iso-8859-15', 'ignore')
uenc = 'iso-8859-15' uenc = 'iso-8859-15'
try: try:
import chardet import chardet
@ -99,7 +101,7 @@ def make_utf8(text, encoding):
d = chardet.detect(text) d = chardet.detect(text)
if d['encoding'] == uenc: if d['encoding'] == uenc:
return u.encode('utf-8') return u.encode('utf-8')
return unicode(text, d['encoding'], 'ignore').encode('utf-8') return text_type(text, d['encoding'], 'ignore').encode('utf-8')
def get_xmlrpc_service(): def get_xmlrpc_service():
@ -110,7 +112,7 @@ def get_xmlrpc_service():
try: try:
_xmlrpc_service = xmlrpclib.ServerProxy(_server_name + 'xmlrpc/', _xmlrpc_service = xmlrpclib.ServerProxy(_server_name + 'xmlrpc/',
allow_none=True) allow_none=True)
except Exception, err: except Exception as err:
fail('Could not connect to Pastebin: %s' % err, -1) fail('Could not connect to Pastebin: %s' % err, -1)
return _xmlrpc_service return _xmlrpc_service
@ -184,10 +186,12 @@ def print_languages():
"""Print a list of all supported languages, with description.""" """Print a list of all supported languages, with description."""
xmlrpc = get_xmlrpc_service() xmlrpc = get_xmlrpc_service()
languages = xmlrpc.pastes.getLanguages().items() languages = xmlrpc.pastes.getLanguages().items()
languages.sort(lambda a, b: cmp(a[1].lower(), b[1].lower())) languages.sort(
print 'Supported Languages:' lambda a, b: (a[1].lower() > b[1].lower())-(a[1].lower() < b[1].lower())
)
print('Supported Languages:')
for alias, name in languages: for alias, name in languages:
print ' %-30s%s' % (alias, name) print(' %-30s%s' % (alias, name))
def download_paste(uid): def download_paste(uid):
@ -196,7 +200,7 @@ def download_paste(uid):
paste = xmlrpc.pastes.getPaste(uid) paste = xmlrpc.pastes.getPaste(uid)
if not paste: if not paste:
fail('Paste "%s" does not exist.' % uid, 5) fail('Paste "%s" does not exist.' % uid, 5)
print paste['code'].encode('utf-8') print(paste['code'].encode('utf-8'))
def create_paste(code, language, filename, mimetype, private): def create_paste(code, language, filename, mimetype, private):
@ -221,7 +225,7 @@ def compile_paste(filenames, langopt):
lang = langopt or '' lang = langopt or ''
if not filenames: if not filenames:
data = read_file(sys.stdin) data = read_file(sys.stdin)
print 'Pasting...' print('Pasting...')
if not langopt: if not langopt:
mime = get_mimetype(data, '') or '' mime = get_mimetype(data, '') or ''
fname = '' fname = ''
@ -292,7 +296,7 @@ def main():
# special modes of operation: # special modes of operation:
# - paste script version # - paste script version
if opts.version: if opts.version:
print '%s: version %s' % (SCRIPT_NAME, VERSION) print('%s: version %s' % (SCRIPT_NAME, VERSION))
sys.exit() sys.exit()
# - print list of languages # - print list of languages
elif opts.languages: elif opts.languages:
@ -310,7 +314,7 @@ def main():
# load file(s) # load file(s)
try: try:
data, language, filename, mimetype = compile_paste(args, opts.language) data, language, filename, mimetype = compile_paste(args, opts.language)
except Exception, err: except Exception as err:
fail('Error while reading the file(s): %s' % err, 2) fail('Error while reading the file(s): %s' % err, 2)
if not data: if not data:
fail('Aborted, no content to paste.', 4) fail('Aborted, no content to paste.', 4)
@ -319,7 +323,7 @@ def main():
code = make_utf8(data, opts.encoding) code = make_utf8(data, opts.encoding)
pid = create_paste(code, language, filename, mimetype, opts.private) pid = create_paste(code, language, filename, mimetype, opts.private)
url = '%sshow/%s/' % (_server_name, pid) url = '%sshow/%s/' % (_server_name, pid)
print url print(url)
if opts.open_browser: if opts.open_browser:
open_webbrowser(url) open_webbrowser(url)
if opts.clipboard: if opts.clipboard:

View File

@ -6,6 +6,7 @@
Creates a bootstrap script for LodgeIt Creates a bootstrap script for LodgeIt
""" """
from __future__ import print_function
from virtualenv import create_bootstrap_script from virtualenv import create_bootstrap_script
@ -33,4 +34,4 @@ def easy_install(package, home_dir, optional_args=None):
""" """
if __name__ == '__main__': if __name__ == '__main__':
print create_bootstrap_script(EXTRA_TEXT) print(create_bootstrap_script(EXTRA_TEXT))

View File

@ -59,7 +59,7 @@ def test_json_get_recent():
return resp return resp
paste_ids = [] paste_ids = []
for x in xrange(10): for x in range(10):
resp = run(x) resp = run(x)
paste_ids.append(int(json(resp)['data'])) paste_ids.append(int(json(resp)['data']))

View File

@ -1,6 +1,6 @@
[tox] [tox]
minversion = 1.6 minversion = 1.6
envlist = pep8, py27 envlist = pep8, py27, py36
skipsdist = True skipsdist = True
[testenv] [testenv]
@ -10,7 +10,6 @@ deps = -r{toxinidir}/requirements.txt
commands = nosetests commands = nosetests
[testenv:pep8] [testenv:pep8]
basepython = python2
commands = flake8 commands = flake8
[flake8] [flake8]