diff libervia/server/blog.py @ 1216:b2d067339de3

python 3 port: /!\ Python 3.6+ is now needed to use libervia /!\ instability may occur and features may not be working anymore, this will improve with time /!\ TxJSONRPC dependency has been removed The same procedure as in backend has been applied (check backend commit ab2696e34d29 logs for details). Removed now deprecated code (Pyjamas compiled browser part, legacy blog, JSON RPC related code). Adapted code to work without `html` and `themes` dirs.
author Goffi <goffi@goffi.org>
date Tue, 13 Aug 2019 19:12:31 +0200
parents 1276452c0d32
children 987595a254b0
line wrap: on
line diff
--- a/libervia/server/blog.py	Tue Aug 13 09:39:33 2019 +0200
+++ b/libervia/server/blog.py	Tue Aug 13 19:12:31 2019 +0200
@@ -36,7 +36,7 @@
 import re
 import os
 import sys
-import urllib
+import urllib.request, urllib.parse, urllib.error
 
 from libervia.server.html_tools import sanitizeHtml, convertNewLinesToXHTML
 from libervia.server.constants import Const as C
@@ -78,7 +78,7 @@
     @param value(unicode): value to quote
     @return (str): quoted value
     """
-    return urllib.quote(value.encode("utf-8"), "")
+    return urllib.parse.quote(value.encode("utf-8"), "")
 
 
 def _unquote(quoted_value):
@@ -87,16 +87,16 @@
     @param unquote_value(str): value to unquote
     @return (unicode): unquoted value
     """
-    assert not isinstance(quoted_value, unicode)
-    return urllib.unquote(quoted_value).decode("utf-8")
+    assert not isinstance(quoted_value, str)
+    return urllib.parse.unquote(quoted_value).decode("utf-8")
 
 
 def _urlencode(query):
     """Same as urllib.urlencode, but use '&amp;' instead of '&'"""
     return "&amp;".join(
         [
-            "{}={}".format(urllib.quote_plus(str(k)), urllib.quote_plus(str(v)))
-            for k, v in query.iteritems()
+            "{}={}".format(urllib.parse.quote_plus(str(k)), urllib.parse.quote_plus(str(v)))
+            for k, v in query.items()
         ]
     )
 
@@ -277,11 +277,11 @@
         try:
             rsm_max = int(request.args["max"][0])
             if rsm_max > C.STATIC_RSM_MAX_LIMIT:
-                log.warning(u"Request with rsm_max over limit ({})".format(rsm_max))
+                log.warning("Request with rsm_max over limit ({})".format(rsm_max))
                 rsm_max = C.STATIC_RSM_MAX_LIMIT
-            request.extra_dict["rsm_max"] = unicode(rsm_max)
+            request.extra_dict["rsm_max"] = str(rsm_max)
         except (ValueError, KeyError):
-            request.extra_dict["rsm_max"] = unicode(C.STATIC_RSM_MAX_DEFAULT)
+            request.extra_dict["rsm_max"] = str(C.STATIC_RSM_MAX_DEFAULT)
         try:
             request.extra_dict["rsm_index"] = request.args["index"][0]
         except (ValueError, KeyError):
@@ -308,11 +308,11 @@
             try:
                 rsm_max = int(request.args["comments_max"][0])
                 if rsm_max > C.STATIC_RSM_MAX_LIMIT:
-                    log.warning(u"Request with rsm_max over limit ({})".format(rsm_max))
+                    log.warning("Request with rsm_max over limit ({})".format(rsm_max))
                     rsm_max = C.STATIC_RSM_MAX_LIMIT
-                request.extra_comments_dict["rsm_max"] = unicode(rsm_max)
+                request.extra_comments_dict["rsm_max"] = str(rsm_max)
             except (ValueError, KeyError):
-                request.extra_comments_dict["rsm_max"] = unicode(
+                request.extra_comments_dict["rsm_max"] = str(
                     C.STATIC_RSM_MAX_COMMENTS_DEFAULT
                 )
         else:
@@ -363,7 +363,7 @@
                 except KeyError:
                     pass
                 try:
-                    metadata["rsm_index"] = unicode(int(rsm_metadata["rsm_index"]) - 1)
+                    metadata["rsm_index"] = str(int(rsm_metadata["rsm_index"]) - 1)
                 except KeyError:
                     pass
 
@@ -491,83 +491,83 @@
             # from microblog data
             items, metadata = data
             items = [data_format.deserialise(i) for i in items]
-            feed_elt = domish.Element((NS_ATOM, u"feed"))
-            title = _(u"{user}'s blog").format(user=profile)
-            feed_elt.addElement(u"title", content=title)
+            feed_elt = domish.Element((NS_ATOM, "feed"))
+            title = _("{user}'s blog").format(user=profile)
+            feed_elt.addElement("title", content=title)
 
             base_blog_url = self.host.getExtBaseURL(
-                request, u"blog/{user}".format(user=profile)
+                request, "blog/{user}".format(user=profile)
             )
 
             # atom link
             link_feed_elt = feed_elt.addElement("link")
-            link_feed_elt["href"] = u"{base}/atom.xml".format(base=base_blog_url)
-            link_feed_elt["type"] = u"application/atom+xml"
-            link_feed_elt["rel"] = u"self"
+            link_feed_elt["href"] = "{base}/atom.xml".format(base=base_blog_url)
+            link_feed_elt["type"] = "application/atom+xml"
+            link_feed_elt["rel"] = "self"
 
             # blog link
             link_blog_elt = feed_elt.addElement("link")
-            link_blog_elt["rel"] = u"alternate"
-            link_blog_elt["type"] = u"text/html"
+            link_blog_elt["rel"] = "alternate"
+            link_blog_elt["type"] = "text/html"
             link_blog_elt["href"] = base_blog_url
 
             # blog link XMPP uri
             blog_xmpp_uri = metadata["uri"]
             link_blog_elt = feed_elt.addElement("link")
-            link_blog_elt["rel"] = u"alternate"
-            link_blog_elt["type"] = u"application/atom+xml"
+            link_blog_elt["rel"] = "alternate"
+            link_blog_elt["type"] = "application/atom+xml"
             link_blog_elt["href"] = blog_xmpp_uri
 
             feed_elt.addElement("id", content=_quote(blog_xmpp_uri))
             updated_unix = max([float(item["updated"]) for item in items])
             updated_dt = datetime.fromtimestamp(updated_unix)
             feed_elt.addElement(
-                u"updated", content=u"{}Z".format(updated_dt.isoformat("T"))
+                "updated", content="{}Z".format(updated_dt.isoformat("T"))
             )
 
             for item in items:
-                entry_elt = feed_elt.addElement(u"entry")
+                entry_elt = feed_elt.addElement("entry")
 
                 # Title
                 try:
                     title = item["title"]
                 except KeyError:
                     # for microblog (without title), we use an abstract of content as title
-                    title = u"{}…".format(u" ".join(item["content"][:70].split()))
-                entry_elt.addElement(u"title", content=title)
+                    title = "{}…".format(" ".join(item["content"][:70].split()))
+                entry_elt.addElement("title", content=title)
 
                 # HTTP link
-                http_link_elt = entry_elt.addElement(u"link")
-                http_link_elt["rel"] = u"alternate"
-                http_link_elt["type"] = u"text/html"
-                http_link_elt["href"] = u"{base}/{quoted_id}".format(
+                http_link_elt = entry_elt.addElement("link")
+                http_link_elt["rel"] = "alternate"
+                http_link_elt["type"] = "text/html"
+                http_link_elt["href"] = "{base}/{quoted_id}".format(
                     base=base_blog_url, quoted_id=_quote(item["id"])
                 )
                 # XMPP link
-                xmpp_link_elt = entry_elt.addElement(u"link")
-                xmpp_link_elt["rel"] = u"alternate"
-                xmpp_link_elt["type"] = u"application/atom+xml"
-                xmpp_link_elt["href"] = u"{blog_uri};item={item_id}".format(
+                xmpp_link_elt = entry_elt.addElement("link")
+                xmpp_link_elt["rel"] = "alternate"
+                xmpp_link_elt["type"] = "application/atom+xml"
+                xmpp_link_elt["href"] = "{blog_uri};item={item_id}".format(
                     blog_uri=blog_xmpp_uri, item_id=item["id"]
                 )
 
                 # date metadata
-                entry_elt.addElement(u"id", content=item["atom_id"])
+                entry_elt.addElement("id", content=item["atom_id"])
                 updated = datetime.fromtimestamp(float(item["updated"]))
                 entry_elt.addElement(
-                    u"updated", content=u"{}Z".format(updated.isoformat("T"))
+                    "updated", content="{}Z".format(updated.isoformat("T"))
                 )
                 published = datetime.fromtimestamp(float(item["published"]))
                 entry_elt.addElement(
-                    u"published", content=u"{}Z".format(published.isoformat("T"))
+                    "published", content="{}Z".format(published.isoformat("T"))
                 )
 
                 # author metadata
-                author_elt = entry_elt.addElement(u"author")
+                author_elt = entry_elt.addElement("author")
                 author_elt.addElement("name", content=item.get("author", profile))
                 try:
                     author_elt.addElement(
-                        "uri", content=u"xmpp:{}".format(item["author_jid"])
+                        "uri", content="xmpp:{}".format(item["author_jid"])
                     )
                 except KeyError:
                     pass
@@ -578,7 +578,7 @@
 
                 # categories
                 for tag in item.get('tags', []):
-                    category_elt = entry_elt.addElement(u"category")
+                    category_elt = entry_elt.addElement("category")
                     category_elt["term"] = tag
 
                 # content
@@ -594,7 +594,7 @@
                         xml_tools.ElementParser()(content_xhtml, namespace=C.NS_XHTML)
                     )
 
-            atom_feed = u'<?xml version="1.0" encoding="utf-8"?>\n{}'.format(
+            atom_feed = '<?xml version="1.0" encoding="utf-8"?>\n{}'.format(
                 feed_elt.toXml()
             )
             self.renderAtomFeed(atom_feed, request),
@@ -708,12 +708,12 @@
             # FIXME: that's really not a good way to get item id
             #        this must be changed after static blog refactorisation
             item_id = items[0][0]["id"]
-            xmpp_uri += u";item={}".format(_quote(item_id))
+            xmpp_uri += ";item={}".format(_quote(item_id))
 
         data = {
             "url_base": base_url,
             "xmpp_uri": xmpp_uri,
-            "url_query": u"?{}".format(query_data) if query_data else "",
+            "url_query": "?{}".format(query_data) if query_data else "",
             "keywords": getOption(C.STATIC_BLOG_PARAM_KEYWORDS),
             "description": getOption(C.STATIC_BLOG_PARAM_DESCRIPTION),
             "title": title,
@@ -850,7 +850,7 @@
         self.content = self.getText(entry, "content")
 
         if is_comment:
-            self.author = _(u"from {}").format(entry["author"])
+            self.author = _("from {}").format(entry["author"])
         else:
             self.author = "&nbsp;"
             self.url = "{}/{}".format(base_url, _quote(entry["id"]))
@@ -860,9 +860,9 @@
             self.title = self.getText(entry, "title")
             self.tags = [sanitizeHtml(tag) for tag in entry.get('tags', [])]
 
-            count_text = lambda count: D_(u"comments") if count > 1 else D_(u"comment")
+            count_text = lambda count: D_("comments") if count > 1 else D_("comment")
 
-            self.comments_text = u"{} {}".format(
+            self.comments_text = "{} {}".format(
                 comments_count, count_text(comments_count)
             )
 
@@ -871,7 +871,7 @@
                 prev_url = "{}?{}".format(
                     self.url, _urlencode({"comments_max": comments_count})
                 )
-                prev_text = D_(u"show {count} previous {comments}").format(
+                prev_text = D_("show {count} previous {comments}").format(
                     count=delta, comments=count_text(delta)
                 )
                 self.all_comments_link = BlogLink(prev_url, "comments_link", prev_text)