Jelajahi Sumber

port to python3

Oz N Tiram 9 tahun lalu
induk
melakukan
43ca6687ff
2 mengubah file dengan 23 tambahan dan 26 penghapusan
  1. 15 17
      blogit/blogit.py
  2. 8 9
      tests/test_all.py

+ 15 - 17
blogit/blogit.py

@@ -15,7 +15,6 @@
 # Copyright (C) 2013-2016 Oz Nahum Tiram <nahumoz@gmail.com>
 # ============================================================================
 
-from __future__ import print_function
 import os
 import re
 import datetime
@@ -23,13 +22,12 @@ import argparse
 import sys
 import operator
 import shutil
-from StringIO import StringIO
+from io import StringIO
 import codecs
+import http.server
 import subprocess as sp
-import SimpleHTTPServer
-import BaseHTTPServer
 import socket
-import SocketServer
+import socketserver
 
 from jinja2 import Environment, FileSystemLoader
 import markdown2
@@ -257,7 +255,7 @@ class Entry(object):
         """this property is always called after prepare"""
         if 'tags' in self.header:
             tags = [Tag(t) for t in self.header['tags']]
-            map(lambda t: setattr(t, 'posts', [self.id]), tags)
+            list(map(lambda t: setattr(t, 'posts', [self.id]), tags))
             return tags
         else:
             return []
@@ -275,7 +273,7 @@ class Entry(object):
 
         self.date = self.header.get('published', datetime.datetime.now())
 
-        if isinstance(self.date, unicode):
+        if isinstance(self.date, str):
             self.date = datetime.datetime.strptime(self.date, "%Y-%m-%d")
 
         for k, v in self.header.items():
@@ -373,9 +371,9 @@ def update_index(entries):
     context['entries'] = entries
     context['last_build'] = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
 
-    map(lambda x: _render(
-        context, x[0], os.path.join(CONFIG['output_to'], x[1])),
-        (('entry_index.html', 'index.html'), ('atom.xml', 'atom.xml')))
+    list(map(lambda x: _render(
+         context, x[0], os.path.join(CONFIG['output_to'], x[1])),
+         (('entry_index.html', 'index.html'), ('atom.xml', 'atom.xml'))))
 
 
 def build(config):
@@ -396,7 +394,7 @@ def build(config):
                 entries.append(post)
         print("%s" % post.path)
 
-    for name, to in tags.iteritems():
+    for name, to in tags.items():
         print("updating tag %s" % name)
         to.render()
 
@@ -422,10 +420,10 @@ def build(config):
 
 def preview():  # pragma: no coverage
     """launch an HTTP to preview the website"""
-    Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
-    SocketServer.TCPServer.allow_reuse_address = True
+    Handler = http.server.SimpleHTTPRequestHandler
+    socketserver.TCPServer.allow_reuse_address = True
     port = CONFIG['http_port']
-    httpd = SocketServer.TCPServer(("", port), Handler)
+    httpd = socketserver.TCPServer(("", port), Handler)
     os.chdir(CONFIG['output_to'])
     print("and ready to test at http://127.0.0.1:%d" % CONFIG['http_port'])
     print("Hit Ctrl+C to exit")
@@ -448,13 +446,13 @@ def new_post(GITDIRECTORY=CONFIG['output_to'],
     Most other fields should be defaults.
     TODO: update this function
     """
-    title = raw_input("Give the title of the post: ")
+    title = input("Give the title of the post: ")
     while ':' in title:
-        title = raw_input("Give the title of the post (':' not allowed): ")
+        title = input("Give the title of the post (':' not allowed): ")
 
     author = CONFIG['author']
     date = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')
-    tags = raw_input("Give the tags, separated by ', ':")
+    tags = input("Give the tags, separated by ', ':")
     published = 'yes'
     chronological = 'yes'
     summary = ("summary: Type your summary here.")

+ 8 - 9
tests/test_all.py

@@ -78,8 +78,7 @@ try:
 except OSError:
     pass
 
-shift_factors = map(lambda x: (x - 1) / 5 +1,   range(1,21))
-
+shift_factors = list([(x - 1) // 5 +1 for x in range(1,21)])
 
 f = open((os.path.join(CONFIG['content_root'],
                        'page.md')), 'w')
@@ -128,18 +127,18 @@ def test_find_new_posts_and_pages():
 
     [e[0].tags for e in entries]
     foo = DB.tags.search(where('name')=='foo')
-    assert foo[0]['post_ids'] == range(1, 16)
+    assert foo[0]['post_ids'] == list(range(1, 16))
 
 def test_tags():
-    entries = map(lambda (p, e): Entry.entry_from_db(p, e),
-                  [(os.path.join(CONFIG['content_root'], e.get('filename')), e.eid)
-                      for e in DB.posts.all()])
+    entries = list(map(lambda p, e: Entry.entry_from_db(p, e),
+                   [(os.path.join(CONFIG['content_root'], e.get('filename')), e.eid)
+                      for e in DB.posts.all()]))
     tags = DB.tags.all()
 
     t = entries[0].tags
 
     assert len(t) == 4
-    assert t[0].name == u'buf'
+    assert t[0].name == 'buf'
 
     new_tag = Tag('buggg')
     new_tag.posts = [100,100]
@@ -233,7 +232,7 @@ def test_tag_render():
     #entry = Entry(os.path.join(CONFIG['content_root'], 'post1.md'))
     tags = entry.tags
 
-    assert map(str, tags) == ['buf', 'foo', 'bar', 'baz']
+    assert list(map(str, tags)) == ['buf', 'foo', 'bar', 'baz']
     # the entries are wrongly sorted, need to look at that
     assert tags[0].render()
     assert len(list(tags[0].entries))
@@ -284,5 +283,5 @@ def test_build():
         soup = BeautifulSoup(tag_foo.read(), 'html.parser')
         titles = [c.a.string for c in
                   soup.find_all(class_="clearfix entry")]
-        for title, idx in zip(titles, range(15, 0, -1)):
+        for title, idx in zip(titles, list(range(15, 0, -1))):
             assert title.split()[-1] == str(idx)