From 5b10a25c59ccb636dc58f797950952806f3ed1ef Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Mon, 1 Jun 2009 02:23:49 +0000 Subject: Add defining views chapter. --- docs/tutorials/bfgwiki2/definingviews.rst | 320 +++++++++++++++++ docs/tutorials/bfgwiki2/src/views/CHANGES.txt | 3 + docs/tutorials/bfgwiki2/src/views/README.txt | 4 + docs/tutorials/bfgwiki2/src/views/ez_setup.py | 276 +++++++++++++++ docs/tutorials/bfgwiki2/src/views/setup.cfg | 6 + docs/tutorials/bfgwiki2/src/views/setup.py | 52 +++ docs/tutorials/bfgwiki2/src/views/tutorial.ini | 20 ++ .../bfgwiki2/src/views/tutorial/__init__.py | 2 + .../bfgwiki2/src/views/tutorial/configure.zcml | 38 +++ .../bfgwiki2/src/views/tutorial/models.py | 43 +++ docs/tutorials/bfgwiki2/src/views/tutorial/run.py | 27 ++ .../bfgwiki2/src/views/tutorial/templates/edit.pt | 30 ++ .../src/views/tutorial/templates/mytemplate.pt | 99 ++++++ .../src/views/tutorial/templates/mytemplate.pt.py | 110 ++++++ .../views/tutorial/templates/static/default.css | 380 +++++++++++++++++++++ .../tutorial/templates/static/images/img01.gif | Bin 0 -> 3840 bytes .../tutorial/templates/static/images/img02.gif | Bin 0 -> 4689 bytes .../tutorial/templates/static/images/img03.gif | Bin 0 -> 229 bytes .../tutorial/templates/static/images/img04.gif | Bin 0 -> 92 bytes .../tutorial/templates/static/images/spacer.gif | Bin 0 -> 43 bytes .../src/views/tutorial/templates/static/style.css | 109 ++++++ .../tutorial/templates/static/templatelicense.txt | 243 +++++++++++++ .../bfgwiki2/src/views/tutorial/templates/view.pt | 27 ++ .../tutorials/bfgwiki2/src/views/tutorial/tests.py | 28 ++ .../tutorials/bfgwiki2/src/views/tutorial/views.py | 76 +++++ 25 files changed, 1893 insertions(+) create mode 100644 docs/tutorials/bfgwiki2/definingviews.rst create mode 100644 docs/tutorials/bfgwiki2/src/views/CHANGES.txt create mode 100644 docs/tutorials/bfgwiki2/src/views/README.txt create mode 100644 docs/tutorials/bfgwiki2/src/views/ez_setup.py create mode 100644 docs/tutorials/bfgwiki2/src/views/setup.cfg create mode 100644 docs/tutorials/bfgwiki2/src/views/setup.py create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial.ini create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/__init__.py create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/configure.zcml create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/models.py create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/run.py create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/templates/edit.pt create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/templates/mytemplate.pt create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/templates/mytemplate.pt.py create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/templates/static/default.css create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/templates/static/images/img01.gif create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/templates/static/images/img02.gif create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/templates/static/images/img03.gif create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/templates/static/images/img04.gif create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/templates/static/images/spacer.gif create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/templates/static/style.css create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/templates/static/templatelicense.txt create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/templates/view.pt create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/tests.py create mode 100644 docs/tutorials/bfgwiki2/src/views/tutorial/views.py (limited to 'docs/tutorials') diff --git a/docs/tutorials/bfgwiki2/definingviews.rst b/docs/tutorials/bfgwiki2/definingviews.rst new file mode 100644 index 000000000..0efd2ce21 --- /dev/null +++ b/docs/tutorials/bfgwiki2/definingviews.rst @@ -0,0 +1,320 @@ +============== +Defining Views +============== + +Views in BFG are typically simple Python functions that accept two +parameters: :term:`context`, and :term:`request`. A view is assumed +to return a :term:`response` object. + +A invocation of a view that matches a URL via :term:`url dispatch` +passes as the context object an object which has attributes matching +the elements placed into the URL by the ``path`` of a ``route`` +statement. For instance, if a route statement in ``configure.zcml`` +had the path ``:one/:two``, and the URL at +``http://example.com/foo/bar`` was invoked, matching this path, the +context object passed to the view would have a ``one`` attribute withe +the value ``foo`` and a ``two`` attribute with the value ``bar``. + +Declaring Dependencies in Our ``setup.py`` File +=============================================== + +Our application will depend on packages which are not dependencies of +the original "tutorial" application as it was generated by the +``paster create`` command. We'll add these dependencies to our +``tutorial`` package's ``setup.py`` file by assigning these +dependencies to both the ``install_requires`` and the +``tests_require`` parameters to the ``setup`` function. In +particular, we require the ``docutils`` package. + +Our resulting ``setup.py`` should look like so: + +.. literalinclude:: src/views/setup.py + :linenos: + :language: python + +Adding View Functions +===================== + +We'll get rid of our ``my_view`` view in our ``views.py`` file. It's +only an example and isn't relevant to our application. + +Then we're going to add four :term:`view` functions to our +``views.py`` module. One view (named ``view_wiki``) will display the +wiki itself (it will answer on the root URL), another named +``view_page`` will display an individual page, another named +``add_page`` will allow a page to be added, and a final view named +``edit_page`` will allow a page to be edited. + +.. note:: + + There is nothing automagically special about the filename + ``views.py``. A project may have many views throughout its codebase + in arbitrarily-named files. Files implementing views often have + ``view`` in their filenames (or may live in a Python subpackage of + your application package named ``views``), but this is only by + convention. + +The ``view_wiki`` view function +------------------------------- + +The ``view_wiki`` function will respond as the default view of a +``Wiki`` model object. It always redirects to a URL which represents +the path to our "FrontPage". It returns an instance of the +``webob.exc.HTTPFound`` class (instances of which implement the WebOb +:term:`response` interface), It will use the the ``routes.url_for`` +API to construct a URL to the ``FrontPage`` page +(e.g. ``http://localhost:6543/FrontPage``), and will use it as the +"location" of the HTTPFound response, forming an HTTP redirect. + + +The ``view_page`` view function +------------------------------- + +The ``view_page`` function will respond as the default view of a +``Page`` object. The ``view_page`` function renders the +:term:`ReStructuredText` body of a page (stored as the ``data`` +attribute of a Page object) as HTML. Then it substitutes an HTML +anchor for each *WikiWord* reference in the rendered HTML using a +compiled regular expression. + +The curried function named ``check`` is used as the first argument to +``wikiwords.sub``, indicating that it should be called to provide a +value for each WikiWord match found in the content. If the wiki +already contains a page with the matched WikiWord name, the ``check`` +function generates a view link to be used as the substitution value +and returns it. If the wiki does not already contain a page with with +the matched WikiWord name, the function generates an "add" link as the +subsitution value and returns it. + +As a result, the ``content`` variable is now a fully formed bit of +HTML containing various view and add links for WikiWords based on the +content of our current page object. + +We then generate an edit URL (because it's easier to do here than in +the template), and we call the +``repoze.bfg.chameleon_zpt.render_template_to_response`` function with +a number of arguments. The first argument is the *relative* path to a +:term:`Chameleon` ZPT template. It is relative to the directory of +the file in which we're creating the ``view_page`` function. The +``render_template_to_response`` function also accepts ``request``, +``page``, ``content``, and ``edit_url`` as keyword arguments. As a +result, the template will be able to use these names to perform +various rendering tasks. + +The result of ``render_template_to_response`` is returned to +:mod:`repoze.bfg`. Unsurprisingly, it is a response object. + +The ``add_page`` view function +------------------------------ + +The ``add_page`` function will be invoked when a user clicks on a +*WikiWord* which isn't yet represented as a page in the system. The +``check`` function within the ``view_page`` view generates URLs to +this view. It also acts as a handler for the form that is generated +when we want to add a page object. The ``context`` of the +``add_page`` view is will always have the attributes we need to +construct URLs and find model objects. + +The context object will have a ``pagename`` attribute that matches the +name of the page we'd like to add. If our add view is invoked via, +e.g. ``http://localhost:6543/add_page/SomeName``, the :term:`pagename` +attribute of the context will be ``SomeName``. + +If the view rendering is *not* a result of a form submission (if the +expression ``'form.submitted' in request.params`` is False), the view +renders a template. To do so, it generates a "save url" which the +template use as the form post URL during rendering. We're lazy here, +so we're trying to use the same template (``templates/edit.pt``) for +the add view as well as the page edit view, so we create a dummy Page +object in order to satisfy the edit form's desire to have *some* page +object exposed as ``page``, and we'll render the template to a +response. + +If the view rendering *is* a result of a form submission (if the +expression ``'form.submitted' in request.params`` is True), we scrape +the page body from the form data, create a Page object using the name +in ``pagename`` context attribute and obtain the page body from the +request, and save it into the database using ``session.add``. We then +redirect back to the ``view_page`` view (the default view for a page) +for the newly created page. + +The ``edit_page`` view function +------------------------------- + +The ``edit_page`` function will be invoked when a user clicks the +"Edit this Page" button on the view form. It renders an edit form but +it also acts as the handler for the form it renders. The ``context`` +of the ``edit_page`` view will *always* have a ``pagename`` attribute +matching the name of the page the user wants to edit. + +If the view rendering is *not* a result of a form submission (if the +expression ``'form.submitted' in request.params`` is False), the view +simply renders the edit form, passing the request, the page object, +and a save_url which will be used as the action of the generated form. + +If the view rendering *is* a result of a form submission (if the +expression ``'form.submitted' in request.params`` is True), the view +grabs the ``body`` element of the request parameter and sets it as the +``data`` attribute of the page context. It then redirects to the +default view of the context (the page), which will always be the +``view_page`` view. + +Viewing the Result of Our Edits to ``views.py`` +=============================================== + +The result of all of our edits to ``views.py`` will leave it looking +like this: + +.. literalinclude:: src/views/tutorial/views.py + :linenos: + :language: python + +Adding Templates +================ + +The views we've added all reference a :term:`template`. Each template +is a :term:`Chameleon` template. The default templating system in +:mod:`repoze.bfg` is a variant of :term:`ZPT` provided by Chameleon. +These templates will live in the ``templates`` directory of our +tutorial package. + +The ``view.pt`` Template +------------------------ + +The ``view.pt`` template is used for viewing a single wiki page. It +is used by the ``view_page`` view function. It should have a div that +is "structure replaced" with the ``content`` value provided by the +view. It should also have a link on the rendered page that points at +the "edit" URL (the URL which invokes the ``edit_page`` view for the +page being viewed). + +Once we're done with the ``view.pt`` template, it will look a lot like +the below: + +.. literalinclude:: src/views/tutorial/templates/view.pt + :linenos: + :language: xml + + +The ``edit.pt`` Template +------------------------ + +The ``edit.pt`` template is used for adding and editing a wiki page. +It is used by the ``add_page`` and ``edit_page`` view functions. It +should display a page containing a form that POSTs back to the +"save_url" argument supplied by the view. The form should have a +"body" textarea field (the page data), and a submit button that has +the name "form.submitted". The textarea in the form should be filled +with any existing page data when it is rendered. + +Once we're done with the ``edit.pt`` template, it will look a lot like +the below: + +.. literalinclude:: src/views/tutorial/templates/edit.pt + :linenos: + :language: xml + +Static Resources +---------------- + +Our templates name a single static resource named ``style.css``. We +need to create this and place it in a file named ``style.css`` within +our package's ``templates/static`` directory: + +.. literalinclude:: src/views/tutorial/templates/static/style.css + :linenos: + :language: css + +This CSS file will be accessed via +e.g. ``http://localhost:6543/static/style.css`` by virtue of the +``static_view`` view we've defined in the ``views.py`` file. Any +number and type of static resources can be placed in this directory +(or subdirectories) and are just referred to by URL within templates. + +Mapping Views to URLs in ``configure.zcml`` +=========================================== + +The ``configure.zcml`` file contains ``route`` declarations which +serve to map URLs (via :term:`url dispatch`) to view functions. +You'll need to add five ``view`` declarations to ``configure.zcml``. + +#. Add a declaration which maps the empty path (signifying the root + URL) to the view named ``view_wiki`` in our ``views.py`` file with + the name ``view_wiki``. This is the default view for the wiki. + +#. Add a declaration which maps the path pattern ``:pagename`` to the + view named ``edit_page`` in our ``views.py`` file with the view + name ``view_page``. This is the edit view for a page. + +#. Add a declaration which maps the path pattern + ``:pagename/edit_page`` to the view named ``view_page`` in our + ``views.py`` file with the name ``edit_page``. This is the edit view + for a page. + +#. Add a declaration which maps the path pattern + ``add_page/:pagename`` to the view named ``add_page`` in our + ``views.py`` file with the name ``add_page``. This is the add view + for a new page. + +As a result of our edits, the ``configure.zcml`` file should look +something like so: + +.. literalinclude:: src/views/tutorial/configure.zcml + :linenos: + :language: xml + +The WSGI Pipeline +----------------- + +Within ``tutorial.ini``, note the existence of a ``[pipeline:main]`` +section which specifies our WSGI pipeline. This "pipeline" will be +served up as our WSGI application. As far as the WSGI server is +concerned the pipeline *is* our application. Simpler configurations +don't use a pipeline: instead they expose a single WSGI application as +"main". Our setup is more complicated, so we use a pipeline. + +"egg:repoze.tm2#tm" is at the "top" of the pipeline. This is a piece +of middleware which commits a transaction if no exception occurs; if +an exception occurs, the transaction will be aborted. This is the +piece of software that allows us to forget about needing to do manual +commits and aborts of our database connection in view code. + +Adding an Element to the Pipeline +--------------------------------- + +Let's add a piece of middleware to the WSGI pipeline. +"egg:Paste#evalerror" middleware which displays debuggable errors in +the browser while you're developing (not recommeded for deployment). +Let's insert evalerror into the pipeline right above +"egg:repoze.tm2#tm", making our resulting ``tutorial.ini`` file look +like so: + +.. literalinclude:: src/views/tutorial.ini + :linenos: + :language: ini + +Viewing the Application in a Browser +==================================== + +Once we've set up the WSGI pipeline properly, we can finally examine +our application in a browser. The views we'll try are as follows: + +- Visiting `http://localhost:6543/ `_ in a + browser invokes the ``view_wiki`` view. This always redirects to + the ``view_page`` view of the FrontPage page object. + +- Visiting `http://localhost:6543/FrontPage/ + `_ in a browser invokes the + ``view_page`` view of the front page page object. + +- Visiting `http://localhost:6543/FrontPage/edit_page + `_ in a browser invokes + the edit view for the front page object. + +- Visiting `http://localhost:6543/add_page/SomePageName + `_ in a browser invokes + the add view for a page. + +Try generating an error in a view by typing some bad code. Then hit +the view. You should see an interactive exception handler in the +browser which allows you to examine values in a post-mortem mode. diff --git a/docs/tutorials/bfgwiki2/src/views/CHANGES.txt b/docs/tutorials/bfgwiki2/src/views/CHANGES.txt new file mode 100644 index 000000000..1544cf53b --- /dev/null +++ b/docs/tutorials/bfgwiki2/src/views/CHANGES.txt @@ -0,0 +1,3 @@ +0.1 + + Initial version diff --git a/docs/tutorials/bfgwiki2/src/views/README.txt b/docs/tutorials/bfgwiki2/src/views/README.txt new file mode 100644 index 000000000..d41f7f90f --- /dev/null +++ b/docs/tutorials/bfgwiki2/src/views/README.txt @@ -0,0 +1,4 @@ +tutorial README + + + diff --git a/docs/tutorials/bfgwiki2/src/views/ez_setup.py b/docs/tutorials/bfgwiki2/src/views/ez_setup.py new file mode 100644 index 000000000..d24e845e5 --- /dev/null +++ b/docs/tutorials/bfgwiki2/src/views/ez_setup.py @@ -0,0 +1,276 @@ +#!python +"""Bootstrap setuptools installation + +If you want to use setuptools in your package's setup.py, just include this +file in the same directory with it, and add this to the top of your setup.py:: + + from ez_setup import use_setuptools + use_setuptools() + +If you want to require a specific version of setuptools, set a download +mirror, or use an alternate download directory, you can do so by supplying +the appropriate options to ``use_setuptools()``. + +This file can also be run as a script to install or upgrade setuptools. +""" +import sys +DEFAULT_VERSION = "0.6c9" +DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3] + +md5_data = { + 'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca', + 'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb', + 'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b', + 'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a', + 'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618', + 'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac', + 'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5', + 'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4', + 'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c', + 'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b', + 'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27', + 'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277', + 'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa', + 'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e', + 'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e', + 'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f', + 'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2', + 'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc', + 'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167', + 'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64', + 'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d', + 'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20', + 'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab', + 'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53', + 'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2', + 'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e', + 'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372', + 'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902', + 'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de', + 'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b', + 'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03', + 'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a', + 'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6', + 'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a', +} + +import sys, os +try: from hashlib import md5 +except ImportError: from md5 import md5 + +def _validate_md5(egg_name, data): + if egg_name in md5_data: + digest = md5(data).hexdigest() + if digest != md5_data[egg_name]: + print >>sys.stderr, ( + "md5 validation of %s failed! (Possible download problem?)" + % egg_name + ) + sys.exit(2) + return data + +def use_setuptools( + version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, + download_delay=15 +): + """Automatically find/download setuptools and make it available on sys.path + + `version` should be a valid setuptools version number that is available + as an egg for download under the `download_base` URL (which should end with + a '/'). `to_dir` is the directory where setuptools will be downloaded, if + it is not already available. If `download_delay` is specified, it should + be the number of seconds that will be paused before initiating a download, + should one be required. If an older version of setuptools is installed, + this routine will print a message to ``sys.stderr`` and raise SystemExit in + an attempt to abort the calling script. + """ + was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules + def do_download(): + egg = download_setuptools(version, download_base, to_dir, download_delay) + sys.path.insert(0, egg) + import setuptools; setuptools.bootstrap_install_from = egg + try: + import pkg_resources + except ImportError: + return do_download() + try: + pkg_resources.require("setuptools>="+version); return + except pkg_resources.VersionConflict, e: + if was_imported: + print >>sys.stderr, ( + "The required version of setuptools (>=%s) is not available, and\n" + "can't be installed while this script is running. Please install\n" + " a more recent version first, using 'easy_install -U setuptools'." + "\n\n(Currently using %r)" + ) % (version, e.args[0]) + sys.exit(2) + else: + del pkg_resources, sys.modules['pkg_resources'] # reload ok + return do_download() + except pkg_resources.DistributionNotFound: + return do_download() + +def download_setuptools( + version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, + delay = 15 +): + """Download setuptools from a specified location and return its filename + + `version` should be a valid setuptools version number that is available + as an egg for download under the `download_base` URL (which should end + with a '/'). `to_dir` is the directory where the egg will be downloaded. + `delay` is the number of seconds to pause before an actual download attempt. + """ + import urllib2, shutil + egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3]) + url = download_base + egg_name + saveto = os.path.join(to_dir, egg_name) + src = dst = None + if not os.path.exists(saveto): # Avoid repeated downloads + try: + from distutils import log + if delay: + log.warn(""" +--------------------------------------------------------------------------- +This script requires setuptools version %s to run (even to display +help). I will attempt to download it for you (from +%s), but +you may need to enable firewall access for this script first. +I will start the download in %d seconds. + +(Note: if this machine does not have network access, please obtain the file + + %s + +and place it in this directory before rerunning this script.) +---------------------------------------------------------------------------""", + version, download_base, delay, url + ); from time import sleep; sleep(delay) + log.warn("Downloading %s", url) + src = urllib2.urlopen(url) + # Read/write all in one block, so we don't create a corrupt file + # if the download is interrupted. + data = _validate_md5(egg_name, src.read()) + dst = open(saveto,"wb"); dst.write(data) + finally: + if src: src.close() + if dst: dst.close() + return os.path.realpath(saveto) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +def main(argv, version=DEFAULT_VERSION): + """Install or upgrade setuptools and EasyInstall""" + try: + import setuptools + except ImportError: + egg = None + try: + egg = download_setuptools(version, delay=0) + sys.path.insert(0,egg) + from setuptools.command.easy_install import main + return main(list(argv)+[egg]) # we're done here + finally: + if egg and os.path.exists(egg): + os.unlink(egg) + else: + if setuptools.__version__ == '0.0.1': + print >>sys.stderr, ( + "You have an obsolete version of setuptools installed. Please\n" + "remove it from your system entirely before rerunning this script." + ) + sys.exit(2) + + req = "setuptools>="+version + import pkg_resources + try: + pkg_resources.require(req) + except pkg_resources.VersionConflict: + try: + from setuptools.command.easy_install import main + except ImportError: + from easy_install import main + main(list(argv)+[download_setuptools(delay=0)]) + sys.exit(0) # try to force an exit + else: + if argv: + from setuptools.command.easy_install import main + main(argv) + else: + print "Setuptools version",version,"or greater has been installed." + print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)' + +def update_md5(filenames): + """Update our built-in md5 registry""" + + import re + + for name in filenames: + base = os.path.basename(name) + f = open(name,'rb') + md5_data[base] = md5(f.read()).hexdigest() + f.close() + + data = [" %r: %r,\n" % it for it in md5_data.items()] + data.sort() + repl = "".join(data) + + import inspect + srcfile = inspect.getsourcefile(sys.modules[__name__]) + f = open(srcfile, 'rb'); src = f.read(); f.close() + + match = re.search("\nmd5_data = {\n([^}]+)}", src) + if not match: + print >>sys.stderr, "Internal error!" + sys.exit(2) + + src = src[:match.start(1)] + repl + src[match.end(1):] + f = open(srcfile,'w') + f.write(src) + f.close() + + +if __name__=='__main__': + if len(sys.argv)>2 and sys.argv[1]=='--md5update': + update_md5(sys.argv[2:]) + else: + main(sys.argv[1:]) + + + + + + diff --git a/docs/tutorials/bfgwiki2/src/views/setup.cfg b/docs/tutorials/bfgwiki2/src/views/setup.cfg new file mode 100644 index 000000000..807ea6b0e --- /dev/null +++ b/docs/tutorials/bfgwiki2/src/views/setup.cfg @@ -0,0 +1,6 @@ +[nosetests] +match=^test +nocapture=1 +cover-package=tutorial +with-coverage=1 +cover-erase=1 diff --git a/docs/tutorials/bfgwiki2/src/views/setup.py b/docs/tutorials/bfgwiki2/src/views/setup.py new file mode 100644 index 000000000..86be6c960 --- /dev/null +++ b/docs/tutorials/bfgwiki2/src/views/setup.py @@ -0,0 +1,52 @@ +import os +import sys + +from ez_setup import use_setuptools +use_setuptools() + +from setuptools import setup, find_packages + +here = os.path.abspath(os.path.dirname(__file__)) +README = open(os.path.join(here, 'README.txt')).read() +CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() + +requires = [ + 'repoze.bfg', + 'SQLAlchemy', + 'transaction', + 'repoze.tm2', + 'zope.sqlalchemy', + 'docutils' + ] + +if sys.version_info[:3] < (2,5,0): + requires.append('pysqlite') + +setup(name='tutorial', + version='0.1', + description='tutorial', + long_description=README + '\n\n' + CHANGES, + classifiers=[ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "Programming Language :: Python", + "Topic :: Internet :: WWW/HTTP", + "Topic :: Internet :: WWW/HTTP :: Dynamic Content", + "Topic :: Internet :: WWW/HTTP :: WSGI", + "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", + ], + author='', + author_email='', + url='', + keywords='web wsgi bfg zope', + packages=find_packages(), + include_package_data=True, + zip_safe=False, + test_suite='tutorial', + install_requires = requires, + entry_points = """\ + [paste.app_factory] + app = tutorial.run:app + """ + ) + diff --git a/docs/tutorials/bfgwiki2/src/views/tutorial.ini b/docs/tutorials/bfgwiki2/src/views/tutorial.ini new file mode 100644 index 000000000..d89616316 --- /dev/null +++ b/docs/tutorials/bfgwiki2/src/views/tutorial.ini @@ -0,0 +1,20 @@ +[DEFAULT] +debug = true + +[app:sql] +use = egg:tutorial#app +reload_templates = true +debug_authorization = false +debug_notfound = false +db_string = sqlite:///%(here)s/tutorial.db + +[pipeline:main] +pipeline = + egg:Paste#evalerror + egg:repoze.tm2#tm + sql + +[server:main] +use = egg:Paste#http +host = 0.0.0.0 +port = 6543 diff --git a/docs/tutorials/bfgwiki2/src/views/tutorial/__init__.py b/docs/tutorials/bfgwiki2/src/views/tutorial/__init__.py new file mode 100644 index 000000000..cbdfd3ac6 --- /dev/null +++ b/docs/tutorials/bfgwiki2/src/views/tutorial/__init__.py @@ -0,0 +1,2 @@ +# A package + diff --git a/docs/tutorials/bfgwiki2/src/views/tutorial/configure.zcml b/docs/tutorials/bfgwiki2/src/views/tutorial/configure.zcml new file mode 100644 index 000000000..70c3d4d9a --- /dev/null +++ b/docs/tutorials/bfgwiki2/src/views/tutorial/configure.zcml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + diff --git a/docs/tutorials/bfgwiki2/src/views/tutorial/models.py b/docs/tutorials/bfgwiki2/src/views/tutorial/models.py new file mode 100644 index 000000000..3e63c3734 --- /dev/null +++ b/docs/tutorials/bfgwiki2/src/views/tutorial/models.py @@ -0,0 +1,43 @@ +import transaction + +from sqlalchemy import create_engine +from sqlalchemy import Column +from sqlalchemy import Integer +from sqlalchemy import Text + +from sqlalchemy.exc import IntegrityError + +from sqlalchemy.orm import scoped_session +from sqlalchemy.orm import sessionmaker + +from sqlalchemy.ext.declarative import declarative_base + +from zope.sqlalchemy import ZopeTransactionExtension + +DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) +Base = declarative_base() + +class Page(Base): + """ The SQLAlchemy declarative model class for a Page object. """ + __tablename__ = 'pages' + id = Column(Integer, primary_key=True) + name = Column(Text, unique=True) + data = Column(Text) + + def __init__(self, name, data): + self.name = name + self.data = data + +def initialize_sql(db, echo=False): + engine = create_engine(db, echo=echo) + DBSession.configure(bind=engine) + Base.metadata.bind = engine + Base.metadata.create_all(engine) + try: + session = DBSession() + page = Page('FrontPage', 'initial data') + session.add(page) + transaction.commit() + except IntegrityError: + # already created + pass diff --git a/docs/tutorials/bfgwiki2/src/views/tutorial/run.py b/docs/tutorials/bfgwiki2/src/views/tutorial/run.py new file mode 100644 index 000000000..f9789522c --- /dev/null +++ b/docs/tutorials/bfgwiki2/src/views/tutorial/run.py @@ -0,0 +1,27 @@ +from repoze.bfg.router import make_app + +import tutorial +from tutorial.models import DBSession +from tutorial.models import initialize_sql + +class Cleanup: + def __init__(self, cleaner): + self.cleaner = cleaner + def __del__(self): + self.cleaner() + +def handle_teardown(event): + environ = event.request.environ + environ['tutorial.sasession'] = Cleanup(DBSession.remove) + +def app(global_config, **kw): + """ This function returns a repoze.bfg.router.Router object. + + It is usually called by the PasteDeploy framework during ``paster serve``. + """ + db_string = kw.get('db_string') + if db_string is None: + raise ValueError("No 'db_string' value in application configuration.") + initialize_sql(db_string) + return make_app(None, tutorial, options=kw) + diff --git a/docs/tutorials/bfgwiki2/src/views/tutorial/templates/edit.pt b/docs/tutorials/bfgwiki2/src/views/tutorial/templates/edit.pt new file mode 100644 index 000000000..3d9e960c2 --- /dev/null +++ b/docs/tutorials/bfgwiki2/src/views/tutorial/templates/edit.pt @@ -0,0 +1,30 @@ + + + + + + bfg tutorial wiki (based on TurboGears 20-Minute Wiki) Editing: ${page.name} + + + + + +
+
Viewing + Page Name Goes Here
+ You can return to the FrontPage. +
+ +
+
+