Skip to content

Commit

Permalink
Remove some Python 2 compatibility leftovers (#1415)
Browse files Browse the repository at this point in the history
  • Loading branch information
charmander committed Jun 26, 2024
1 parent ea49be1 commit 7473785
Show file tree
Hide file tree
Showing 30 changed files with 201 additions and 201 deletions.
6 changes: 3 additions & 3 deletions libweasyl/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,9 @@ def file_type_for_category(data, category):
except SanperaError:
raise UnknownFileFormat('The image data provided could not be decoded.')
fmt = im.original_format.decode()
if fmt == u'JPEG':
fmt = u'JPG'
if fmt not in {u'GIF', u'JPG', u'PNG'}:
if fmt == 'JPEG':
fmt = 'JPG'
if fmt not in {'GIF', 'JPG', 'PNG'}:
raise InvalidFileFormat('Image files must be in the GIF, JPG, or PNG formats.')
return im, str(fmt.lower())
elif category == Category.literary:
Expand Down
2 changes: 1 addition & 1 deletion libweasyl/models/media.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def file_url(self):
return '/' + '/'.join(self._file_path_components)


class _LinkMixin(object):
class _LinkMixin:
cache_func = None

@classmethod
Expand Down
8 changes: 4 additions & 4 deletions libweasyl/models/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ def default_fkey(*args, **kwargs):
Column('height', String(length=100), nullable=False, server_default=''),
Column('weight', String(length=100), nullable=False, server_default=''),
Column('species', String(length=100), nullable=False, server_default=''),
Column('content', String(length=100000), nullable=False, server_default=u""),
Column('content', String(length=100000), nullable=False, server_default=""),
Column('rating', RatingColumn, nullable=False),
Column('settings', CharSettingsColumn({}, length=20), nullable=False, server_default=''),
Column('hidden', Boolean(), nullable=False, server_default='f'),
Expand Down Expand Up @@ -365,7 +365,7 @@ def default_fkey(*args, **kwargs):
'media', metadata,
Column('mediaid', Integer(), primary_key=True, nullable=False),
Column('file_type', String(length=8), nullable=False),
Column('attributes', JSONValuesColumn(), nullable=False, server_default=text(u"''::hstore")),
Column('attributes', JSONValuesColumn(), nullable=False, server_default=text("''::hstore")),
Column('sha256', String(length=64)),
)

Expand Down Expand Up @@ -655,7 +655,7 @@ def default_fkey(*args, **kwargs):
Column('created_at', ArrowColumn(), nullable=False, server_default=text('now()')),
Column('last_active', TIMESTAMP(timezone=True), nullable=True, server_default=func.now()),
Column('userid', Integer()),
Column('additional_data', JSONValuesColumn(), nullable=False, server_default=text(u"''::hstore")),
Column('additional_data', JSONValuesColumn(), nullable=False, server_default=text("''::hstore")),
Column('ip_address', String(length=39), nullable=True),
Column('user_agent_id', Integer(), nullable=True),
default_fkey(['userid'], ['login.userid'], name='sessions_userid_fkey'),
Expand Down Expand Up @@ -825,7 +825,7 @@ def _tag_suggestion_feedback_table(content_table, id_column):
Column('added', ARRAY(Text())),
Column('removed', ARRAY(Text())),
Column('updated_at', Integer(), nullable=False,
server_default=text(u"(date_part('epoch'::text, now()) - (18000)::double precision)")),
server_default=text("(date_part('epoch'::text, now()) - (18000)::double precision)")),
default_fkey(['submitid'], ['submission.submitid'], name='tag_updates_submitid_fkey'),
ForeignKeyConstraint(['userid'], ['login.userid'], name='tag_updates_userid_fkey'),
)
Expand Down
2 changes: 1 addition & 1 deletion libweasyl/ratings.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@


@functools.total_ordering
class Rating(object):
class Rating:
def __init__(self, code, character, name, nice_name, minimum_age, block_text,
additional_description=None):

Expand Down
2 changes: 1 addition & 1 deletion libweasyl/test/test_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,4 @@ def test_file_type_for_category_literary_results():
"""
Non-PDF UTF-8 documents are returned decoded.
"""
assert files.file_type_for_category(b'hello\xc3\xbfworld', Category.literary) == (u'hello\xffworld', 'txt')
assert files.file_type_for_category(b'hello\xc3\xbfworld', Category.literary) == ('hello\xffworld', 'txt')
54 changes: 27 additions & 27 deletions libweasyl/test/test_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,17 +125,17 @@ def test_markdown_respect_ordered_list_start():


def test_markdown_strikethrough():
assert markdown(u"~~test~~") == u"<p><del>test</del></p>\n"
assert markdown("~~test~~") == "<p><del>test</del></p>\n"


@pytest.mark.parametrize(('target', 'expected'), [
(u"[external](http://example.com/)", u'<a href="http://example.com/" rel="nofollow ugc">external</a>'),
(u'<a href="http://example.com/">external</a>', u'<a href="http://example.com/" rel="nofollow ugc">external</a>'),
(u'<a href="http://example.com/" rel="noreferrer">external</a>', u'<a href="http://example.com/" rel="nofollow ugc">external</a>'),
(u"[external](//example.com/)", u'<a href="//example.com/" rel="nofollow ugc">external</a>'),
("[external](http://example.com/)", '<a href="http://example.com/" rel="nofollow ugc">external</a>'),
('<a href="http://example.com/">external</a>', '<a href="http://example.com/" rel="nofollow ugc">external</a>'),
('<a href="http://example.com/" rel="noreferrer">external</a>', '<a href="http://example.com/" rel="nofollow ugc">external</a>'),
("[external](//example.com/)", '<a href="//example.com/" rel="nofollow ugc">external</a>'),
])
def test_markdown_external_link_noreferrer(target, expected):
assert markdown(target) == u"<p>%s</p>\n" % (expected,)
assert markdown(target) == "<p>%s</p>\n" % (expected,)


markdown_link_tests = [
Expand All @@ -151,28 +151,28 @@ def test_markdown_link(target, expected):


def test_tag_stripping():
assert markdown(u"<button>text</button>") == u"<p>text</p>\n"
assert markdown(u"<button><button>text</button></button>") == u"<p>text</p>\n"
assert markdown(u"<!--[if IE]><script>alert(1)</script><![endif]-->") == u"\n"
assert markdown("<button>text</button>") == "<p>text</p>\n"
assert markdown("<button><button>text</button></button>") == "<p>text</p>\n"
assert markdown("<!--[if IE]><script>alert(1)</script><![endif]-->") == "\n"


markdown_excerpt_tests = [
(u'', u''),
(u'short', u'short'),
(u'just short enoughAAAAAAAAAAAAA', u'just short enoughAAAAAAAAAAAAA'),
(u'not short enoughAAAAAAAAAAAAAAA', u'not short enoughAAAAAAAAAAAAA…'),
(u'*leading* inline formatting', u'leading inline formatting'),
(u'middle *inline* formatting', u'middle inline formatting'),
(u'trailing inline *formatting*', u'trailing inline formatting'),
(u'*nested **inline** formatting*', u'nested inline formatting'),
(u' unnecessary whitespace\t', u'unnecessary whitespace'),
(u'multiple\nlines', u'multiple lines'),
(u'multiple \nlines', u'multiple lines'),
(u'multiple\n\nparagraphs', u'multiple paragraphs'),
(u'Üñíçôđe\N{COMBINING ACUTE ACCENT}', u'Üñíçôđe\N{COMBINING ACUTE ACCENT}'),
(u'single-codepoint graphemes😊😊😊😊', u'single-codepoint graphemes😊😊😊😊'),
(u'single-codepoint graphemes😊😊😊😊😊', u'single-codepoint graphemes😊😊😊…'),
(u'test\n - lists\n - of\n - items\n\ntest', u'test lists of items test'),
('', ''),
('short', 'short'),
('just short enoughAAAAAAAAAAAAA', 'just short enoughAAAAAAAAAAAAA'),
('not short enoughAAAAAAAAAAAAAAA', 'not short enoughAAAAAAAAAAAAA…'),
('*leading* inline formatting', 'leading inline formatting'),
('middle *inline* formatting', 'middle inline formatting'),
('trailing inline *formatting*', 'trailing inline formatting'),
('*nested **inline** formatting*', 'nested inline formatting'),
(' unnecessary whitespace\t', 'unnecessary whitespace'),
('multiple\nlines', 'multiple lines'),
('multiple \nlines', 'multiple lines'),
('multiple\n\nparagraphs', 'multiple paragraphs'),
('Üñíçôđe\N{COMBINING ACUTE ACCENT}', 'Üñíçôđe\N{COMBINING ACUTE ACCENT}'),
('single-codepoint graphemes😊😊😊😊', 'single-codepoint graphemes😊😊😊😊'),
('single-codepoint graphemes😊😊😊😊😊', 'single-codepoint graphemes😊😊😊…'),
('test\n - lists\n - of\n - items\n\ntest', 'test lists of items test'),
('<div style="text-align: center">**foo**</div>\n<!-- comment -->', "foo"),
('1 < 3 > 2 "foo"', '1 < 3 > 2 "foo"'),
("&copy;", "©"),
Expand All @@ -189,5 +189,5 @@ def test_excerpt(target, expected):


def test_excerpt_default_length():
assert markdown_excerpt(u'a' * 300) == u'a' * 300
assert markdown_excerpt(u'a' * 301) == u'a' * 299 + u'…'
assert markdown_excerpt('a' * 300) == 'a' * 300
assert markdown_excerpt('a' * 301) == 'a' * 299 + '…'
78 changes: 39 additions & 39 deletions libweasyl/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def _sofurry(target):
def strip_outer_tag(html):
match = locatestarttagend.match(html)
start_tag_end = match.end()
end_tag_start = html.rindex(u'<')
end_tag_start = html.rindex('<')
return html[:start_tag_end + 1], html[start_tag_end + 1:end_tag_start], html[end_tag_start:]


Expand All @@ -82,7 +82,7 @@ def block_html(self, raw_html):
if raw_html.startswith('<!--'):
return raw_html
start, stripped, end = strip_outer_tag(raw_html)
return u''.join([start, _markdown(stripped).rstrip(), end])
return ''.join([start, _markdown(stripped).rstrip(), end])

def autolink(self, link, is_email):
# default implementation from sundown’s `rndr_autolink`, with the tag name replaced
Expand Down Expand Up @@ -111,31 +111,29 @@ def _markdown(target):


def create_link(t, username):
link = etree.Element(u"a")
link.set(u"href", u"/~" + get_sysname(username))
link = etree.Element("a")
link.set("href", "/~" + get_sysname(username))

if t == "~":
link.text = username
else:
link.set(u"class", u"user-icon")
link.set("class", "user-icon")

image = etree.SubElement(link, u"img")
image.set(u"src", u"/~{username}/avatar".format(username=get_sysname(username)))
image = etree.SubElement(link, "img")
image.set("src", "/~{username}/avatar".format(username=get_sysname(username)))

if t == "!":
image.set("alt", username)
else:
image.set("alt", "")
label = etree.SubElement(link, u"span")
label = etree.SubElement(link, "span")
label.text = username
image.tail = u" "
image.tail = " "

return link


def add_user_links(fragment, parent, can_contain):
_nonlocal = {}

def add_matches(text, got_link):
text_start = 0

Expand Down Expand Up @@ -163,7 +161,8 @@ def add_matches(text, got_link):
return True

def got_text_link(t, username):
previous = _nonlocal["previous"]
nonlocal previous
nonlocal insert_index

if previous is None:
fragment.text = "".join(previous_text)
Expand All @@ -173,46 +172,47 @@ def got_text_link(t, username):
del previous_text[:]

link = create_link(t, username)
fragment.insert(_nonlocal["insert_index"], link)
_nonlocal["insert_index"] += 1
fragment.insert(insert_index, link)
insert_index += 1

_nonlocal["previous"] = link
previous = link

def got_tail_link(t, username):
_nonlocal["previous"].tail = "".join(previous_text)
nonlocal previous
nonlocal insert_index

previous.tail = "".join(previous_text)
del previous_text[:]

_nonlocal["insert_index"] += 1
insert_index += 1
link = create_link(t, username)
parent.insert(_nonlocal["insert_index"], link)
parent.insert(insert_index, link)

_nonlocal["previous"] = link
previous = link

if can_contain:
for child in list(fragment):
child_can_contain = child.tag not in ("a", "pre", "code")
add_user_links(child, fragment, child_can_contain)

if fragment.text:
_nonlocal["previous"] = None
_nonlocal["insert_index"] = 0
previous = None
insert_index = 0
previous_text = []

if add_matches(fragment.text, got_text_link):
previous = _nonlocal["previous"]

if previous is None:
fragment.text = "".join(previous_text)
else:
previous.tail = "".join(previous_text)

if fragment.tail:
_nonlocal["previous"] = fragment
_nonlocal["insert_index"] = parent.index(fragment)
previous = fragment
insert_index = parent.index(fragment)
previous_text = []

if add_matches(fragment.tail, got_tail_link):
_nonlocal["previous"].tail = "".join(previous_text)
previous.tail = "".join(previous_text)


def _convert_autolinks(fragment):
Expand All @@ -226,15 +226,15 @@ def _convert_autolinks(fragment):
t, _, user = href.partition(":")

if t == "user":
link.set("href", u"/~{user}".format(user=get_sysname(user)))
link.set("href", "/~{user}".format(user=get_sysname(user)))
elif t == "da":
link.set("href", u"https://www.deviantart.com/{user}".format(user=_deviantart(user)))
link.set("href", "https://www.deviantart.com/{user}".format(user=_deviantart(user)))
elif t == "ib":
link.set("href", u"https://inkbunny.net/{user}".format(user=_inkbunny(user)))
link.set("href", "https://inkbunny.net/{user}".format(user=_inkbunny(user)))
elif t == "fa":
link.set("href", u"https://www.furaffinity.net/user/{user}".format(user=_furaffinity(user)))
link.set("href", "https://www.furaffinity.net/user/{user}".format(user=_furaffinity(user)))
elif t == "sf":
link.set("href", u"https://{user}.sofurry.com/".format(user=_sofurry(user)))
link.set("href", "https://{user}.sofurry.com/".format(user=_sofurry(user)))
else:
continue

Expand All @@ -256,26 +256,26 @@ def _markdown_fragment(target):
t, _, user = src.partition(":")

if t != "user":
link = etree.Element(u"a")
link = etree.Element("a")
link.tail = image.tail
link.set(u"href", src)
link.set("href", src)
link.text = image.get("alt", src)
image.getparent().replace(image, link)
continue

image.set(u"src", u"/~{user}/avatar".format(user=get_sysname(user)))
image.set("src", "/~{user}/avatar".format(user=get_sysname(user)))

link = etree.Element(u"a")
link.set(u"href", u"/~{user}".format(user=get_sysname(user)))
link.set(u"class", u"user-icon")
link = etree.Element("a")
link.set("href", "/~{user}".format(user=get_sysname(user)))
link.set("class", "user-icon")
link.tail = image.tail
image.getparent().replace(image, link)
link.append(image)

alt = image.get("alt")
if alt:
image.tail = u" "
label = etree.SubElement(link, u"span")
image.tail = " "
label = etree.SubElement(link, "span")
label.text = alt
del image.attrib["alt"]
else:
Expand Down
16 changes: 8 additions & 8 deletions weasyl-apidocs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@
master_doc = 'index'

# General information about the project.
project = u'Weasyl API'
copyright = u'2016, weykent'
project = 'Weasyl API'
copyright = '2016, weykent'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
Expand Down Expand Up @@ -186,8 +186,8 @@
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'WeasylAPI.tex', u'Weasyl API Documentation',
u'weykent', 'manual'),
('index', 'WeasylAPI.tex', 'Weasyl API Documentation',
'weykent', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
Expand Down Expand Up @@ -216,8 +216,8 @@
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'weasylapi', u'Weasyl API Documentation',
[u'weykent'], 1)
('index', 'weasylapi', 'Weasyl API Documentation',
['weykent'], 1)
]

# If true, show URL addresses after external links.
Expand All @@ -230,8 +230,8 @@
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'WeasylAPI', u'Weasyl API Documentation',
u'weykent', 'WeasylAPI', 'One line description of project.',
('index', 'WeasylAPI', 'Weasyl API Documentation',
'weykent', 'WeasylAPI', 'One line description of project.',
'Miscellaneous'),
]

Expand Down
2 changes: 1 addition & 1 deletion weasyl/commishinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ def prepare(info):
dinfo['localmax'] = convert_currency(info.pricemax, info.pricesettings, currency)
if tags:
terms = ["user:" + d.get_sysname(info.username)] + ["|" + tag for tag in tags]
dinfo['searchquery'] = "q=" + urlquote(u" ".join(terms).encode("utf-8"))
dinfo['searchquery'] = "q=" + urlquote(" ".join(terms).encode("utf-8"))
else:
dinfo['searchquery'] = ""
return dinfo
Expand Down
Loading

0 comments on commit 7473785

Please sign in to comment.