22 Jul 2014

feedPlanet TurboGears

Christpher Arndt: EuroPython training checklist

Here's a checklist for participants of my training session Interactive experiments in sound synthesis with Nsound, numpy and matplotlib at EuroPython 2014 in Berlin. Have/bring a laptop with Linux (preferred), Windows, or OS X and good headphones. An external audio interface may help with audio performance but is not essential. Download and install my virtual […]

22 Jul 2014 2:01pm GMT

Christpher Arndt: Setting up a virtualenv for IPython and Nsound

These instructions detail how to create a working environment for participants of my training session Interactive experiments in sound synthesis with Nsound, numpy and matplotlib at EuroPython 2014 in Berlin who do not want to or cannot use the virtual machine appliance I created for the course. These instructions are geared to Linux users, though […]

22 Jul 2014 2:00pm GMT

19 Jul 2014

feedPlanet TurboGears

Christpher Arndt: Virtual machine for my EuroPython 2014 sound experimentation training

I have created a virtual machine for virtualbox for the participants of my training session Interactive experiments in sound synthesis with Nsound, numpy and matplotlib at EuroPython 2014 in Berlin. It provides a ready to run Manjaro Linux System with an XFCE desktop and all the software necessary to follow the course. Update (2014-07-22): if you […]

19 Jul 2014 5:49pm GMT

20 Apr 2014

feedPlanet TurboGears

Curia: Announcing the pyramid_assetmutator package

If you're like me, one of the first things you do when starting a new web application project is set up a CSS alternative such as LESS or SASS/SCSS. Those who aren't particularly fond of JavaScript might also tend to add CoffeeScript. These "metalanguages" can assist in making client-side/asset code more pleasurable to work with, as they typically provide functionality that's "missing" in the the languages they get interpreted into.

Some frameworks (e.g. Ruby on Rails) give you support for these alternatives out-of-the-box, but in the land of less opinionated software things can require a bit more work. Since I am personally a fan of the Pyramid web framework, I've used the pyramid_webassets and pyramid_fanstatic packages in the past to provide this support. However, these packages are so powerful and comprehensive that they can also tend to be somewhat involved in regards to configuration, so I recently decided to roll my own Pyramid add-on: pyramid_assetmutator

Although definitely not as "feature-full" as the packages I have mentioned earlier, as of this writing it provides the following:

Feel free to check it out on GitHub or browse the documentation, and share here or open a GitHub issue if you have any comments or suggestions.

20 Apr 2014 1:07am GMT

03 Apr 2014

feedPlanet TurboGears

Christpher Arndt: Select a Python code block in Geany with Lua

Here's a nifty little Lua script for the Geanylua plug-in for the Geany text editor to select a Python code block in Geany with Lua. When the script is activated, it will select the block corresponding to the current code folding level of the line the cursor is on in the active document. E.g. if you place the cursor in the body of a Python function on a line that is on the same indentation level as the first line of the body of the function, it will select the whole function. Also, if the cursor is on the opening line of a block, e.g. a line starting with class, def, if, etc., the script will select the block started by this line.

03 Apr 2014 11:09pm GMT

10 Mar 2014

feedPlanet TurboGears

Matthew Wilson: RIP hen #1

For two years now, I've been letting my hens free range around in a fenced-in section in my back yard during the day. They love it.

Went out to check for eggs today after work and found one of my girls had been killed in the coop.

Head bitten off. No other signs of predation. Internet forums say this was likely a possum or a raccoon.

Going to set up a live trap tonight. And some wire snares.

I raised these girls since they were a day old. Can't really remember the last time I was this angry and sad.

10 Mar 2014 11:01pm GMT

18 Feb 2014

feedPlanet TurboGears

Christpher Arndt: Benjamins Schlaflied

Welcome, my Nephew Here is a little song I wrote for my nephew, who was born two weeks ago, to welcome him into this world and hopefully give him some comfort while he rests from the tiring all-day business of processing his mother's milk. It is thus called Benjamins Schlaflied (Benjamin's Lullaby) and I play […]

18 Feb 2014 7:30pm GMT

11 Feb 2014

feedPlanet TurboGears

Christpher Arndt: Get the gist of it

Some months ago I finally caught up with modern development practices and switched to Git for new software projects. Though I host my own projects on my own server with the help of Trac and gitosis, one thing I do like about GitHub though, are Gists. Like many good ideas this one makes one wonder, why nobody came up with it before. It is also very easy to include Gists in your blog, which is what I'm starting with this post. Recently, on the German mailing list of the pyCologne User Group, someone was pointing out Python's poor performance at an implementation of the fibonacci series using recursion and showed some Scala code that profited from a few added type declarations. I showed that a similar performance gain could be achieved using Cython, with very few changes to the original pure Python code. I created a small shell function to automate the process of compiling a Cython source file with the --embed option and turning it it into a binary. The function then runs the resulting binary, so you can use this function to run a *.pyx file directly. Read full article...

11 Feb 2014 7:43pm GMT

02 Jan 2014

feedPlanet TurboGears

Matthew Wilson: What’s good and bad about github issues

Ticketing / workflow / bugtracker systems are always nasty. Github's is pretty good. Maybe the best of what's out there. But it ain't perfect.

Here's what I like:

And what I dislike:

02 Jan 2014 4:09pm GMT

08 Dec 2013

feedPlanet TurboGears

Matthew Wilson: I really like my gardening boots

You don't need many tools to start gardening. You can dig holes with a stick or a sharp rock. You can start seeds in tin cans. You can use all sorts of stuff to carry water. You really only need dirt, sun, and seeds. So don't run out and buy a bunch of stuff!

But when you realize you've got the gardening bug bad, there's a few tools that really help. First off, you need some rubber boots. Otherwise, you're going to track mud everywhere. That's going to make your significant other very annoyed!

I bought these boots in 2006. They've held up very well over the last seven years. They're waterproof, thick enough to block thorns, easy to hose off, and the sole is thick enough that I can push on a shovel with them.

They're made here in Illinois, USA, by Boss Manufacturing Company. They've been around since 1893!

You can order them on Amazon. You can't order them direct from the company.

Note: I will get some commission if you order the boots from the link below, so if you hate me, you should not click on that link.

08 Dec 2013 4:50pm GMT

16 Nov 2013

feedPlanet TurboGears

Matthew Wilson: Upload files directly to Rackspace from the browser with AJAX PUT

I just wrote this up on my biz site.

Upload files directly to Rackspace Cloudfiles from the browser with AJAX PUT

I hope it helps somebody out!

16 Nov 2013 9:43pm GMT

10 Nov 2013

feedPlanet TurboGears

Alessandro Molina: TurboGears 2.3 Hidden Gems #2 - Application Wrappers

One of the less known features introduced in TurboGears 2.3 are application wrappers.
Application wrappers are much like controller wrappers (available since 2.2), but instead of wrapping controllers they actually wrap the whole application providing an easier way to implement what in plain WSGI is done through middlewares.

The advantage of application wrappers over middlewares is that they have full access to TurboGears stack, they can access the current request, the database, session and caches as the application itself would do.

The great part is that, as they run between TGApp and TGController, they can also replace the TurboGears Context and the TurboGears Response providing a great way to hijack requests, responses or even replace entire features of the framework like the cache layer. A very similar concept is available in other frameworks like Pyramid Tweens.

A very simple application wrapper that intercepts exceptions and logs them without messing with the standard TurboGears error handling might look like:

class ErrorLoggingWrapper(object):
    def __init__(self, handler, config):
        self.handler = handler
        self.config = config
 
    def __call__(self, controller, environ, context):
        path = context.request.path
        try:
            return self.handler(controller, environ, context)
        except:
            log.exception('Error while handling %s', path)
            raise

The wrapper can then be enabled calling

base_config.register_wrapper(ErrorLoggingWrapper)

inside config/app_cfg.py

Now that we have an application wrapper able to log exceptions we can decide for example to add another one that suppresses exceptions and prints "Something went wrong!", as it is possible to specify the order of execution for application wrappers we can register a SuppressErrorsWrapper that should execute after the ErrorLoggingWrapper:

from webob import Response
 
class SuppressErrorsWrapper(object):
    def __init__(self, handler, config):
        self.handler = handler
        self.config = config
 
    def __call__(self, controller, environ, context):
        try:
            return self.handler(controller, environ, context)
        except:
            return Response('Oh! Oh! Something went wrong!', status=500, content_type='text/plain')

Then it can be registered after the ErrorLoggingWrapper using:

base_config.register_wrapper(SuppressErrorsWrapper, after=ErrorLoggingWrapper)

While applications wrappers are a powerful feature, most of their power comes from the new response management refactoring that makes possible to access the current context and replace the outgoing response while working with high level objects instead of having to manually cope with WSGI.

10 Nov 2013 1:16pm GMT

02 Nov 2013

feedPlanet TurboGears

Alessandro Molina: TurboGears 2.3 Hidden Gems #1 - New Response Management

TurboGears2.3 has been a major improvement for the framework, most of its code got rewritten to achieve less dependencies, cleaner codebase a cleaner API and a faster framework. This resulted in reduction to only 7 dependencies in minimal mode and a 3x faster codebase.

While those are the core changes for the release, there are a lot of side effects that users can exploit at their benefit. This is the reason why I decided to start this set of posts to describe some of those hidden gems and explain users how to achieve the best from the new release.

The first change I'm going to talk about is how the response management got refactored and simplified. While this has some direct benefits it also provided some interesting side effects it makes sense to explore.

How TurboGears on Pylons did it

TurboGears tried to abstract a lot of response complexity through tg.response object and as there were not many reasons to override TGController.__call__ it was common that the response object body was always set by TurboGears itself.

Due to the fact that Pylons controllers were somehow compliant to WSGI itself the TGController was then in charge of calling the start_response function by actually providing all the headers user set into tg.response

response = self._dispatch_call()
 
# Here the response body got set, removed for brevity
 
if hasattr(response, 'wsgi_response'):
  # Copy the response object into the testing vars if we're testing
  if 'paste.testing_variables' in environ:
      environ['paste.testing_variables']['response'] = response
  if log_debug:
      log.debug("Calling Response object to return WSGI data")
 
  return response(environ, self.start_response)

While this made sense for Pylons, where you are expected to subclass the controller to perform advanced customizations, it was actually something unexposed to TurboGears users.

TurboGears made possible to change application behaviour using hooks and controller_wrappers. So the use for subclassing the TGController was actually strictly related to custom dispatching methods, which was usually better solved by specializing the TGController._dispatch method (tgext.routes is a simple enough example of this).

Cleaning Up Things

This lead to a curious situation where the TGController needed to speak with TGApp through WSGI to make Pylons happy, so it needed to call start_response and return the response iterator itself. TGApp was supposed to be the WSGI application, but in fact most of the real work was happening into TGController, in the end we had two WSGI applications: both TGController and TGApp were callable that spoke WSGI.

The 2.3 rewrite has been a great occasion to solve this ambiguity by providing a clear communication channel between TGController and TGApp by assigning each one a specific responsibility.

Communication Channel

In TG2.3 only the TGApp is now in charge of exposing the WSGI application interface. The TGController is expected to get a TurboGears Request Context object and provide back a TurboGears Response object. The TGApp will then use the provided response object to submit headers and response body.

The TGController code got much more straightforward and the whole testing and call response part was moved to the TGApp itself:

try:
    response = self._perform_call(context)
except HTTPException as httpe:
    response = httpe
 
# Here the response body got set, removed for brevity
 
return response

This has been possible without breaking backward compatibility thanks to the fact that the only subclassing of TGController common in TurboGears world was the BaseController class implemented by most applications.

The BaseController usually acts just as a pass-through between TGApp and TGController to setup some shortcuts to authentication data and other helpers for each request. So the fact that the parameters received by BaseController.__call__ changed didn't cause an huge issue as they were just forwarded to TGController.__call__

A little side effect

One of the interesting effects of this change is that your controllers are now enabled to return any instance of webob.Response.

In previous versions it was possible to return practically only webob. WSGIHTTPException subclasses (as they exposed a wsgi_response property which was consumed by Pylons), so it was possible to return an HTTPFound instance to force a redirect, but it was not possible to return a plain response.

A consequence of the new change is enabling your controller to call third party WSGI applications by using tg.request.get_reponse with a given application. The returned response can be directly provided as the return value of your controller.

This behaviour also makes easier to write reusable components that don't need to rely on tg.response and change it. Your application can forward the request to them and proxy back the response they return.

Part #2 will cover Application Wrappers, which greatly benefit from the new response management.

02 Nov 2013 10:51pm GMT

17 Sep 2013

feedPlanet TurboGears

Craig Small: jqGrid in TurboGears2 Admin Screens

I wanted to use the jqGrid for my admin pages as I liked that look and it matches some of the other screens outside the admin controller. The admin controller, or rather the CrudRestController out of tgext.crud, has a way of exporting results in json format. So surely its a matter of changing the TableBase to use jqGrid in the admin controller and we're done?

Well, no.

First you need to adjust the jsonReader options so that it lines up to the field names that the controller sends and this was one of the first (or last snags). The json output looks like:

{
  "value_list": {
    "total": 20,
    "items_per_page": 7,
    "page": 1,
    "entries": [(lots of entries)...]
  }
}

Now this is a little odd because of the top-level dictionary that is being used here. Most of the examples have everything that is inside the value_list being returned. In fact adjusting the controller to return only those items in the value_list values works.

To look inside this structure we need to adjust the jsonReader options. jqGrid documentation uses the format "toptier>subtier" for the XML reader so that was the intial attempt. It was also an intial fail, it doesn't work and you get your very familiar empty grid.

The trick is close to this format, but slightly different for json. You change the options to "toptier.subtier". In other words change the greater than symbol to a full stop for json access.

The jqGridWidget now has the following options (amongst others):

options = {
  'datatype': 'json',
  'jsonReader': {
    'repeatitems': False,
    'root': 'value_list.entries',
    'total': 'value_list.total',
    'page': 'value_list.page',
  }
}

There might be a way of saying all entries sit under value_list inside jqGrid, but I couldn't find it. Those options given above do give a working jqGrid on the admin screens.

17 Sep 2013 12:29pm GMT

23 Jul 2013

feedPlanet TurboGears

Matthew Wilson: old-school code checklist

You can't call it old-school code unless a majority of these are true:

23 Jul 2013 5:06pm GMT

18 Jul 2013

feedPlanet TurboGears

Craig Small: Step or Sloping Graphs

Even though the backend of Rosenberg NMS uses rrdtool RRD files, the front end graphs are created using jqPlot. The idea is to have a set of templates for the different types of graphs and just apply them to the various data sets. It makes things a lot simpler for new graphs because you just select which one you want; unless you want something a lot different which would involve a new graph template.

In any case, anyone that looks enough at the standard rrdtool graphs will know they are a series of steps. While it depends on the RRA, usually they are 5 minute steps, so a graph showing an increasing rate might show 5 minutes of 2 Mbps and then the next 5 minutes of 11 Mbps. jqPlot graphs as I've currently got them draws a line between two data points, so there would be a sloping line starting at 2.5 minutes (half of the first 5 minute interval) and 2Mbps sloping up to 11 Mbps at 7.5 minutes.

At first I thought this was wrong and spent some time attempting to "fix" the graph by making it look like a rrdtool graph more. Someway through that process I stopped and wondered, what IS the right way? The answer like a lot of other things, is "it depends".

For a graph showing a rate, such as the output bits per second on an interface, the way this is done is at regular intervals a counter is measured. So if at time 0 the counter is 140 and time 60 the counter is 200 and finally at time 120 the counter is at 800 there has been an average rate of 1 [(200-140)/60] and 100 [(800-200)/60)]. rrdtool would show a horizontal bar at 1 bps and then another horizontal bar at 100 at the next time interval. jqPlot would show a sloping line going from 30,1 up to 90,100.

Two graphs looking very different from the same data, what gives? Each graph is right, or rather is showing an estimation of different things, hence their differences.

rrdtool is showing the average rate for that time period. It is in some ways accurate because leaving aside missed wrap-arounds and resets that many bits did pass through that interface for the time specified. However often the graphs are interpreted incorrectly as the real rate and not an average. We can be reasonably sure for a rate that it would not be 1 for exactly a minute and then immediately jump to 100 for another minute. This isn't rrdtool's fault, it is just how the graphs can be interpreted.

jqplot will show more "realistic" graphs, with a curve sloping up. However this too makes assumptions that the rate increase is linear which often it is not. It just gives the illusion that the graph knows more about the data than it really does.

In the end, both graphs are at the same time accurate and misleading. It's important when looking at any graph in general (not just these two types) that you understand its limits and assumptions. To give one example of the problems that can be missed, traffic interfaces may have microbursts (large amount of traffic in short amount of time) which, due to the averaging that goes on in graphing are invisible to graphs and give an incorrect account of what is going on.

18 Jul 2013 1:05pm GMT