Saturday, 1 September 2018

VuePress Examples

I Had great fun writing playing with vuepress and netlify putting together https://vuepress-examples.netlify.com/ however as usual I have to move onto other things and stop having fun.

Still a really useful way to put quick sites together especially for documentation and so on.

Tuesday, 3 September 2013

Who is Installing gbrainy?

While I was flicking through the metrics from installion.co.uk last night I was shocked by just how many hits the Debian and Ubuntu installation pages for gbrainy had had. It seems that from virtually out of nowhere a while back, an increasing number of people are trying to install it on a linux box and it made me wonder why.

The way I look at it there can only be two reasons:

  1. It's just really good and so is spreading virally.
  2. Everyone is being asked to install it by some educational or training body - maybe it's on some curriculum somewhere.

Having Goggled around and wasted more time than I really should have I came up with nothing except that Edubuntu comes with it installed (and surely schools are using that?)

Anyway, if you have any ideas then let me know. Meanwhile I'm just sitting here playingr gbrainy like the rest of them.

There's a neat article here

Thursday, 16 May 2013

Python _imaging cannot open shared object file

Okay so I'm using a 64 bit Linux and I was having a lot of trouble getting Calibre ebook tool to convert books into Kindle loving mobi format. I was getting a python error:

ImportError: libjpeg.so.62: cannot open shared object file: No such file or directory

Turns out all you need to do is

sudo apt-get install libjpeg62

You can test this by starting python and doing:

import _imaging

Friday, 1 March 2013

Installing Git and Virtualenv on Linux or Mac

For Debian/Ubuntu Linux:

sudo apt-get install git python-setuptools

For Redhat/Fedora Linux:

sudo yum install git python-setuptools

For Mac:

Install MacPorts and then:
sudo port install git python-setuptools

Continuing on for all of the above

sudo easy_install pip
sudo pip install virtualenv virtualenvwrapper

Now, you may want to set some defaults in your ~/.bashrc. My relevant entries look like this:



export WORKON_HOME=$HOME/Projects
export VIRTUALENVWRAPPER_HOOK_DIR=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_LOG_DIR=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

git config --global user.name "Terse Col"
git config --global user.email myemail@gmail.com
git config --global http.sslVerify false

Now away you go:

mkdir $HOME/.virtualenvs
source $HOME/.bashrc
mkvirtualenv mynewproject 
cdvirtualenv

Tuesday, 29 January 2013

Install Google App Engine on Ubuntu 12.10

Google App Engine  is currently on version 1.7.4 and Ubuntu has recently released Ubuntu 12.10 (Quantal Quetzal). Quantal Quetzal comes with Python 2.7 installed, and App Engine has been providing that version of Python as an option since February 2012. So if you are starting a new App Engine project, it's probably a good time to move to Python 2.7.

I'll explain briefly how you start a new project and there's a nice clean copy of the code at the bottom that you can cut and paste.

Let's get the show on the road. Choose a name for the project and create and switch to a virtual environment:

PROJ=gae_project
mkvirtualenv ${PROJ}
cdvirtualenv

Note that note that "--no-site-packages" and "--distribute" are now the defaults for mkvirtualenv. You don't even need to use "--python=python2.7" on Ubuntu 12.10.

Now we need to know what the latest version of App Engine is, but as of writing it's 1.7.4:

GAE=1.7.4
wget -O /tmp/gae.zip http://googleappengine.googlecode.com/files/google_appengine_${GAE}.zip
unzip /tmp/gae.zip

Now let's create an App Engine app. The app will need a name that has been created in the App Engine Console:

GAE_APP_NAME=dummy
mkdir -p gae_app/static

Now create the app.yaml file:

echo """application: ${GAE_APP_NAME}
version: development
runtime: python27
api_version: 1
threadsafe: true

default_expiration: 7d

handlers:
- url: /static
  static_dir: static
- url: .*
  script: wsgi_app.app
""" > gae_app/app.yaml

And finally the app itself:

echo """import webapp2

class MainPage(webapp2.RequestHandler):
  def get(self):
      self.response.headers['Content-Type'] = 'text/plain'
      self.response.out.write('Please replace me with a decent WSGI App Framework such as Flask')

app = webapp2.WSGIApplication([('/', MainPage)],
                              debug=True)
""" > gae_app/wsgi_app.py


And finally to run the development server:

python ./google_appengine/dev_appserver.py gae_app/

I hope that this has all been of some help to you. Did I miss anything? Please comment below.

Sunday, 13 January 2013

A Review of the Nagare Microframework

The analytics tell me that the keywords for this blog are "Best Python Framework" which is odd because I don't think I can pretend to have that answer. What I can do is point out what the differences are and let you find the one that suits you best. Nagare for example offers some concepts that you won't be used to if you come from using Django or Flask and the like.

If you have read Install Stackless Python on Ubuntu and could get stackless running the examples I showed you, then just follow these commands to get a stackless virtual environment running a nagare project called 'nagaredemo':

In the examples below, paste the code directly into the file
//negaredemo/demos/demos/app.py
and be aware that when you change the code you need to  restart the development server (Ctrl-C stops it.)

Hello World!



Okay, so example1 shows the basics of rendering a Welcome object.
http://localhost:8080/demos/
You'll notice immediately that we're not using a templating language here, but rather the built in Domain Specific Language (DSL). In reality you would use the DSL to build xhtml snippets and then use meld to insert them into templates. I've not used meld before, but it looks very straight forward - neat in fact. Now onto example2.

Callbacks



Here we've registered two callbacks on the DOM without having to explicitly declare the URL mappings. have a look at the rendered HTML to see how this has been implemented. Now, that's pretty handy.

Tiresome RESTful URLs



Example 3 takes that same code and augments it to allow us to have more ReSTful URLs. I'm not sure this is as obvious as I'd like, but it works I suppose.
http://localhost:8080/demos/Counter?value=7

Saving State Automatically


Nagare can hide the request/response object and global session from the developer. Object states are automatically saved in a server side session during the request/response round-trip. This allows for a more direct style of programming like in a desktop application.

And there's more


There's more documentation on the Nagere website itself, so scoot along there and see what else there is to offer. Nagare is built upon ConfigObj, WebOb, Paste, PEAK-Rules and lxml, so it's on good foundations. I'm told by HervĂ© Coatanhay that the next release will introduce non stackless support using pypy or CPython.

Conclusion


Nagare is able to implement Continuations and that's a great thing. However I'm not sure I like the way it obfuscates the implementation. I'd much rather be able to see what was going on.

For example, saving state between requests is nice, but is it secure? Do I need to plough through the code to find out? In my opinion it would have been better to have offered a structure that allows for others to plug in solutions/implementations.

The documentation is somewhat limited, which is probably because the community is still fairly small. However sinceteh project has been running since 2008, perhaps that's something to be concerned about.

Thanks to HervĂ© Coatanhay for suggestion the illustrative code snippets.


Monday, 7 January 2013

An Alternate Explanation of Continuations


What's a continuation?

If you read the Wikipedia item on continuations, make sure you understand the "continuation sandwich" paragraph which is supposed to be the definitive example of what a continuation is. I like to think of it the other way around - with my patent "what a continuation is not" example.

What a continuation is not?

Imagine you have a bookies slip with a four horse accumulator bet (parlay) on it. Your first three horses win and you are in a situation (the state of the bet) where you have a small fortune going onto the last horse. The horse falls.

Now, if the bookies slip had been a continuation it would have maintained the state after the third race and you could have retrieved that state and tried another horse on the last race. But it isn't and you can't, so tough.

Continuations are an important concept in the Nagare Microframework which I'll be looking at next. Continuations allow Nagare to maintain state in an exciting way which may seem unusual to you if you have used some of the other python frameworks like Flask or Bottle or Django.

Good luck fellow travellers.

Stackless Code - The Short Version

So my last couple of posts have been on installing Stackless Python and what exactly the Stackless bit of Stackless Python means. Now it's time for the short version of the example code and an alternate explanation of continuations. Prepare to be underawed.

With Stackless ou get tasklets and channels. Channels let you communicate between tasklets.

Running this you get:

Now the third and final thing that Stackless offers is cooperative multitasking. To see how this works, just uncomment the line with stackless.schedule() in it and rune it again.

That's about it really, but as you know it's not what you got it's how you use it. There's a much more detailed explanation of what we just did here and the point is that this allows you to use continuations.

See my next post An Alternate Explanation of Continuations

Good luck fellow travellers.

Saturday, 5 January 2013

Python Rocks - So what is Stackless Python?

Python may be one of the most widely learned and used languages today, but it was conceived in the late 1980's when if you hadn't got a mainframe, you almost certainly were running your code on a single CPU computer of some sort.

For this reason the original implementation of Python was written with the understanding that it was perfectly sensible to use the same single execution stack that C used - after all Python was written in C. Despite being on version 2.7/3.3 nowadays, the standard Python is still written in C, still uses a single execution stack design and is often known as CPython.

English: CPU Zilog Z8
English: CPU Zilog Z8 (Photo credit: Wikipedia)
The execution stack - or call stack - or just stack is like a big spike that you stick messages on in a last on, first off way and it's where the low level machine code subroutines used to stick the current code  address before going away to do some jiggery pokery. When the subroutine was finished it returned by pulling the last address off the stack and then execution continued from there. It was all fairly simple in the days of the Z80 and as I understand it, that's still essentially how a single CPU - or Core - works.

AMD Athlon™ X2 Dual-Core Processor 6400+ in AM...
AMD Athlon™ X2 Dual-Core Processor 6400+ in AM2 package (Photo credit: Wikipedia)
The problem is that sometime in the early 2000s, dual-core, and then multi-core chips started to be become increasingly affordable and therefore available. Most of you will be using a multi-core system to read this post. This means that your systems are capable of running more than one process a time - what is called concurrency.

This is a bit of a pain for CPython because it only knows how to use a single stack, i.e. a single core, and that is just a bit of a waste of those other cores which are just itching to make it all run super fast.

So Stackless Python is essentially a redesign of CPython which avoids using the call stack and instead uses something called microthreads to get around the problem. This means four things to you:

  • Concurrent programming is possible.
  • Concurrency can improve on execution time if done properly.
  • You need to learn some new concepts: tasklets and channels.
  • You get to use some new stuff: tasklets and channels.
I'll introduce those next time.

There's a very informative interview with the creator of Stackless Python here.

You may like to be ready by reading my post about installing Stackless Python.

Good luck fellow travellers.

Wednesday, 2 January 2013

Install Stackless Python on Ubuntu

I'm just about to write a couple of posts on Stackless Python and the Nagare Micro Framework which runs on it. So I've been installing Stackless on my Ubuntu 12.04. Here are some nice copy and paste instructions if you want to play along.

First install the required libraries and get stackless itself:


Now install stackless :


After the "make" you'll see some failures as below. Just ignore them.


Now it's time to link your standard (CPython) packages so that they can be used with stackless:

...and edit the paths in the site.py file. At about line 300, edit the file to look like this. It's the second sitepackages.append bit we're adding here:

That should be it! Let's test it:


Wednesday, 5 December 2012

Aggregating Everything - Map/Reduce and Camel?

If you are used to Map/Reduce you will be used to the idea of breaking tasks down into little chunks and then collecting the partial results together into some final format.

So, recently when I was parsing zillions of rows of data and aggregating related data into partial CSV files  and then aggregating the bits of partial of data to reports I thought - Aha! MapReduce.

For a whole bunch of good design decisions I was using Apache Camel - a neat pipelining tool which with a bit of help from ActiveMQ provides the sort of long running stability that I needed. Camel however does not do Map/Reduce, but it does have the Aggregator Integration pattern, which you can use to so a similar thing.

Image courtesy of Carlos Oliveira
Imagine you empty your jar of loose change on a table. You stack the nickles in stacks of ten coins, the dimes is stacks of ten coins and the quarters in stacks of ten coins. You add up all the 50 cents, $1s and $2.50s and you know how much you have. That's Map/Reduce.

Now, imagine you empty your jar of loose change into one of those coin counting machines in the Mall. Internally all the coins are sorted by falling through a hole which is either nickle, dime or quarter shaped and as they emerge from the other side they are counted*. That's aggregation Camel style.

I did hit a bit of a snag. I couldn't work out how to tell the Aggregator Integration pattern that there were no more files to come... Stop... Woaa-there... Desist!

It turns out that hidden away (in the middle of the docs) the File endpoint rather usefully sets a flag in the headers called CamelBatchComplete which is just what I was looking for:

Good luck fellow travelers.

* I have no idea how a coin counting machine works.

Friday, 23 November 2012

Simple Camel Configuration of a Twitter Endpoint

I was asked just now how my got the Twitter Stream working in my new Camel based project and how I managed the credentials.

The Twitter endpoint works like a dream and this is essentially what my code looks like. All you need is a secrets.properties file in alongside your java file.

Saturday, 17 November 2012

Apache Camel - Connection Beans Without Spring

While writing some tests for an Apache Camel project, I just spent rather longer than I'd have liked trying to work out how to configure a connection bean for Mongo without using Spring.

Since I hide my embarrassments in public I thought I'd best share with anyone else with brain freeze.


Don't forget you need the camel-mongodb artifact in your pom.xml file. Good luck fellow travellers.

Monday, 5 November 2012

Python Web Microframeworks - Take Your Pick

You may read my post "Top Python Web Frameworks - Today" in which I took a fresh look at what which Python Web Frameworks were still around and still maintained.

In this post I give a quick overview of about half of those which I have loosely designated as "Microframeworks" - regardless of what the authors have called them. Wikipedia doesn't have a definition for microframework - I just looked - so what I really mean here is anything which let's you get started without having to learn a whole bunch of syntax and convention. Right on sister!

Let's get going:

Now that's done a little code from each -

Bottle (v0.11.13)



Bottle doesn't rely on any other packages at all, which means it's a great framework to use if you want to see all the working parts as they're all in the one file. That being said it can offer client-side sessions and compression and even WebSockets straight out of the box so it's not just a toy by any means.

Flask (v0.9)


Flask is dependent on Werkzeug for all the WSGI stuff and upon Jinja2 as a template library. It comes with client-side sessions, a built in debugger and is totally unicode friendly. I love Flask and use it often as my other posts will testify.

kiss.py (v0.4.9)


The first of the new boys, kiss.py is certainly not package independent! It requires Werkzeug for WSGI, requests for http, Beaker for sessions, Elixir and SQLAlchemy for an ORM (PostgreSQL, MySQL and SQLite), Jinja2 for templates, gevent, pev and greenlet for events as well as compressinja, jsmin, jsonpickle, putils and pyScss which add various other niceties. Almost all well known and trusted libraries.

web.py (v0.37)


Again, web.py doesn't rely on any other packages at all, but to me it's not as useful as flask or kiss.py and not as simple to study as bottle, so I can't see the point, although according to the site, it's well used by others.

wheezy.web (v0.1.307)


pip installs wheezy.web, wheezy.core, wheezy.caching, wheezy.html, wheezy.http, wheezy.routing, wheezy.security, wheezy.validation which to me looks like the developers have taken a sensible approach to the development cycle by splitting everything up into independent code units.

According to the site,  functionality includes routing, model update/validation, authentication/authorization,content caching with dependency, xsrf/resubmission protection, AJAX+JSON, i18n (gettext), middlewares, and more.

In Summary

No I haven't tested them to death and no I haven't even tried out kiss.py and wheezy.web in a real world app, although I will do. I certainly have not done either load or concurrency testing on them. You can do that and I'll read your blog.

Goo luck fellow traveller.

Friday, 2 November 2012

CoffeeScript Love: Backbone.js Tutorials in CoffeeScript

Ahhhh enjoy the aroma, inhale the caffeine. If you're looking for a nice list of Backbone tutorials that use CoffeeScript then look no more - CoffeeScript Love: Backbone.js Tutorials in CoffeeScript.

Thursday, 1 November 2012

Top Python Web Frameworks - Today

Every once in a while it's nice to rediscover old friends. Over the last few years I've had a play with quite a few Python Web Frameworks, but one does tend to get a favourite and stick with it. Same as other areas I suppose - cars, dogs, beers, partners... Still, it's good to have a look at what's new and fresh once in a while (my wife doesn't care, but don't tell my dog.)

example of Python language
example of Python language (Photo credit: Wikipedia)
If you look around the internet, there are probably thirty or so Python Web Frameworks around, but not all of them are actively supported. This means that they are likely to be missing functionality in some of the latest latest areas of interest - OAuth2, HTML5 or mobile support for example. Or maybe they just don't make it easy to stuff that you have become used to over the last few years - AJAX or web services maybe.

In my previous post "My Top Ten Python Web Frameworks" from about 18months ago, I gave you my opinion of what was hot, or not, at that time. Some of those seem to have stalled now - Tipfy, GAE framework, Weblayer; while others have appeared or matured - kiss.py, web.py, wheezy.web.

Below is an alphabetic list of the active (updated this year) which I know about. There may be others out there, so please let me know in the comments at the bottom.
In my next few posts I'll be giving you a run down of what state each of them is in and try to give you some idea of how they fit your requirements.

Good luck fellow traveller.


Tuesday, 17 July 2012

A First Look at Flask-Evolution

While poking around in Flask-Ahoy this morning I came across Flask-Evolution which I hadn't previous noticed. It offers the Django idea of migrations to the Flask community and so I thought I'd give it a go and see how it shapes up.


So let's set up a virtual environment and get the basics in place.
Now the contents of the two files you touched. First the "hello world" Flask app goes in the myapp.py file:


Next we we take the tutorial Flask-Script manage.py file and adapt it very slightly:

Now we are ready to create a simple migration for a Post model for a blog:



and you get the template file which looks like this:



In the file put your Post model and modfy "up" and "down":


Our First Migration


Our Second Migration
Now if we want to modify that Post model we can again do:


modify your model and modfy "up" and "down", I've left some comments so you can see what I did:


and run it again.


You should also play around with the "redo" and "undo" commands. That's about it really.

Conclusion
This is only version 0.6 of Flask-Evolution and it's got a way to go, but I can see some use in using it, but it's far from seamless and it's a long way from South.

Documentation is woeful and I'm not convinced the developer Adam Patterson has the time to do the job he'd like to.

You could always offer to give him a hand!

If you see anything wrong with what I've written here or if you spot spelling or other mistakes then please let me know.

Good luck fellow traveller.

Sunday, 8 July 2012

Hosting Domains on Your Domestic Broadband Connection

It's not ideal, but it is possible to host your own domain(s) on your home broadband connection. Find out how.

Hosting on a Budget?
I showed you in my previous last Nginx & uWSGI Living Together in Your Shed how to set up your own Nginx server to serve WSGI applications like Flask, Django, Bottle, Pyramid etc. This allows you to host your own applications on the cheap. All you need is any old server right?

Well sort of. I mean it's cheap enough to buy your own domain name and you probably will want to, but when you are filling in the registration what do you enter when it asks for your DNS servers?

Static IPs can be bought or leased from IP providers and this makes it possible to host your own DNS services. However most of us have dynamic IP addresses at home because our IP providers keep their costs down by buying big blocks of addresses and dynamically allocating us one from the deck each time we need one, and sometimes for their own maintenance reasons too. 

This means your IP address will change from time to time. 

To get around this you can use a dynamic DNS service such as freedns.afraid.org who will point your domain name at your new IP address every time it changes. Cool. Their service is simple, clear and cheap (or even free). I'll let you investigate that yourself, but the main thing is that when you buy your domain name, you need to fill in the DNS bit using the dynamic DNS server names that they provide.

The final thing is: How do you know when your dynamic IP address changes and how do you inform your dynamic DNS service when it happens? Well, for my own purposes I wrote a little script which will do this for you, it checks if your IP has changed and if it has it calls the special callback URL that freedns and others supply you with. 

You can find it here: https://github.com/colwilson/dynamic-dns-updater

Good luck fellow traveller.

Wednesday, 4 July 2012

Nginx & uWSGI Living Together in Your Shed

Let's assume you have just bought the memorable domain name idrinkink.org and you want to host your lovely web app on that old server in the shed. 

I recently set up both Flask-Ahoy! and Django-Ahoy! on a five year old desktop my daughter was chucking out, so I can guarantee you that this configuration can handle enough traffic to get you going, or to demo products to your customers.

Before we start, I'm assuming you are familiar with python web frameworks (Django, Flask, Bottle etc) and with using virtualenv to segregate your environments. I usually use Flask as my framework of choice, so I'm using their "Hello World" app here.

Let's get started:

Now the contents of those files:

Finally copy the config into place and start the uwsgi daemon and the server up:


This of course is just the basics, but it will hopefully give you a starting point from which you can fiddle to your hearts content.

Good luck fellow traveller.