www.BigDataTechCon.com
April 26-28, 2015
Seaport World Trade Center HotelBig Data TechCon is the HOW-TO technical conference
for professionals implementing Big Data solutions
at their company
Choose from 55+ classes and tutorials!
Come to Big Data TechCon to learn the best ways to:
• Process and analyze the real-time data pouring into your organization
• Learn how to extract better data analytics and predictive analysis to produce the kind of actionable information and reports your organization needs.
• Come up to speed on the latest Big Data technologies like Yarn, Hadoop, Apache Spark and Cascading
• Understand HOW to leverage Big Data to help your organization today
Big Data Gets Real in Boston!
People are talking about
BigData TechCon!
“Big Data TechCon is a great learning experience and very intensive.”
—Huaxia Rui, Assistant Professor, University of Rochester
“Get some sleep beforehand, and divide and conquer the packed schedule with colleagues.”
—Paul Reed, Technology Strategy & Innovation, FIS
“Worthwhile, technical, and a breath of fresh air.”
—Julian Gottesman, CIO, DRA Imaging
Dear Readers!
Our Best of SDJ issue is finally released and it is free to download! We worked hard and we hope that you see that. This issue is dedicated to Web Development mostly. We tried to compare as many frameworks as we can. Our jQuery section starts with Jquery is awesome. So, use it less! by Willian Carvahlo. Author is convinced that jQuery is a great tool but it’s sometimes used in a wrong way. This article is a voice in a discussion about proper use of jQuery.
Then you’ll find jQuery promises by Ryan O’Neill. This article is related to the previous one. Author shows in a simple way how you can manage all that you want with jQuery without complications.
Davide Marzioni shows a simple trick with web2py and Tomomichi Onishi presents Tutorial for creating simple Hyakunin-Issyu application using Sinatra and Heroku. Manfred Jehle in theoretical way explains how you can Start developing better applications.
Aimar Rodriguez covers Django subject in the article entitled Developing your own GIS application with GeoDjango and Leaflet.js.
Also look closely to the other articles. You need to read the article on AexolGL and I think you will find the new 3D graphics engine full of new tools. This issue contains really interesting content and we are happy to publish that for you!
We’re hoping you’ll enjoy our work. Ewa & the SDJ Team
Editorial Advisory Board: David Gillies, Shawn Davis
Special thanks to our Beta testers and Proofreaders who helped us with this issue. Our magazine would not exist without your assistance and expertise.
Publisher: Paweł Marciniak Managing Director: Ewa Dudzic DTP: Ireneusz Pogroszewski Marketing Director: Ewa Dudzic Publisher: Hakin9 Media SK
02-676 Warsaw, Poland Postepu 17D
http://www.sdjournal.org
Whilst every effort has been made to ensure the highest qual-ity of the magazine, the editors make no warranty, expressed or implied, concerning the results of the content’s usage. All trademarks presented in the magazine were used for informa-tive purposes only.
All rights to trademarks presented in the magazine are reserved by the companies which own them.
DISCLAIMER!
The techniques described in our magazine may be used in private, local networks only. The editors hold no respon-sibility for the misuse of the techniques presented or any data loss.
Copyright © 2015 Hakin9 Media Sp. z o.o. SK
Table of Contents
AexolGL – New 3D Graphics Engine ...6
Jquery is Awesome. So, Use it Less! ...9
by Willian Carvalho
Jquery Promises ...11
by Ryan O’Neill
Technical Tip & Tricks For Web2py ...14
by Davide Marzioni
Tutorial for Creating Simple Hyakunin-Issyu Application
Using Sinatra and Heroku ...18
by Tomomichi Onishi
Start Developing Better Web Applications ...28
by Manfred JEHLE
Developing Your Own GIS Application with GeoDjango and Leaflet.js ...33
by Aimar Rodriguez
Solving Metrics Within Distributed Processes ...44
by Dotan Nahum
CreateJS In Brief ...52
by David Roberts
Build Customized Web Apps through Joomla ...67
by Randy Carey
What is Drupal? Concepts And Tips for Users and Developers ...74
by Juan Barba
AngularJS Tool Stack ...80
by Zachariah Moreno
Thinking the AngularJS Way ...84
by Shyam Seshadri
Reusable UI Components in AngularJS ...100
by Abraham Polishchuk & Elliot Shiu
Test Automation with Selenium 2 ...104
by Veena Devi
Grabbing the Elements in Selenium ...109
AexolGL – New 3D Graphics Engine
Aexol specialises in creating mobile applications. It was created by
Artur Czemiel, a graduate of the DRIMAGINE 3D Animation & VFX
Academy, who has a lifelong interest in 3D technology. He first started
to realise his passion by working in the film industry. Artur is the
co-creator of the special effects in Polish production “Weekend” and
the short film “Hexaemeron”, which was awarded Finest Art award
Fokus Festiwal and nominated to best short animated film at fLEXiff
2010 Australia. The experience gained by working in the movie
industry and on the mobile applications market was the basis for
creating AexolGL – a tool designed to make work easier for Aexol and
other programmers around the world.
What is AexolGL?
A set of tools for creating visualisations, applications and 3D games with little workload. The user doesn’t have to worry about things like differences between OS’s or hardware. AexolGL lets you focus on the key elements and appearance of the end product (application, game) instead of worrying about technical details.
What was the main objective and the main incentive to create the engine?
We wanted to create a tool for small/medium-sized devel-oper studios, indie develdevel-opers, that would let them design 3D projects on any platform they want.
Why create two different engines?
AexolGL PRO is a tool for creating games and applica-tions natively in C++/Python, for the following platforms: iOS, Android,Windows, Mac and Linux. AexolGL WEB is used to create games and applications for internet browsers (Mozilla, Safari, Chrome) without the need to use plugins or simple webview apps, games for iOS and Android. Is AexolGL a tool only for creating games and mobile applications? Will it find use in other fields?
AexolGL WEB is a perfect tool for creating visualiza-tions. 3D technology is the modern form of presentation, that works perfectly for visualizing interiors, buildings and product models (e.g. cars and electronic devices). Aex-olGL takes website product presentation to a whole new level.
Will displaying a lot of 3D graphics in web browser slow the user’s computer (AexolGL WEB)?
Most certainly not! The web engine handles displaying 3D very well, even on machines using integrated
graph-Why use Python (AexolGL PRO)?
Python is a easily adaptable scripting language. Being in line with the idea behind the engine itself (quick program-ming), it allows rapid prototyping of applications. Python’s module structure allows the addition of many prepared li-braries, which help make the programmers work easier. How are different scenes, models etc.
imported into the engine?
We have integrated the ASSIMP library with our engine, which allows the import of about 20 different formats. However because it is constantly being expanded that number will increase overtime.
What can you say about the engine structure? One of the main efficiency problems that appear when creating 3D projects are context changes. To minimalize the number of costly changes, while not forcing the object sorting order, we created a RenderTree, which makes sure that operations are not repeated and are executed in the correct order.
Does the engine give user the ability to
implement individual solutions, for example, Yes, we let the user create personal solutions, write custom shaders or effects needed for specialised tasks.
Are there any similar products already on the market? What makes AexolGL stand out (specifically in terms of functionality) in the field of available solutions?
AexolGL, is primarily a tool for small and medium-sized projects, that lets you rapidly prototype and preview them. We do not aim to compete with the big engines. Ours is one of the select few that works on all platforms and has a web counterpart with a similar RenderTree structure.
Are there any examples available? It seems that currently there aren’t any games or more importantly, a tech demo of the engine created with AexolGL available on the website.
We are currently putting finishing touches on our product and the website. Soon gl.aexol.com will host the first ex-amples showcasing the possibilities of AexolGL WEB as well as the first game fro mobile devices created with our technology, called Gravity: Planet Rescue.
Does the engine use optimization algorithms, like occlusion culling? Or others like, for example, those found in Umbra technology. The engine does have the most popular optimization al-gorithms available. Although not as advanced as Umbra’s,
they certainly increase the efficiency of the application. As we expand the engine we will certainly further im-prove this system.
What kinds of lighting algorithms are available in the engine, does it support
lightmapping or global illumination? Do you plan on including realtime global illumination shaders?
We are constantly working on scene lighting. Ultimately it will be one of the advantages of LightRig technology which creates a compact lighting model out of the envi-ronment map, giving the illusion of GI. Currently the en-gine is equipped with several types of lighting and sup-ports shadow-mapping.
How does the engine model terrain, do you plan on using voxels, can you create
heightmap based terrain?
Heightmap based terrain creation is already available. It’s actually very convenient and practical tool useful in a ma-jority of projects. A voxel version might be implemented as well in the future.
To my understanding, the engine provides a joint interface that lets create applications that work both under, for example, Windows and Android? How does it handle the fundamental difference in controls (desktop – mouse and keyboard, mobile devices – touchpad)?
We give the developer the ability to define controls on key-board, joystick, mouse and touchscreen. It is also possible to define a virtual joystick on the touchscreen. However how the application reacts to individual signals is entirely up to its creator. By default, signals from the mouse and one finger touches are treated the same, however they can easily be assigned to different actions.
How about the significant difference in computing power between desktops and smartphones?
Obviously smartphones do have less computing power than desktops, however how the application functions on mobile platforms depends primarily on its design. And for our users, the help of our efficient solutions.
In the currently available version of AexolGL WEB you used the K-3D library licensed by GNU GPL. Why wasn’t this fact mentioned on the product page? Are the licenses
compatible?
The K-3D library is not used in the current version of the engine. The File loading mechanisms employed by K-3D are obsolete and do not support usemtl.
Is AexolGL only a graphics engine or does it also handle other aspects of game creation (physics, optimal resource management, AI etc.)?
Aside from the graphics engine itself, our framework also supports optimal, multithread resource management. We introduced a simple system of creating multiple threads in an application and solved the problem of file loading on different platforms as well. For mobile platforms we prepared a suitable small format for saving 3D geometry. Additionally our engine easily integrates with available physics engines (for example, the popular Bullet Physics). The engine also has an integrated mathematical library equipped with the most needed functions for 3D applica-tions: 2D/3D vector math, transformation matrices and quaternions. As well as countless additional instruments e.g.: color conversions, easing function library, Bezier and CatMull curves and the ability to create simple parameter-ized geometry (cubes, spheres, cylinders).
Similarities and differences between your product and the biggest player, Unity 3D. What is the niche for AexolGL in a market with a free Unity 3D?
Its difficult for us to compare with Unity. The idea behind our engine is completely different. We’re not targeting the biggest studios with complicated and high-budget projects. Our aim is to let small and medium-sized studios benefit from a quick and simple tool that will let them begin their journey into the world of 3d games and applications with-out straining their budget. Obviously we will also contin-ue to work on our project, extending its capabilities and broadening its use. Additionally if we take a closer look at the free version of Unity 3D, we can see that the access to many useful functions, such as Static Batching, Render-to-Texture Effects, Full-Screen Post-Processing Effects or GPU Skinning, is only available to the paid PRO version. Does your product benefit from the new possibilities available in OpenGL 4?
OpenGL 4 is currently only available on PC. Because a lot of mobile devices still use OpenGL ES 2.0 our en-gine is compatible mainly with that API version. Although thanks to the high flexibility of the engine, introducing OpenGL 4 would not be a problem. Users of the AexolGL Lab have the ability to independently adapt the engine to OpenGL 4 thanks to GL abstract.
Jquery is Awesome. So, Use it Less!
by Willian Carvalho
One of the greatest features, if not the only one, responsible for making Javascript shine
brighter in the past years is definitely jQuery.
Since its birth in 2006, it has become very popular, attracting both programmers and web designers, because it made their lives a lot easier.
At that time, server side developers were always paying attention to database and security handling, component layers, message queues, etc and they have never actually been able to focus on client side programming.
Web designers, on the other hand, focused their efforts on building nice designs for applications, as well as caring about user experience and on making the best out of HTML/CSS combo, also leaving Javascript behind. Jquery came to fill this gap between the server and the client tiers.
Enough with cross browser concerns and AJAX handling issues. Enough with lines and lines of code to do simple and repetitive tasks. It was the beginning of a new era for the web development.
The time has passed and tons of jQuery plugins have been built. Almost everybody uses jQuery now, and it has become some sort of a common language between developers and web designers.
Jquery became so popular and easy to use that people started using it for nearly everything, from rich plugins to simple selectors.
This brings us to the whole point on what this article is about: people have forgotten why jquery was built. Frameworks and APIs are made to solve a lot of problems by encapsulating functionalities, like if they were an utility belt. However, these functionalities come with the cost of being too generic, causing them to be slower than if they were built to solve one single problem.
Jquery is no different from other frameworks. But this also doesn’t mean that the additional cost is a bad thing. Actually it means that jQuery is doing what it was supposed to do! It’s just that we shouldn’t be using our utility belt when our own hands do the job as well (or better) than it.
But, what exactly are we doing wrong with jQuery? When should we be using VanillaJS (http://vanilla-js.com/) instead of it? How can we make sure that we made the right choice?
First of all, let me refresh your mind about what jQuery is for. Here’s the description from jquery.com itself: “jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.”
This means that jQuery makes easier for us to manipulate DOM elements, bind and unbind event listeners, write less code to some tasks, such as animations, and it handles AJAX requests a lot easier than we would have done on our own. All of this without having to care about browser compatibility!
Besides these awesome features, jQuery also provides us a very useful set of functions for dealing with loops, reading a particular item on an array, css style manipulation and so on.
Although these functions are very tempting to use, some of them don’t necessarily make our work easier. One example is the use of the $.each function (http://api.jquery.com/jQuery.each/) instead of using the
It might not be of a big difference when iterating a small number of elements, but for larger lists the performance would be compromised. Because deep inside, jQuery is using the plain old Javascript with an anonymous function for every step of the loop.
Besides, the amount of lines of code required to build a loop is not very different between jQuery and pure Javascript. Let’s see:
Listing 1. jQuery sample var arr = [‘a’, ‘b’, ‘c’];
$(arr).each(function(index, data) { console.log(index, data);
});
Listing 2. Javascript sample JS version
var arr = [‘a’, ‘b’, ‘c’]; len = arr.length;
for(var i=0; i < len; i++) { console.log(i, arr[i]); }
As you can see, there is no big difference between them, but keep in mind that pure JS is faster, for sure. There are other cases where we should be using pure Javascript instead of jQuery. Unfortunately, there is no magic way to decide which one, other than analyze each situation.
It is very hard to guess which one is faster, and you will want to make sure which one to use.
A simple way to compare your code with jQuery (or any other code) is by using JSPerf (http://jsperf.com/). With this online tool, it’s possible to create any number of test cases and run them against each other to see how many operations are done per second.
JSPerf is also able to store the results for every test in every browser and version. This is good, because some tests might be quite similar, but one particular browser might have a very different result than the others, which can help you on your decision.
In conclusion, when you are writing a web application, take a 5 seconds break, think about what you are about to use jQuery for, and try to use it properly.
We all know how brilliant it is and how much it has helped us for the past years, but it’s important to always keep in mind why and what it was really built for. Use less jQuery for the best!
About the Author
Willian is a Senior Javascript Engineer at TOTVS. He worked specificly with Javascript for years and he wants to discuss about jQuery.
Jquery Promises
by Ryan O’Neill
jQuery has made working with asynchronous Javascript incredibly easy. However, callback
functions still get quickly out of control leading to code that is both hard to read and to
debug. Usage of the promises pattern via the jQuery Deferred object is a great way to keep
your code clean and maintainable.
This article will give an overview of jQuery’s implementation of the promise pattern, how it can be used to write clean asynchronous jQuery, and an example implementation.
The author has been working with the jQuery library for over five years. He is currently a front-end engineer with Twitter designing and building single page apps using jQuery and other libraries.
For context, this article assumes that the reader has some general Javascript and jQuery experience and is familiar with the asynchronous nature of the language.
Since jQuery’s initial release in 2006, it has grown from a simple utility library into the defacto standard for writing Javascript in the browser. jQuery solved many issues, such as cross-browser incompatibilities and shaky DOM querying, and also introduced features like the $.ajax() function which made it easier than ever
for developers to build dynamic pages and applications without the need for full page reloads.
The Status Quo
The $.ajax() function did indeed change how Javascript applications were built. With the power of AJAX so
readily available, it quickly gained traction within the Javascript community. Shortly thereafter developers ran into a problem which occurred when they needed to make more than one request to a remote server with the second request relying on the response of the first. For example, code that looks like this:
Listing 1. A single AJAX request with callback $.get(‘/user’, function (user) {
$(‘#user-name’).val(user.name); });
$.ajax(
type: ‘GET’, url: ‘/user’,
success: function (user) {
$(‘#user-name’).val(user.name); $.ajax(
type: ‘POST’
url: ‘/user/login’,
data: { userId : user.id }, success: function (loginResult) { alert(loginResult);
},
error: function (err) { // Error handling });
},
error: function (err) { // Error handling });
Even in this basic example adding a single nested request and some trivial error handling makes the code much more difficult to read (partly due to switching to the longer form $.ajax() for error handling. Note that post()
and get() are wrappers for ajax()). In practice, callback and error handling functions are typically much longer
and the need for three or four nested requests commonly becomes necessary. This is especially true if the application uses more than one web service to function. At this point the code becomes effectively unreadable.
Cleaner Code with Promises
By taking advantage of the fact that the $.ajax() function returns a $.Deferred.promise we can break this code
into individual pieces and lay them out much more clearly and without nesting. We’ll get into the $.Deferred interface later. First let’s look at the above logic written using these promises.
Listing 3. Multiple AJAX requests using promises var errorHandler = function (err) {
// Handle Error }
var userRequest = $.get(‘/user’);
var userLoginRequest = function (user) { return $.post( ‘/user/login’, { userId : user.id } ); } userRequest .then(userLoginRequest, errorHandler)
// Any number of then()s can be used here to chain more asynchronous functions together .done(function (loginResult) {
The above code accomplishes the same set of tasks as the code in Figure 2. Through the use of jQuery promises we are able to chain the asynchronous requests together rather than to rely on messy nested callbacks resulting in a script that is both easier to read and more maintainable. A few things to note:
• done() and then() appear to be similar. A key difference is that then() will pipe the result of the callback(s)
into the next piece of the chain
• Note that in the then() block we need to return the result of the second AJAX request rather than to call it
standalone. This is so that the resulting $.Deferred from the userLoginRequest gets passed into the done()
function, allowing us to make use of its result
• We also hoisted a generic error handler for an even clearer solution.
What is $.Deferred?
Under the covers $.Deferred is a stateful callback register that follows the convention of Promises/A (http:// wiki.commonjs.org/wiki/Promises/A). The promise has three possible states: pending, resolved, and rejected. Every $.Deferred object starts in the pending state and can move into either the resolved state via the
resolve() function or the rejected state via the reject() function. In practice, these two methods are called
internally by the library being used. For instance, the $.ajax() function handles resolving and rejecting the
promise. In fact, the resolve() and reject() functions will not even be available to us. This is because the
object returned from $.ajax() is actually a $.Deferred.promise which exposes only the functions to attach
callbacks and hides the functions that control the promise state. You can also take advantage of this if you are writing code that returns a promise that other code will subscribe to.
When a promise is rejected, all callbacks registered to the promise via the fail() function will execute.
Similarly, when a promise is resolved the callbacks registered via the then() or the done() method will be
called. If we need a block of code to run when the promise completes regardless of whether it is failed or resolved, we can attach those callbacks using the always() function. This is analogous to a finally statement
in a try/catch block and is generally used for running clean-up code. Listing 4. Using always()
$.get(‘/user’, function (user) { $(‘#user-name’).val(user.name); }).always(function () {
alert(‘AJAX request complete’); // This will always be called });
Keeping a clean, maintainable, and readable code base requires active effort and diligence from all developers involved. Promises are not a magic bullet and code can still get out of control when using this pattern. When used correctly, promises can offer a large improvement in flow control relative to the traditional callback pattern.
About the Author
Ryan O’Neill was born in Washington D.C. in 1986. Since then he has taken residence in Miami, Atlanta, Chicago and San Francisco. He has worked with web technologies for the better part of a decade and is currently a senior front-end engineer with Twitter (you can follow him @rynonl).
Technical Tip & Tricks For Web2py
by Davide Marzioni
Web2py (http://www.web2py.com) is an amazing framework to develop a fully-featured
web-based application using Python language (http://www.python.org).
Web2py inherit all Python feature in term of simplicity, power and flexibility and it applies
them to a web environment.
You will find a lot of useful tools like a database abstraction layer, authentication form and
form-making utilities.
What you will learn
In this article I want to share with you some tips and tricks that could be useful when programming with Web2Py framework. What you should know
You should have a basic knowledge about how Web2Py works.
Use Aptana Studio as IDE
The integrated admin tool in Web2py is good enough to develop simple application and to do quickly edit, but if you want a stronger tool I suggest you to use Aptana (http://www.aptana.com). The main advantage to use Aptana as IDE is that you can use the integrated debugger.
Setup Aptana for Web2Py is easy: • Create new ‘PyDev Project’ • Name it ‘Web2py’
• Uncheck ‘Use default’ under ‘Project contents’ and select the path to your local Web2py folder • Be sure you are using Python 2.5-2.7
To run Web2py you need to create a custom launch configuration: • Select ‘Run’ menu and then ‘Run configurations...’
• Right click on ‘Python Run’ and select ‘New’ • Name it ‘Web2Py’
• Select the ‘Web2py’ project just created • Select ‘web2py.py’ file as main module • In the arguments tabs use the options:
• -i 0.0.0.0 to bind web2py to all network • -a 123456 as dummy administration password
• -p <num port> if you want to change the default port (8000) • Press ‘Apply’ button to save the configuration
The only drawback in using Web2py in any IDEs (Aptana included) is that it doesn’t understand the context (the gluon module) and therefore autocompletion doesn’t work. To solve this issue you can use a trick to add in the models and controllers with the following code:
Listing 1. A trick if False:
from gluon import * request = current.request response = current.response session = current.session cache = current.cache T = current.T
This code isn’t executed but it does force the IDE to parse it and understand where the objects in the global namespace come from.
Modify a form with form.element
Web2py has some function helpers to define forms (FORM(), SQLFORM(), SQLFORM.factory()). Howeveroften
happens that you’ll need to modify a form element after the declaration (styles, default values, etc.). You can do it using .element() and .elements() methods. They are equivalent but elements return a list of item if there
are more corresponding to the criteria you inserted.
Items returned can be modified using the standard notation: undescore + attribute name.
The parameters of these functions are descriptor of what item you want to return. The only positional
parameter is the item type you want to modify (eg. input, textarea, select, etc...). Other parameter are explicit and depend on the attribute you want to filter.
For example we want to change the submit button style classes. Listing 2. Change the submit button style classes
submit_button = form.element(‘input’, _type=’submit’) submit_button[‘_class’] = ‘btn btn-large btn-success’
To change the selected status of an option item. Listing 3. Change the selected status of an option item
default_option = form.element(‘option’, _id=’option_1’) default_option[‘_selected’] = ‘selected’
del default_option[‘_selected’]
To change the text of a textarea. Listing 4. Change the text of a textarea
textarea = form.element(‘textarea’, _name=’description’) textarea[0] = ‘New text’
Listing 5. Change the style of all inputs for input_field in form.element(‘input’):
input_field[‘_style’] = input_field[‘_style’] + ‘ width: 200px’
How to write a custom validator of two linked field in a
table
Validators are special functions which helps to validate a form or database field. You can insert them using the ‘requires’ keywords. If you want to have a database table where only one of two fields must have a value, there will be trouble to define this with standard validators. This can be resolved by a custom validator. For example, if you have a ‘website’ table where, for some reason, you want be filled an IPv4 address or a URL link, only one of them but not both together. In addition you want use the default validator for both fields. To solve this problem you can define in the model a custom LinkedFieldValidator and use it in the requires values of the fields.
Listing 6. TwoLinkedValidator in a model file. class TwoLinkedValidator:
def __init__(self, a, b, validator=None,both_filled_message=’Enter only one field!’, both_ empty_message=’Insert at least one field!’):
self.a = a self.b = b self.v = validator self.error_filled = both_filled_message self.error_empty = both_empty_message
def __call__(self, value):
if IS_NOT_EMPTY()(self.a)[1] == None: if IS_NOT_EMPTY()(self.b)[1] == None: return (value, self.error_filled) if self.v:
return self.v(value) return (value, None) else:
if IS_NOT_EMPTY()(self.b)[1] == None: return (value, None)
return (value, self.error_empty)
def formatter(self, value): return value
Init function requires the two field to validate. Parameter ‘a’ is always the self-referenced field, while ‘b’ is the other. Optionally I can pass another validation function in the validator parameter.
The validation functions return a tuple where the first value is the formatted value (no formatting is done in this case) and the second value is an error message (None if the value is correct).
Listing 7. A sample code db.website.weblink.requires = LinkedFieldValidator(request.vars.weblink, request.vars.ipaddress, IS_URL(mode=’generic’, allowed_schemes=[‘ftp’, ‘http’, ‘https’])) db.website.ipaddress.requires = LinkedFieldValidator(request.vars.document_file, request.vars.weblink, IS_IPV4())
How to solve lazyT issues
Web2py has a great tool to internationalize the content: the T() function. Every string inserted as parameter
will be putted in the translation files.
T() works in default mode as lazy. It means that the real content is established when rendering the view.
A lazy T returns an object instead a string, so if you need the translated value string in a function, you’ll get a an error ‘argument must be string or read-only buffer, not lazyT’
Listing 8. Example of error string
timestamp_string = datetime.strftime(datetime.now(), T(‘%Y-%m-%d %H:%M’)) label = DIV(timestamp_string)
Then you have two options:
• Use a function that immediately force to cast a lazyT object to a string like .xml().
• Disable temporarily lazyness with T.lazy = False,
In the previous example you can. Listing 9. First solution
timestamp_string = datetime.strftime(datetime.now(), T(‘%Y-%m-%d %H:%M’).xml()) label = DIV(timestamp_string)
Or you can try that!
Listing 10. Second solution T.lazy = False
timestamp_string = datetime.strftime(datetime.now(), T(‘%Y-%m-%d %H:%M’)) label = DIV(timestamp_string)
T.lazy = True
About the Author
I’m Davide Marzioni and I have worked since 2011 as software developer for a small company in Italy mainly focused on research and development in automation and electronic fields. I use Web2py in many projects I can because it bring in easy way your application to a web environment.
Tutorial for Creating Simple
Hyakunin-Issyu Application Using Sinatra and
Heroku
by Tomomichi Onishi
Figure 1. Image of Karuta – Hyakunin-Issyu based card game (photo credit: aurelio.asiain via photopin cc)
Overview
In this tutorial, we’ll see how to create a web application using Sinatra, the light-weight Ruby framework, and how to deploy it on Heroku, the web application hosting service.
We create a simple web application as a sample, using Hyakunin-Issyu, the beautiful anthology of Japanese ancient poems, as a theme.
This app has only two pages; the one shows the list of all the poems and the other one shows the detail of each poem.
(Don’t worry if you never heard of Hyakunin-Issyu. You’ll see a quick guide at the end of this introduction.) What you will learn…
Through this tutorial, you’ll learn the following. • how to use Sinatra framework
• how to deploy your app on Heroku • general understanding of Hyakunin-Issyu What you should know…
This tutorial expects you to know.. • Ruby
• Gem management using Bundler • Git
About Hyakunin-Issyu
Hyakunin-Issyu, or the one hundred poems by one hundred poets, is an anthology of one hundred tanka, a Japanese poem of thirty-one syllables, selected by a famous poet in the medieval period.
http://en.wikipedia.org/wiki/Ogura_Hyakunin_Isshu – Wiki page of Hyakunin Isshu
Tanka is made of thirty-one syllables, five-seven-five for the first half of the poem and the seven-seven for the last half.
As it can’t contain very much information on such a limited number of words, it’s very important to feel the aftertaste of the poem.
Composing a poem with very selected words, describing the delicate feelings and the beautiful scenery of nature, is a very Zen-like way and this is the culture we Japanese should be proud of.
We often play the Hyakunin-Issyu based card game called “Karuta” in the New Year’s holidays in Japan. The basic idea of the Karuta game is to be able to quickly determine which card out of an array of cards is required and then to grab the card before it is grabbed by an opponent.
Chihayafuru, the karuta themed comic, became a big hit in Japan and now this traditional culture has became popular again.
Please take a look at this comic if you are interested.
http://www.youtube.com/watch?v=rxebYxY9NXE – opening video for Chihayafuru anime Okay, I think that’s enough for the intro.
Now it’s time to start the tutorial.
Using Sinatra
The first half of this tutorial is to create an simple application with Sinatra.
The very basics of Sinatra
Minimum construction
To start with the smallest possible project, all you need is two files. Listing 1. The construction of the project files
|-sample |-main.rb |-Gemfile
The core parts of the application will be written in main.rb.
At the moment, we only need to add routing for root (‘/’). So any requests for ‘/’ will be processed here. In this example, we’ll output a simple “hello world”.
Listing 2. The minimum implementation of main.rb #main.rb require “sinatra” get ‘/’ do “hello world.” end
Next, make a Gemfile for gem management. Now you only need a Sinatra gem. Listing 3. List gems on Gemfile
#Gemfile
source :rubygems ruby ‘2.0.0’
gem ‘sinatra’
From the terminal, run “bundle install” to install gems to the project. The project settings are almost done!
Move to the project root and run “ruby main.rb” from the Terminal.
The application will be run on port:4567 (this may be different on your machine, so be sure to check the output in Terminal).
Open your browser and access ‘localhost:4567’.
If successful, you should see the words “hello world” displayed there. Adding more pages
Okay, now we’re going to add some more pages to this app (it’s just too simple, otherwise!). Edit main.rb to do this:
Listing 4. Adding more page to main.rb #main.rb
...
get ‘/poem’ do
“this is another page!” end
Well done! Now we have another page with the route ‘/poem’.
Restart the project by running ruby main.rb and access “localhost:4567/poem” in your browser. You should now see “this is another page!” displayed there.
Auto reloading Sinatra
It can get tiresome to restart the process every time you’ve changed something in the code. To make things easier, let’s introduce auto-reloading into our app.
Listing 5. Add sinatra-contrib to Gemfile #Gemfile
...
gem ‘sinatra-contrib’
Add this line to Gemfile and run “bundle install” again. Then require sinatra/reloader on main.rb.
Listing 6. Require sinatra/reloader in main.rb #main.rb
require ‘sinatra’
require ‘sinatra/reloader’ ...
That’s all we need. Try restarting main.rb again (it’s the last time, I promise!), then access “localhost:4567” in the browser.
Next, change the “hello world” message on main.rb and refresh the page. If all goes well, you’ll now see the message changed without having to restart.
Accept parameters
One last thing for this section is to accept URL’s with parameters, like “/poem/13”, so that the page contents update based on this new value.
Listing 7. Accept parameters in main.rb #main.rb
get ‘/poem/:id’ do
“this page shows the detail of poem-#{params[:id]}” end
Add :id to the get part, and use that param with params[:id].
Now try accessing “localhost:4567/poem/13”. The content should have changed.
Developing the main parts
Okay, we now have much of the core of the project completed.
I have made a HyakuninIssyu gem which allows us to use poem data easily, so lets install it. (don’t worry, the file contains English data, also)
If you want to know how to use the gem, please check it out, here.
https://github.com/Tomomichi/HyakuninIssyu – Tomomichi/HyakuninIssyu
Install HyakuninIssyu gem
Listing 8. Add HyakuninIssyu gem to Gemfile #Gemfile
gem ...
gem ‘HyakuninIssyu’
You’ll also need to ‘require’ it in main.rb.
Listing 9. Require HyakuninIssyu gem in main.rb #main.rb
require ...
require ‘HyakuninIssyu’
With that done, check to make sure it works. Listing 10. Add sample code to test gem #main.rb
get ‘/’ do
data = HyakuninIssyu.new data.poem(1).kanji end
Add this to main.rb and then access “localhost:4567” in your browser. Have you found the poem of Emperor Tenchi (in Japanese this time)?
Figure 2. The card of Emperor Tenchi
This poem describes a miserable life of farmers, but isn’t it strange that the emperor composed a poem like this? How could he understand the feelings of those people?
Okay, we’ll now finish the index page using this gem.
This page shows the list of all the poems. Use the poems method of the gem: Listing 11. List all the poems in index page
#main.rb get ‘/’ do data = HyakuninIssyu.new @poems = data.poems end
That’s it. We set all the poems data to @poem. Now it’s time to finish view files.
Use separate view files
It’ll be messy if you write all the html document in main.rb, so we will divide the code and use separate view files.
Listing 12. The construction of the project after adding view files |-sample
|-... |-views
|-index.haml |-poem.haml
Add a views directory and create haml files there. Install haml gem to use haml files.
Listing 13. Adding haml gem to Gemfile #Gemfile
...
gem ‘haml’
And now create the index.haml file to show the list of poems. Listing 14. Index.haml #views/index.haml %h1 INDEX – @poems.each do |poem| – unless poem.nil? %p #{poem.kanji} %small #{poem.en}
Listing 15. Declare the use of haml file #main.rb get ‘/’ do ... haml :index end
This simply means that it uses views/index.haml as a view file.
Now let’s access “localhost:4567” again to see whether the content of index.haml is shown there. Remember that we used @poems in main.rb.
This enables us to pass that variable to the view file.
Now the index page is done. Let’s move on to the second page. Poem detail page
As we enabled the parameter handling already, we use it to get poem data from the gem. Listing 16. Developing poem detail page
#main.rb ...
get ‘/poem/:id’ do
id = params[:id].to_i #treat the parameter as an integer data = HyakuninIssyu.new @poem = data.poem(id) @poet = data.poet(id) haml :poem end
We set the poem data to @poem and @poet, and declared that we use views/poem.haml as a view file. The poem.haml file should look like this:
Listing 17. The content of poem.haml #views/poem.haml %h1 POEM %div %h2 Poem Info %p #{@poem.kanji} %small #{@poem.en} %div %h2 Poet Info %p #{@poet.name.ja} %small #{@poet.name.en}
Access “localhost:4567/poem/13” in the browser, perhaps with a different poem number, and check the poem data is shown correctly.
Finish the development
Listing 18. Add a link to index.haml #views/index.haml %h1 INDEX – @poems.each do |poem| %p %a(href=”/poem/#{poem.id}”) #{poem.kanji} %small #{poem.en}
And add a very simple back link to poem.haml. Listing 19. Add a link to poem.haml
#views/poem.haml ...
%a(href=”/”) Back
Okay, we’ve now finished developing this very simple Sinatra web application.
It shows the list of all the poems of HyakuninIssyu, and you can see the detail of each poem. Now let’s try to deploy this to Heroku.
Heroku Deployment
The last half of this tutorial is deploying the Sinatra application to Heroku. Before continuing, please sign up and create your account on Heroku. https://id.heroku.com/signup – Heroku Sign Up
Also you’ll need the Heroku Toolbelt to use the heroku command. Please download this from the link below:
https://toolbelt.heroku.com/ – Heroku Toolbelt Okay, now let’s get started.
Create a Heroku app
First you need to create a Heroku app.
Move to a new project root and run the following comand: Listing 20. Create a new heroku app
heroku create YOUR-APP-NAME
That’s all. The empty app is created on heroku and it’s added to your git remote repository. (You can check this by running the git remote command)
Create a system startup file
Create config.ru file as shown below: Listing 21. Create a config.ru file #config.ru
require ‘bundler’ Bundler.require
require ‘./main’ #requiring main.rb run Sinatra::Application
Introduce a git version management
As we use the git command to deploy the app to Heroku, we need to introduce git and commit the changes so far.
Listing 22. Introduce git version management git init
git commit -m “initial commit”
If you’re not familiar with git, check the Git Book or other tutorials. http://git-scm.com/book – Git Book
Now we’re ready for deployment!
Deploy to Heroku
Deploying to Heroku is extremely easy. Just run the following command: Listing 23. Deploy command to Heroku
git push heroku master
That’s it. After successfully building your app on Heroku, run “heroku open” or access “APP-NAME.heroku-app.com” to see your app.
Is your app working well? If you find some errors, please run “heroku logs” to see what’s wrong. Okay, that’s the end of the tutorial.
The final version of the codes are in my GitHub repository.
If your code doesn’t work, please check there and compare it with yours. And more..
This tutorial covers only the very basics of Sinatra and Heroku to keep it simple. If you find them interesting, please go further to get to know them better.
• use layout/shared files in view • use Helper
• introduce SCSS, CoffeeScript • internationalization of the app • test with Rspec
• introduce login management with Sorcery Heroku
• prevent Heroku app from sleeping with Heroku Scheduler • monitor the app performance with NewRelic
• use thin server instead of webrick • build the staging app
• connect to the database and backup it
• use Travis CI for the automatic test and continuous deployment Hyakunin-Issyu
• learn the poems of Hyakunin-Issyu and remember them • read Chihayafuru to know the poems more.
• join the Karuta game.
If you have an interest on these topics, I’ll write the next article about them.
Please send me a request to let me know what you would like next: [email protected].
About the Author
The author of this article is a Japanese web developer interested in Hyakunin-Issyu. My GitHub account is here: https://github.com/Tomomichi – the author’s github account. My past products are:
• booklovesmusic: Music recommendation service which matches your favourite books • Hyaku-Ichi: Will help you to remember Hyakunin-Issyu about a month from nowt
Start Developing Better Web Applications
by Manfred JEHLE
Web applications are a good thing – no client installation needed and they usually work with
different browsers and browser versions properly! However, their functionality and look and
feel are currently much different than a desktop application.
That has not to be so! We look step by step at various issues and suggest resolutions to brush
them up. The resolutions also provide additional benefits that make web applications more
useful than a desktop application.
Avoid that flickering screen
Most web applications are designed as common web pages, frequently by the same developer creating the marketing web pages. On marketing designed web solutions pixel accurate representation of the content is in great demand, whereas page reloads or rebuilds of the whole page are not an issue. On the other hand, in a web application the permanent reload of the whole page makes the work slow and unattractive. Additionally, the reload means also that a lot of data has to be transferred from page to page.
Solution
To solve the flickering screen use AJAX functionality and you are able to replace any identifiable part on the web page without reloading the whole page. In other words, you need a real single page application. If you choose a good AJAX libraries support features such as: changing input element types, for example, text input to drop-down box depending on the entered value by identifying on server side and providing additional content back to the page.
With AJAX, you can develop user-friendly applications like desktop applications.
Developer’s corner
Web application architecture contains not only the server side – it covers also the client side. To get an efficient client application it is not necessary to hold all the JavaScript code initially time loaded in the single page. Such designs frequently result in slow, inefficient web applications with too much overhead that suffer from lost flexibility and maintainability. Keep an eye on the client side HTML code structure and reloading and disposing partial JavaScript code.
Web application environment
Some web applications are developed for Silverlight or flash, but these technologies are not usable in the most browsers on mobile devices. Not all browser and operating systems supports flash and SilverLight technology. The current heterogeneous environment of devices and device vendors limits the IT department in flexibility. Remote desktop orientated solutions like Silverlight or remote desktop solutions are not the real solution because the usability is not the best for mobile devices. Try to use with the fingers a standard designed desktop application on a mobile device – your fingers are mostly too thick to get the best interaction on screen.
Solution
Use pure HTML on the client side! The reward for your efforts: approximately 80% compatibility with common browsers.
Developer’s corner
Avoid using hacks to get a nonstandard or incorrectly implemented browser element running! When the browser is fixed, your hack will produce mostly side effects so that you have to remove the code previously fixing a bug. Use code that will run in all browsers at development time and you will be on the better side!
No Menu
A lot of web applications are not designed with the elements commonly used in desktop applications. The look and feel of desktop applications is given by standard user interfaces like a menu bar with all the commands needed to handle the application. Web applications are frequently designed against marketing pages standards, which, as described above, are not the right approach for web applications.
Solution
Consider application processes, keeping the focus on making your web application function like common desktop applications. Use a common menu element to make all options available in the menu bar and control the icons and descriptions only if the function is available in the current context. Use common icons and domain specific or a general (common) naming for the menu items.
Developer’s corner
Use a state machine to handle all the combinations of menu items state and the availability of menu functions. Show and open events are not clear enough because menu parts can be set as inactive or hidden too on different content stated like in a common desktop menu.
Ribbon
The ribbon user interface element is not often used in web applications. But this element provides of fast access to many of the web application’s functions and provides handling closer to the common Microsoft desktop applications.
Solution
If it makes sense add a ribbon to your web application to make more useful functions accessible for users. Don’t hide functions in the depth of menu structures!
Developer’s corner
Use a state machine to handle all the combinations of ribbon items state and the availability of ribbon functions. The same applies for any ribbon item as for any menu item applies too to have additional states like hidden or inactive.
Undo and Redo
Most web applications have no built in Undo or Redo function, but in desktop applications this functionality is one of the most used. Providing this functionality in web applications greatly improves user experience.
Solution
Keep the last actions in the background to implement the Undo and Redo functionality. Practically speaking, it is not so simple but try to add it in your next update or new web application.
Developer’s corner
You must check on each Redo operation to ensure it makes sense at the current position. The Undo is not a big problem because the content refers directly to the content part on that a Redo makes sense.
Wizard functionality
In some desktop applications a wizard helps users step by step through entering and editing data. The wizard makes it easier for users to get enter structured data into the application. Such functionality is also used in online survey tools. But in many web applications, a wizard would make it easier for the user to enter the data. Another option is to allow the user to switch between dialog and wizard-based data editing.
Solution
Provide a wizard for the dialog-based data editing and allow switching between the two views.
Developer’s corner
Use in the edit dialog web parts and make them visible or hide them to get the switch between common dialog content and wizard content.
Push function
In some desktop applications you can be pushed by other user’s activities when using the same data or file. The common workaround is notifying a user that you are editing the data which the other user is already viewing Another method is presenting a read-only view until the editing has been completed.
This functionality needs information about what you are currently viewing and what other users are doing. Web applications can also provide this functionality but I have not seen many web applications, other than my own, implement this functionality.
Solution
It is possible to implement a notification to other users handling the same data, but keep the same in mind, just as with desktop applications – use this functionality only when circumstances call for it.
Developer’s corner
Use a simple JavaScript timer to ask the server who is using the same data as I use currently and hold the notifications ready for the other user. With a second timer ask for notifications on the server. Without any web socket you can provide content “like” from server pushed. At the moment for web sockets is no implementation available working on any browser and operating system.
Local devices
In desktop applications it is mostly not a problem to add local devices or other devices in the network to the functionality of the solution. In web applications the usage of local devices is mostly a reason why a web application is not practical to develop except printing. But that assumption is not true! With a little more effort it is possible to use most local devices in a web application.
Solution
Expose devices to web applications accessible by wrapping them in a local service with a web service interface. With this trick it is possible to access local devices through the server, and by proxy the external application.
Developer’s corner
If you build such services it is the easier way to use REST services.
Dump and last actions
In some really professional developed desktop applications when an error occurs you may be able to send an application dump, with the last few actions performed, to the software support centre or helpdesk.
That allows the support team to rebuild the current state and execute the last action before the error occurred. Similar functionality is currently not common on the client side; on server side it is a common and helpful support feature. It is possible to build in such a dump and last action functionality on the client side. The support team can easily recover the HTML page while getting the real HTML page part.
Solution
Adding such a function to the web application does not take much effort. You have to cover the URL based actions (GET, POST actions) and store them into a first in last out (FILO) queue. The dump is quite easy to implement: select the html part, copy the outer HTML and send it through the server to the support team.
Developer’s corner
Use the standard functions from jQuery to capture the HTML dump. The FILO needs a little bit more JavaScript effort, but not too much.
Device detection
Device detection in desktop applications has no significance because it runs mostly in similar environments or is designed to run on different operating systems with standard desktop screens. Exemplary web
applications support a wide range of devices such as tablets and phones along with desktop machines. By detecting the device, you are able to deliver device – depending content to the target. Common web application solutions support the usual boring actions such as zooming and moving screen content, but frequently suffer from issues such as clicking the wrong link because your fingers are too thick. Mobile users benefit from device specific content that is intended for fingers.
Most web applications detect devices at CSS level, but deliver every time the full content and hide only some parts or enable alternate designs for smart phones and tablets. Such a solution is ineffective because it wastes bandwidth by forcing the device to download extra, unnecessary content. Only a delivery of the effectively needed content will be an efficient solution.
Solution
Detect the device in your web application and deliver only device-specific code.
Developer’s corner
Don’t be satisfied with common CSS solutions – go a step further by detecting the device and delivering content specified for that device. It is required to get at any time the screen of the smart phone in 100% scale visible! Overall, a smart phone ready design will involve some effort.
Common URL
In the content of device detection it is mandatory that you have the same URL and sub URL’s for all devices. The common URL is needed to store page links in the cloud or in a common link collection. Only with a common URL base the web application will be handy for users working with different device types.
Developer’s corner
Don’t think about URL switches – they don’t solve the problem of URLs stored in link collections!
Final statement
Web applications are not dead! In today’s multi-device environment, web applications soar to new prime of life. Most web applications are developed for low budgets but they are used as desktop applications developed for high levels. This gap and the described missing functions can lift up the web applications to a higher level. It’s clear that mostly it needs some effort to achieve the higher state, but finally you get an actual solution ready to use in several devices.
Another fact
Web applications developed more than thirteen years ago runs without any update of the user interface without problems in the current browsers. How many desktop applications can get such a lifetime with all the operation system changes in the past?
The discussions about apps reminds me of the late 90s, when the battleground was between operating systems. At the moment we have the same kind of solution as we got at the past by JAVA – a crutch not really working perfectly for the app development.
For the foreseeable future, the web application provides a common base for all operating systems and devices – the browser.
About the Author
Manfred is CEO and Chief Architect of several products and customer projects and has more than 17 years of experience in web applications and more than 28 years in general information technology. Contact: [email protected]
Developing Your Own GIS Application
with GeoDjango and Leaflet.js
by Aimar Rodriguez
Geographic information systems seem to have been proliferating lately, both on smart
phones and on the web. GeoDjango is a module included in the Django contrib package
which allows to easily create geographic web applications. In this article we will build a
simple GIS application using GeoDjango and Leaflet.js.
What you will learn
You will learn to develop a simple geographic application using Django. You will learn to set up a geospatial database using Post-greSQL and PostGIS, to represent and manipulate the data stored in this database with Django models and GeoDjango extensions for this models and to present it to the user using the HTML5 map framework Leaflet.js.
What you should know
In order to fully understand this article some knowledge about the basics of the Django web framework are recommended, as well as knowledge of the Python programming language, even though they are not required. It is also advisable to have some knowledge about the JavaScript programming language.
A Geographic Information System or GIS is a computer system that enables users to work with spatial data. Even if this concept was invented around the 60s, it has only taken relevance in the past years, with powerful applications like Google Maps or OpenStreetMap. The proliferation of this kind of applications has been huge to the point that now event the smallest local transport company uses this technologies. We have all kinds of projects, from social networks based on routes like Wikiloc to project which attempt to bring a spatial dimension to The Semantic Web, like LinkedGeoData or GeoSPARQL.
One of the biggest benefits that the developer community have gotten from this phenomena is the
appearance diverse tools and framework for spatial data manipulation, and this is where GeoDjango comes into play. Django an open source web development framework written in Python, it has a huge community and a wide amount of tools for the developers. Many of this tools come included in the contrib package of
the framework, where we can find the geographic web framework GeoDjango. What this package offers to the web developers is the following:
• The Model API, to store, query and manipulate the geographic data stored in the database using the typical Django models,
• The Database API, to manipulate different spatial database back ends,
• The Forms API, which provides some specialized forms and widgets to display and edit the data on a map, • The GeoQuerySet API, which allows using the QuerySet API for spatial lookups,
• The GEOS API, a wrapper for the GEOS open source geometry engine, for C++, • The GDAL (Geospatial Data Abstraction Library) API,
• The measurement objects, which allow convenient representation of distance and area measure units. Apart from the aforementioned, several utility functions, commands are included in the package, as well as a specialized administration site.
We will be developing a very simple GIS application, which allows user to upload routes and to visualize them in maps. We have already seen that we can store and manipulate all this data with GeoDjango, however, we
Both are JavaScript libraries which allow to create a dynamic map on a web page. Which library to choose is up to each developer, I personally prefer Leaflet.js for its ease of use and learning. However, OpenLayer is a more mature project and promises several improvements in its third version which is yet to come.
With these two tools we can easily create a GIS web application of any kind. However, when developing one of these we will have several concerns, not related with the available technologies, for example, where can we get our data from? One approach which is followed by many is to let our users generate the data, however this is not always suitable for our application. It is also quite common to use external information sources, like available web services. Even if we are not going to explore the possibilities that these web services offer, I will give the following list of web services with some of the functions they offer.
• Nominatim, a tools to search OSM (OpenStreetMaps) data. It allows address lookup and reverse geocoding, among other functions. A guide to this search engine is published on http://wiki. openstreetmap.org/wiki/Nominatim,
• The OSM API. OpenStreetMaps offers an XML API which allows to upload to and download data from their database. You can find more about it the following address: http://wiki.openstreetmap.org/wiki/API_v0.6, • LinkedGeoData. For those desiring to implement a semantic spatial web application, know that
LinkedGeoData offers and API and has developed an ontology. It even has one SPARQL endpoint. More information on http://linkedgeodata.org/OnlineAccess,
• Google Maps API web services. Google maps has its own API (even has a library for map visualization). However it imposes several limitations, so it is not used for more advanced GIS applications. More information on the google developers webpage: https://developers.google.com/maps/documentation/webservices.
The Web Application
To introduce this two libraries we will develop a very simple web application. It will allow users to upload routes in GPX format, which will be processed and stored in a spatial database. Then, the users will be able to browse all the routes and visualize one of them. We will also perform a small analysis of these routes, using the GEOS API.
The code will be presented along the article, however, the whole project can be found in the following repository: https://github.com/aimarrod/SimpleGISApp.
The web application will consist on a simple HTML page, which will contain a form allowing the users to submit their GPX files, a map showing a route and a list of all the uploaded routes. On the back end we will have a small Django project with a PostgreSQL database extended by PostGIS. The choice of database has been done taking into account that GeoDjango offers some limitations depending on the database, and the least constraining one is PostGIS. Anyway, there are several choices, for example, MySQL, so feel free to use any of them.
The first steps
First of all, we have to install a PostgreSQL database and the Django framework (and of course a python interpreter if you don’t have it yet). This is usually trivial and if you are working on a Linux distribution you may find instructions on how to do it in your distros wiki.
Note
From now on I will be assuming that PostgreSQL, Django and Python2.7 are installed. Since I am working with an Arch Linux distribution, so some installation steps may vary. Also, I will not be explaining all the basics of the Django framework, some aspects like the settings file and the urls.py file will be omitted, if you don’t know the framework I encourage you to look up the Django documentation page, which explains everything very nicely. You can find it in the following address: https://docs.djangoproject.com/en/1.5/.