summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBert JW Regeer <bertjw@regeer.org>2020-11-28 12:07:55 -0800
committerBert JW Regeer <bertjw@regeer.org>2020-11-28 12:28:22 -0800
commit264aa8b9cc8753e07692484732b897978c6fa8cb (patch)
tree2f8f71b794046df3bc86cddc1916141d6116baf0
parent2b4a8f63adc17807de29e462062e0cd1492dc920 (diff)
downloadwebob-264aa8b9cc8753e07692484732b897978c6fa8cb.tar.gz
Upgrade sample code in docs to Python 3
-rw-r--r--docs/comment-example-code/example.py105
-rw-r--r--docs/conf.py107
-rw-r--r--docs/doctests.py28
-rw-r--r--docs/jsonrpc-example-code/jsonrpc.py128
-rw-r--r--docs/jsonrpc-example-code/test_jsonrpc.py5
-rw-r--r--docs/wiki-example-code/example.py115
6 files changed, 263 insertions, 225 deletions
diff --git a/docs/comment-example-code/example.py b/docs/comment-example-code/example.py
index 5b50759..97486b1 100644
--- a/docs/comment-example-code/example.py
+++ b/docs/comment-example-code/example.py
@@ -6,8 +6,8 @@ from cPickle import load, dump
from webob import Request, Response, html_escape
from webob import exc
-class Commenter(object):
+class Commenter(object):
def __init__(self, app, storage_dir):
self.app = app
self.storage_dir = storage_dir
@@ -16,12 +16,12 @@ class Commenter(object):
def __call__(self, environ, start_response):
req = Request(environ)
- if req.path_info_peek() == '.comments':
+ if req.path_info_peek() == ".comments":
return self.process_comment(req)(environ, start_response)
# This is the base path of *this* middleware:
base_url = req.application_url
resp = req.get_response(self.app)
- if resp.content_type != 'text/html' or resp.status_code != 200:
+ if resp.content_type != "text/html" or resp.status_code != 200:
# Not an HTML response, we don't want to
# do anything to it
return resp(environ, start_response)
@@ -40,21 +40,21 @@ class Commenter(object):
if not os.path.exists(filename):
return []
else:
- f = open(filename, 'rb')
+ f = open(filename, "rb")
data = load(f)
f.close()
return data
def save_data(self, url, data):
filename = self.url_filename(url)
- f = open(filename, 'wb')
+ f = open(filename, "wb")
dump(data, f)
f.close()
def url_filename(self, url):
- return os.path.join(self.storage_dir, urllib.quote(url, ''))
+ return os.path.join(self.storage_dir, urllib.quote(url, ""))
- _end_body_re = re.compile(r'</body.*?>', re.I|re.S)
+ _end_body_re = re.compile(r"</body.*?>", re.I | re.S)
def add_to_end(self, html, extra_html):
"""
@@ -64,24 +64,31 @@ class Commenter(object):
if not match:
return html + extra_html
else:
- return html[:match.start()] + extra_html + html[match.start():]
+ return html[: match.start()] + extra_html + html[match.start() :]
def format_comments(self, comments):
if not comments:
- return ''
+ return ""
text = []
- text.append('<hr>')
- text.append('<h2><a name="comment-area"></a>Comments (%s):</h2>' % len(comments))
+ text.append("<hr>")
+ text.append(
+ '<h2><a name="comment-area"></a>Comments (%s):</h2>' % len(comments)
+ )
for comment in comments:
- text.append('<h3><a href="%s">%s</a> at %s:</h3>' % (
- html_escape(comment['homepage']), html_escape(comment['name']),
- time.strftime('%c', comment['time'])))
+ text.append(
+ '<h3><a href="%s">%s</a> at %s:</h3>'
+ % (
+ html_escape(comment["homepage"]),
+ html_escape(comment["name"]),
+ time.strftime("%c", comment["time"]),
+ )
+ )
# Susceptible to XSS attacks!:
- text.append(comment['comments'])
- return ''.join(text)
+ text.append(comment["comments"])
+ return "".join(text)
def submit_form(self, base_path, req):
- return '''<h2>Leave a comment:</h2>
+ return """<h2>Leave a comment:</h2>
<form action="%s/.comments" method="POST">
<input type="hidden" name="url" value="%s">
<table width="100%%">
@@ -94,54 +101,60 @@ class Commenter(object):
<textarea name="comments" rows=10 style="width: 100%%"></textarea><br>
<input type="submit" value="Submit comment">
</form>
- ''' % (base_path, html_escape(req.url))
+ """ % (
+ base_path,
+ html_escape(req.url),
+ )
def process_comment(self, req):
try:
- url = req.params['url']
- name = req.params['name']
- homepage = req.params['homepage']
- comments = req.params['comments']
+ url = req.params["url"]
+ name = req.params["name"]
+ homepage = req.params["homepage"]
+ comments = req.params["comments"]
except KeyError, e:
- resp = exc.HTTPBadRequest('Missing parameter: %s' % e)
+ resp = exc.HTTPBadRequest("Missing parameter: %s" % e)
return resp
data = self.get_data(url)
- data.append(dict(
- name=name,
- homepage=homepage,
- comments=comments,
- time=time.gmtime()))
+ data.append(
+ dict(name=name, homepage=homepage, comments=comments, time=time.gmtime())
+ )
self.save_data(url, data)
- resp = exc.HTTPSeeOther(location=url+'#comment-area')
+ resp = exc.HTTPSeeOther(location=url + "#comment-area")
return resp
-if __name__ == '__main__':
+
+if __name__ == "__main__":
import optparse
- parser = optparse.OptionParser(
- usage='%prog --port=PORT BASE_DIRECTORY'
- )
+
+ parser = optparse.OptionParser(usage="%prog --port=PORT BASE_DIRECTORY")
parser.add_option(
- '-p', '--port',
- default='8080',
- dest='port',
- type='int',
- help='Port to serve on (default 8080)')
+ "-p",
+ "--port",
+ default="8080",
+ dest="port",
+ type="int",
+ help="Port to serve on (default 8080)",
+ )
parser.add_option(
- '--comment-data',
- default='./comments',
- dest='comment_data',
- help='Place to put comment data into (default ./comments/)')
+ "--comment-data",
+ default="./comments",
+ dest="comment_data",
+ help="Place to put comment data into (default ./comments/)",
+ )
options, args = parser.parse_args()
if not args:
- parser.error('You must give a BASE_DIRECTORY')
+ parser.error("You must give a BASE_DIRECTORY")
base_dir = args[0]
from paste.urlparser import StaticURLParser
+
app = StaticURLParser(base_dir)
app = Commenter(app, options.comment_data)
from wsgiref.simple_server import make_server
- httpd = make_server('localhost', options.port, app)
- print 'Serving on http://localhost:%s' % options.port
+
+ httpd = make_server("localhost", options.port, app)
+ print("Serving on http://localhost:%s" % options.port)
try:
httpd.serve_forever()
except KeyboardInterrupt:
- print '^C'
+ print("^C")
diff --git a/docs/conf.py b/docs/conf.py
index 914d0f9..db67971 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -4,30 +4,30 @@ import os
import shlex
extensions = [
- 'sphinx.ext.autodoc',
- 'sphinx.ext.intersphinx',
+ "sphinx.ext.autodoc",
+ "sphinx.ext.intersphinx",
]
# Add any paths that contain templates here, relative to this directory.
-templates_path = ['_templates']
+templates_path = ["_templates"]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
-source_suffix = ['.txt', '.rst']
+source_suffix = [".txt", ".rst"]
# The encoding of source files.
-#source_encoding = 'utf-8-sig'
+# source_encoding = 'utf-8-sig'
# The master toctree document.
-master_doc = 'index'
+master_doc = "index"
# General information about the project.
-project = u'WebOb'
-copyright = u'2018, Ian Bicking, Pylons Project and contributors'
-author = u'Ian Bicking, Pylons Project, and contributors'
+project = "WebOb"
+copyright = "2018, Ian Bicking, Pylons Project and contributors"
+author = "Ian Bicking, Pylons Project, and contributors"
-version = release = pkg_resources.get_distribution('webob').version
+version = release = pkg_resources.get_distribution("webob").version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
@@ -38,84 +38,83 @@ language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
-exclude_patterns = ['_build', 'jsonrpc-example-code/*', 'file-example-code/*']
+exclude_patterns = ["_build", "jsonrpc-example-code/*", "file-example-code/*"]
# The name of the Pygments (syntax highlighting) style to use.
-pygments_style = 'sphinx'
+pygments_style = "sphinx"
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
-modindex_common_prefix = ['webob.']
+modindex_common_prefix = ["webob."]
-autodoc_member_order = 'bysource'
+autodoc_member_order = "bysource"
# -- Options for HTML output ---------------------------------------------
-html_theme = 'alabaster'
+html_theme = "alabaster"
-html_static_path = ['_static']
+html_static_path = ["_static"]
-htmlhelp_basename = 'WebObdoc'
+htmlhelp_basename = "WebObdoc"
-smartquotes=False
+smartquotes = False
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
-# The paper size ('letterpaper' or 'a4paper').
-#'papersize': 'letterpaper',
-
-# The font size ('10pt', '11pt' or '12pt').
-#'pointsize': '10pt',
-
-# Additional stuff for the LaTeX preamble.
-#'preamble': '',
-
-# Latex figure (float) alignment
-#'figure_align': 'htbp',
+ # The paper size ('letterpaper' or 'a4paper').
+ #'papersize': 'letterpaper',
+ # The font size ('10pt', '11pt' or '12pt').
+ #'pointsize': '10pt',
+ # Additional stuff for the LaTeX preamble.
+ #'preamble': '',
+ # Latex figure (float) alignment
+ #'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
- (master_doc, 'WebOb.tex', u'WebOb Documentation',
- u'Ian Bicking and contributors', 'manual'),
+ (
+ master_doc,
+ "WebOb.tex",
+ "WebOb Documentation",
+ "Ian Bicking and contributors",
+ "manual",
+ ),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
-#latex_logo = None
+# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
-#latex_use_parts = False
+# latex_use_parts = False
# If true, show page references after internal links.
-#latex_show_pagerefs = False
+# latex_show_pagerefs = False
# If true, show URL addresses after external links.
-#latex_show_urls = False
+# latex_show_urls = False
# Documents to append as an appendix to all manuals.
-#latex_appendices = []
+# latex_appendices = []
# If false, no module index is generated.
-#latex_domain_indices = True
+# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
-man_pages = [
- (master_doc, 'webob', u'WebOb Documentation',
- [author], 1)
-]
+man_pages = [(master_doc, "webob", "WebOb Documentation", [author], 1)]
# If true, show URL addresses after external links.
-#man_show_urls = False
+# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
@@ -124,22 +123,28 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
- (master_doc, 'WebOb', u'WebOb Documentation',
- author, 'WebOb', 'One line description of project.',
- 'Miscellaneous'),
+ (
+ master_doc,
+ "WebOb",
+ "WebOb Documentation",
+ author,
+ "WebOb",
+ "One line description of project.",
+ "Miscellaneous",
+ ),
]
# Documents to append as an appendix to all manuals.
-#texinfo_appendices = []
+# texinfo_appendices = []
# If false, no module index is generated.
-#texinfo_domain_indices = True
+# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
-#texinfo_show_urls = 'footnote'
+# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
-#texinfo_no_detailmenu = False
+# texinfo_no_detailmenu = False
# -- Options for Epub output ----------------------------------------------
@@ -150,9 +155,9 @@ epub_author = author
epub_publisher = author
epub_copyright = copyright
-epub_exclude_files = ['search.html']
+epub_exclude_files = ["search.html"]
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
- 'python': ('https://docs.python.org/3', None),
+ "python": ("https://docs.python.org/3", None),
}
diff --git a/docs/doctests.py b/docs/doctests.py
index 9aecb31..a84a19b 100644
--- a/docs/doctests.py
+++ b/docs/doctests.py
@@ -1,17 +1,21 @@
import unittest
import doctest
+
def test_suite():
- flags = doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE
- return unittest.TestSuite((
- doctest.DocFileSuite('test_request.txt', optionflags=flags),
- doctest.DocFileSuite('test_response.txt', optionflags=flags),
- doctest.DocFileSuite('test_dec.txt', optionflags=flags),
- doctest.DocFileSuite('do-it-yourself.txt', optionflags=flags),
- doctest.DocFileSuite('file-example.txt', optionflags=flags),
- doctest.DocFileSuite('index.txt', optionflags=flags),
- doctest.DocFileSuite('reference.txt', optionflags=flags),
- ))
+ flags = doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE
+ return unittest.TestSuite(
+ (
+ doctest.DocFileSuite("test_request.txt", optionflags=flags),
+ doctest.DocFileSuite("test_response.txt", optionflags=flags),
+ doctest.DocFileSuite("test_dec.txt", optionflags=flags),
+ doctest.DocFileSuite("do-it-yourself.txt", optionflags=flags),
+ doctest.DocFileSuite("file-example.txt", optionflags=flags),
+ doctest.DocFileSuite("index.txt", optionflags=flags),
+ doctest.DocFileSuite("reference.txt", optionflags=flags),
+ )
+ )
+
-if __name__ == '__main__':
- unittest.main(defaultTest='test_suite')
+if __name__ == "__main__":
+ unittest.main(defaultTest="test_suite")
diff --git a/docs/jsonrpc-example-code/jsonrpc.py b/docs/jsonrpc-example-code/jsonrpc.py
index c038992..dbb95ba 100644
--- a/docs/jsonrpc-example-code/jsonrpc.py
+++ b/docs/jsonrpc-example-code/jsonrpc.py
@@ -5,6 +5,7 @@ from simplejson import loads, dumps
import traceback
import sys
+
class JsonRpcApp(object):
"""
Serve the given object via json-rpc (http://json-rpc.org/)
@@ -24,53 +25,45 @@ class JsonRpcApp(object):
return resp(environ, start_response)
def process(self, req):
- if not req.method == 'POST':
- raise exc.HTTPMethodNotAllowed(
- "Only POST allowed",
- allowed='POST')
+ if not req.method == "POST":
+ raise exc.HTTPMethodNotAllowed("Only POST allowed", allowed="POST")
try:
json = loads(req.body)
except ValueError, e:
- raise ValueError('Bad JSON: %s' % e)
+ raise ValueError("Bad JSON: %s" % e)
try:
- method = json['method']
- params = json['params']
- id = json['id']
+ method = json["method"]
+ params = json["params"]
+ id = json["id"]
except KeyError, e:
- raise ValueError(
- "JSON body missing parameter: %s" % e)
- if method.startswith('_'):
+ raise ValueError("JSON body missing parameter: %s" % e)
+ if method.startswith("_"):
raise exc.HTTPForbidden(
- "Bad method name %s: must not start with _" % method)
+ "Bad method name %s: must not start with _" % method
+ )
if not isinstance(params, list):
- raise ValueError(
- "Bad params %r: must be a list" % params)
+ raise ValueError("Bad params %r: must be a list" % params)
try:
method = getattr(self.obj, method)
except AttributeError:
- raise ValueError(
- "No such method %s" % method)
+ raise ValueError("No such method %s" % method)
try:
result = method(*params)
except:
text = traceback.format_exc()
exc_value = sys.exc_info()[1]
error_value = dict(
- name='JSONRPCError',
- code=100,
- message=str(exc_value),
- error=text)
+ name="JSONRPCError", code=100, message=str(exc_value), error=text
+ )
return Response(
status=500,
- content_type='application/json',
- body=dumps(dict(result=None,
- error=error_value,
- id=id)))
+ content_type="application/json",
+ body=dumps(dict(result=None, error=error_value, id=id)),
+ )
return Response(
- content_type='application/json',
- body=dumps(dict(result=result,
- error=None,
- id=id)))
+ content_type="application/json",
+ body=dumps(dict(result=result, error=None, id=id)),
+ )
class ServerProxy(object):
@@ -82,112 +75,127 @@ class ServerProxy(object):
self._url = url
if proxy is None:
from wsgiproxy.exactproxy import proxy_exact_request
+
proxy = proxy_exact_request
self.proxy = proxy
def __getattr__(self, name):
- if name.startswith('_'):
+ if name.startswith("_"):
raise AttributeError(name)
return _Method(self, name)
def __repr__(self):
- return '<%s for %s>' % (
- self.__class__.__name__, self._url)
+ return "<%s for %s>" % (self.__class__.__name__, self._url)
-class _Method(object):
+class _Method(object):
def __init__(self, parent, name):
self.parent = parent
self.name = name
def __call__(self, *args):
- json = dict(method=self.name,
- id=None,
- params=list(args))
+ json = dict(method=self.name, id=None, params=list(args))
req = Request.blank(self.parent._url)
- req.method = 'POST'
- req.content_type = 'application/json'
+ req.method = "POST"
+ req.content_type = "application/json"
req.body = dumps(json)
resp = req.get_response(self.parent.proxy)
if resp.status_code != 200 and not (
- resp.status_code == 500
- and resp.content_type == 'application/json'):
+ resp.status_code == 500 and resp.content_type == "application/json"
+ ):
raise ProxyError(
- "Error from JSON-RPC client %s: %s"
- % (self.parent._url, resp.status),
- resp)
+ "Error from JSON-RPC client %s: %s" % (self.parent._url, resp.status),
+ resp,
+ )
json = loads(resp.body)
- if json.get('error') is not None:
+ if json.get("error") is not None:
e = Fault(
- json['error'].get('message'),
- json['error'].get('code'),
- json['error'].get('error'),
- resp)
+ json["error"].get("message"),
+ json["error"].get("code"),
+ json["error"].get("error"),
+ resp,
+ )
raise e
- return json['result']
+ return json["result"]
+
class ProxyError(Exception):
"""
Raised when a request via ServerProxy breaks
"""
+
def __init__(self, message, response):
Exception.__init__(self, message)
self.response = response
+
class Fault(Exception):
"""
Raised when there is a remote error
"""
+
def __init__(self, message, code, error, response):
Exception.__init__(self, message)
self.code = code
self.error = error
self.response = response
+
def __str__(self):
- return 'Method error calling %s: %s\n%s' % (
+ return "Method error calling %s: %s\n%s" % (
self.response.request.url,
self.args[0],
- self.error)
+ self.error,
+ )
+
class DemoObject(object):
"""
Something interesting to attach to
"""
+
def add(self, *args):
return sum(args)
+
def average(self, *args):
return sum(args) / float(len(args))
+
def divide(self, a, b):
return a / b
+
def make_app(expr):
- module, expression = expr.split(':', 1)
+ module, expression = expr.split(":", 1)
__import__(module)
module = sys.modules[module]
obj = eval(expression, module.__dict__)
return JsonRpcApp(obj)
+
def main(args=None):
import optparse
from wsgiref import simple_server
- parser = optparse.OptionParser(
- usage='%prog [OPTIONS] MODULE:EXPRESSION')
+
+ parser = optparse.OptionParser(usage="%prog [OPTIONS] MODULE:EXPRESSION")
parser.add_option(
- '-p', '--port', default='8080',
- help='Port to serve on (default 8080)')
+ "-p", "--port", default="8080", help="Port to serve on (default 8080)"
+ )
parser.add_option(
- '-H', '--host', default='127.0.0.1',
- help='Host to serve on (default localhost; 0.0.0.0 to make public)')
+ "-H",
+ "--host",
+ default="127.0.0.1",
+ help="Host to serve on (default localhost; 0.0.0.0 to make public)",
+ )
options, args = parser.parse_args()
if not args or len(args) > 1:
- print 'You must give a single object reference'
+ print("You must give a single object reference")
parser.print_help()
sys.exit(2)
app = make_app(args[0])
server = simple_server.make_server(options.host, int(options.port), app)
- print 'Serving on http://%s:%s' % (options.host, options.port)
+ print("Serving on http://%s:%s" % (options.host, options.port))
server.serve_forever()
# Try python jsonrpc.py 'jsonrpc:DemoObject()'
-if __name__ == '__main__':
+
+if __name__ == "__main__":
main()
diff --git a/docs/jsonrpc-example-code/test_jsonrpc.py b/docs/jsonrpc-example-code/test_jsonrpc.py
index a418516..a688f1d 100644
--- a/docs/jsonrpc-example-code/test_jsonrpc.py
+++ b/docs/jsonrpc-example-code/test_jsonrpc.py
@@ -1,3 +1,4 @@
-if __name__ == '__main__':
+if __name__ == "__main__":
import doctest
- doctest.testfile('test_jsonrpc.txt')
+
+ doctest.testfile("test_jsonrpc.txt")
diff --git a/docs/wiki-example-code/example.py b/docs/wiki-example-code/example.py
index 2d452c7..f5edd9f 100644
--- a/docs/wiki-example-code/example.py
+++ b/docs/wiki-example-code/example.py
@@ -4,7 +4,8 @@ from webob import Request, Response
from webob import exc
from tempita import HTMLTemplate
-VIEW_TEMPLATE = HTMLTemplate("""\
+VIEW_TEMPLATE = HTMLTemplate(
+ """\
<html>
<head>
<title>{{page.title}}</title>
@@ -21,9 +22,11 @@ VIEW_TEMPLATE = HTMLTemplate("""\
<a href="{{req.url}}?action=edit">Edit</a>
</body>
</html>
-""")
+"""
+)
-EDIT_TEMPLATE = HTMLTemplate("""\
+EDIT_TEMPLATE = HTMLTemplate(
+ """\
<html>
<head>
<title>Edit: {{page.title}}</title>
@@ -47,7 +50,9 @@ EDIT_TEMPLATE = HTMLTemplate("""\
<a href="{{req.path_url}}">Cancel</a>
</form>
</body></html>
-""")
+"""
+)
+
class WikiApp(object):
@@ -59,67 +64,63 @@ class WikiApp(object):
def __call__(self, environ, start_response):
req = Request(environ)
- action = req.params.get('action', 'view')
+ action = req.params.get("action", "view")
page = self.get_page(req.path_info)
try:
try:
- meth = getattr(self, 'action_%s_%s' % (action, req.method))
+ meth = getattr(self, "action_%s_%s" % (action, req.method))
except AttributeError:
- raise exc.HTTPBadRequest('No such action %r' % action)
+ raise exc.HTTPBadRequest("No such action %r" % action)
resp = meth(req, page)
except exc.HTTPException, e:
resp = e
return resp(environ, start_response)
def get_page(self, path):
- path = path.lstrip('/')
+ path = path.lstrip("/")
if not path:
- path = 'index'
+ path = "index"
path = os.path.join(self.storage_dir, path)
path = os.path.normpath(path)
- if path.endswith('/'):
- path += 'index'
+ if path.endswith("/"):
+ path += "index"
if not path.startswith(self.storage_dir):
raise exc.HTTPBadRequest("Bad path")
- path += '.html'
+ path += ".html"
return Page(path)
def action_view_GET(self, req, page):
if not page.exists:
- return exc.HTTPTemporaryRedirect(
- location=req.url + '?action=edit')
- if req.cookies.get('message'):
- message = req.cookies['message']
+ return exc.HTTPTemporaryRedirect(location=req.url + "?action=edit")
+ if req.cookies.get("message"):
+ message = req.cookies["message"]
else:
message = None
- text = self.view_template.substitute(
- page=page, req=req, message=message)
+ text = self.view_template.substitute(page=page, req=req, message=message)
resp = Response(text)
if message:
- resp.delete_cookie('message')
+ resp.delete_cookie("message")
else:
resp.last_modified = page.mtime
resp.conditional_response = True
return resp
def action_view_POST(self, req, page):
- submit_mtime = int(req.params.get('mtime') or '0') or None
+ submit_mtime = int(req.params.get("mtime") or "0") or None
if page.mtime != submit_mtime:
return exc.HTTPPreconditionFailed(
- "The page has been updated since you started editing it")
- page.set(
- title=req.params['title'],
- content=req.params['content'])
- resp = exc.HTTPSeeOther(
- location=req.path_url)
- resp.set_cookie('message', 'Page updated')
+ "The page has been updated since you started editing it"
+ )
+ page.set(title=req.params["title"], content=req.params["content"])
+ resp = exc.HTTPSeeOther(location=req.path_url)
+ resp.set_cookie("message", "Page updated")
return resp
def action_edit_GET(self, req, page):
- text = self.edit_template.substitute(
- page=page, req=req)
+ text = self.edit_template.substitute(page=page, req=req)
return Response(text)
+
class Page(object):
def __init__(self, filename):
self.filename = filename
@@ -133,15 +134,15 @@ class Page(object):
if not self.exists:
# we need to guess the title
basename = os.path.splitext(os.path.basename(self.filename))[0]
- basename = re.sub(r'[_-]', ' ', basename)
+ basename = re.sub(r"[_-]", " ", basename)
return basename.capitalize()
content = self.full_content
- match = re.search(r'<title>(.*?)</title>', content, re.I|re.S)
+ match = re.search(r"<title>(.*?)</title>", content, re.I | re.S)
return match.group(1)
@property
def full_content(self):
- f = open(self.filename, 'rb')
+ f = open(self.filename, "rb")
try:
return f.read()
finally:
@@ -150,9 +151,9 @@ class Page(object):
@property
def content(self):
if not self.exists:
- return ''
+ return ""
content = self.full_content
- match = re.search(r'<body[^>]*>(.*?)</body>', content, re.I|re.S)
+ match = re.search(r"<body[^>]*>(.*?)</body>", content, re.I | re.S)
return match.group(1)
@property
@@ -166,35 +167,41 @@ class Page(object):
dir = os.path.dirname(self.filename)
if not os.path.exists(dir):
os.makedirs(dir)
- new_content = """<html><head><title>%s</title></head><body>%s</body></html>""" % (
- title, content)
- f = open(self.filename, 'wb')
+ new_content = (
+ """<html><head><title>%s</title></head><body>%s</body></html>"""
+ % (title, content)
+ )
+ f = open(self.filename, "wb")
f.write(new_content)
f.close()
-if __name__ == '__main__':
+
+if __name__ == "__main__":
import optparse
- parser = optparse.OptionParser(
- usage='%prog --port=PORT'
- )
+
+ parser = optparse.OptionParser(usage="%prog --port=PORT")
parser.add_option(
- '-p', '--port',
- default='8080',
- dest='port',
- type='int',
- help='Port to serve on (default 8080)')
+ "-p",
+ "--port",
+ default="8080",
+ dest="port",
+ type="int",
+ help="Port to serve on (default 8080)",
+ )
parser.add_option(
- '--wiki-data',
- default='./wiki',
- dest='wiki_data',
- help='Place to put wiki data into (default ./wiki/)')
+ "--wiki-data",
+ default="./wiki",
+ dest="wiki_data",
+ help="Place to put wiki data into (default ./wiki/)",
+ )
options, args = parser.parse_args()
- print 'Writing wiki pages to %s' % options.wiki_data
+ print("Writing wiki pages to %s" % options.wiki_data)
app = WikiApp(options.wiki_data)
from wsgiref.simple_server import make_server
- httpd = make_server('localhost', options.port, app)
- print 'Serving on http://localhost:%s' % options.port
+
+ httpd = make_server("localhost", options.port, app)
+ print("Serving on http://localhost:%s" % options.port)
try:
httpd.serve_forever()
except KeyboardInterrupt:
- print '^C'
+ print("^C")