Permalink
Browse files

Convert to py3k

2to3 did most of the work. Some encoding issues were fixed by hand
(e.g. opening files in binary mode, converting strings to bytes).
  • Loading branch information...
1 parent 5463c04 commit 4367d8af07d692e852633ed144f496c637b74226 @akheron committed Jul 21, 2010
Showing with 47 additions and 36 deletions.
  1. +1 −1 bin/stango
  2. +2 −1 stango/__init__.py
  3. +13 −13 stango/main.py
  4. +25 −15 stango/manage/__init__.py
  5. +5 −5 stango/manage/autoreload.py
  6. +1 −1 stango/views.py
View
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/env python3
import stango.main
View
@@ -2,6 +2,7 @@
import os
import tarfile
from stango.views import file_from_tar, static_file
+from functools import reduce
class File(object):
def __init__(self, path, view, kwargs):
@@ -29,7 +30,7 @@ def _files(self, args):
else:
path, view, kwargs = arg
- if not isinstance(path, basestring) or path.startswith('/'):
+ if not isinstance(path, str) or path.startswith('/'):
raise ValueError('invalid path %r in arg %d' % (path, i))
yield File(path, view, kwargs)
View
@@ -41,15 +41,15 @@ def hello(message, link):
'''
init_files = [
- ('__init__.py', '', 0644),
- ('conf.py', conf_code, 0644),
- ('views.py', views_code, 0644),
- ('static/hello.css', hello_css, 0644),
- ('templates/hello.html', hello_template, 0644),
+ ('__init__.py', '', 0o644),
+ ('conf.py', conf_code, 0o644),
+ ('views.py', views_code, 0o644),
+ ('static/hello.css', hello_css, 0o644),
+ ('templates/hello.html', hello_template, 0o644),
]
for filename, contents, mode in init_files:
- print 'Creating %s' % filename
+ print('Creating %s' % filename)
dirname = os.path.dirname(filename)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
@@ -58,12 +58,12 @@ def hello(message, link):
fobj.close()
os.chmod(filename, mode)
- print 'Now run "stango serve" or "stango render"'
+ print('Now run "stango serve" or "stango render"')
return 0
def print_help():
- print '''\
+ print('''\
usage: %s COMMAND [ARGS...]
Available commands:
@@ -84,7 +84,7 @@ def print_help():
Initialize a boilerplate example project in the
current directory.
-''' % sys.argv[0]
+''' % sys.argv[0])
sys.exit(2)
@@ -105,22 +105,22 @@ def run():
sys.exit(quickstart())
if not os.path.exists('conf.py'):
- print >>sys.stderr, 'conf.py not found'
+ print('conf.py not found', file=sys.stderr)
sys.exit(1)
try:
backup = sys.path
sys.path = [''] + sys.path
config = {}
- execfile('conf.py', config)
+ exec(open('conf.py').read(), config)
finally:
sys.path = backup
- for k, v in CONFIG_DEFAULTS.items():
+ for k, v in list(CONFIG_DEFAULTS.items()):
config.setdefault(k, v)
if not 'files' in config:
- print >>sys.stderr, "'files.py' doesn't define the 'files' variable"
+ print("'files.py' doesn't define the 'files' variable", file=sys.stderr)
sys.exit(1)
if config['index_file']:
View
@@ -2,7 +2,20 @@
import os
import shutil
import sys
-from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
+from http.server import HTTPServer, BaseHTTPRequestHandler
+import collections
+
+def view_and_encode(file):
+ data = file.view(**file.kwargs)
+
+ if not isinstance(data, (str, bytes, bytearray)):
+ print('Warning: The result of the view %r is not a str, bytes or bytearray instance, writing an empty file' % (view, file.realpath), file=sys.stderr)
+ data = b''
+
+ if isinstance(data, str):
+ data = data.encode('utf-8')
+
+ return data
class StangoRequestHandler(BaseHTTPRequestHandler):
def start_response(self, code, headers=[]):
@@ -26,7 +39,7 @@ def do_GET(self):
if file.realpath == realpath:
headers = []
self.start_response(200)
- self.wfile.write(file.view(**file.kwargs))
+ self.wfile.write(view_and_encode(file))
break
else:
self.start_response(404)
@@ -41,11 +54,11 @@ def __init__(self, server_address, files, index_file):
def serve(config, host, port):
if port < 0 or port > 65535:
- print >>sys.stderr, 'Unable to serve on invalid port %r' % port
+ print('Unable to serve on invalid port %r' % port, file=sys.stderr)
return 1
def do_serve():
- print 'Starting server on http://%s:%d/' % (host, port)
+ print('Starting server on http://%s:%d/' % (host, port))
httpd = StangoHTTPServer((host, port),
config['files'], config['index_file'])
httpd.serve_forever()
@@ -55,23 +68,23 @@ def do_serve():
def render(config, outdir):
- print 'Rendering to %s...' % outdir
+ print('Rendering to %s...' % outdir)
if os.path.exists(outdir):
if os.path.isdir(outdir):
shutil.rmtree(outdir)
else:
- print >>sys.stderr, '%r is not a directory' % outdir
+ print('%r is not a directory' % outdir, file=sys.stderr)
return 1
try:
os.mkdir(outdir)
- except OSError, err:
+ except OSError as err:
if err.errno != errno.EEXIST:
raise
post_render_hook = config['post_render_hook']
- if post_render_hook and not callable(post_render_hook):
- print >>sys.stderr, 'Error: post_render_hook must be callable'
+ if post_render_hook and not isinstance(post_render_hook, collections.Callable):
+ print('Error: post_render_hook must be callable', file=sys.stderr)
return 1
for file in config['files']:
@@ -80,17 +93,14 @@ def render(config, outdir):
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
- fobj = open(path, 'w')
+ fobj = open(path, 'wb')
try:
- data = file.view(**file.kwargs)
+ data = view_and_encode(file)
if post_render_hook:
data = post_render_hook(file.realpath, data)
- if not isinstance(data, basestring):
- print >>sys.stderr, 'Warning: post_render_hook returned a non-string for %s, writing an empty file' % file.realpath
- data = ''
fobj.write(data)
finally:
fobj.close()
- print 'done.'
+ print('done.')
return 0
@@ -69,9 +69,9 @@
import glob, itertools, os, sys, time
try:
- import thread
+ import _thread
except ImportError:
- import dummy_thread as thread
+ import _dummy_thread as thread
# This import does nothing, but it's necessary to avoid some race conditions
# in the threading module. See http://code.djangoproject.com/ticket/2330 .
@@ -89,7 +89,7 @@
def code_files():
return \
[os.path.abspath('conf.py')] + \
- filter(lambda v: v, map(lambda m: getattr(m, "__file__", None), sys.modules.values()))
+ [v for v in [getattr(m, "__file__", None) for m in list(sys.modules.values())] if v]
def matching_files(patterns):
for pattern in patterns:
@@ -145,7 +145,7 @@ def restart_with_reloader():
def python_reloader(main_func, filepatterns, args, kwargs):
if os.environ.get("RUN_MAIN") == "true":
- thread.start_new_thread(main_func, args, kwargs)
+ _thread.start_new_thread(main_func, args, kwargs)
try:
reloader_thread(filepatterns)
except KeyboardInterrupt:
@@ -158,7 +158,7 @@ def python_reloader(main_func, filepatterns, args, kwargs):
def jython_reloader(main_func, filepatterns, args, kwargs):
from _systemrestart import SystemRestart
- thread.start_new_thread(main_func, args)
+ _thread.start_new_thread(main_func, args)
while True:
if code_changed(filepatterns):
raise SystemRestart
View
@@ -2,7 +2,7 @@ def file_from_tar(tar, member):
return tar.extractfile(member).read()
def static_file(path):
- fobj = open(path)
+ fobj = open(path, 'rb')
try:
return fobj.read()
finally:

0 comments on commit 4367d8a

Please sign in to comment.