• No results found

In this section, we will show you how to set up the development environment.

Python can run on Unix, Linux, Windows, Mac and many more environments from mainframes to portable devices. In this tutorial, we assume that you will be developing in a linux box running Ubuntu. If you are using Windows or Mac, it’s possible to create a virtual machine using Virtual Box, VMware Player and run Ubuntu inside your own operating system.

On Ubuntu, Python usually comes pre-installed. You can check if it is there by typing python in a terminal window which should cause the Python interpreter to start showing it’s version and prompt characterized by the sign >>>. After you start your Python interpreter you can close it easily by using the Ctrl+d shortcut. If Python is not installed, you can install it using the package manager from your Linux distribution. On Ubuntu, as your own user type sudo apt-get install python in a terminal window. Beside the Python binary, in order to have a full development environment we advise you to also install the python-dev package by typing sudo apt-get install python-dev on your terminal.

Python has its own libraries/package manager. To install Python libraries you need first to install the Python package manager and then, using it, install the needed packages and libraries. At the time of this writing, the most used Python package manager is Pip. To install it on your Ubuntu box, use the following command sudo apt-get install python-pip. To use the frameworks presented in this article, you will need to install the package that contains the framework and its dependencies. That can be easily achieved with Pip. For example, to use Django, you will have install Django package with its dependencies using: sudo pip install django. When you are developing multiple python projects, you should consider using Virtualenv. It’s the best way to avoid conflicts between libraries and package versions. Virtualenv basically builds all the needed Python infrastructure (binaries, libraries and so on) inside an isolated directory. After this directory is created you need to activate the virtual environment which will allow you to install via Pip all packages and libraries inside it.To install Virtualenv through Pip, you can use the command sudo pip install virtualenv.

Now, to create a virtual environment, you should go to your project directory using a terminal window and once inside it you use the command virtualenv <ENV_NAME> where ENV_NAME is the name of your environment. Virtualenv will then create a subdirectory called ENV_NAME inside your project’s directory and build all the basic Python structure inside it. Before developing from your project directory you should run source ENV_ NAME/bin/activate to activate your environment. By doing that all your python variables will be pointing to the files in your environment instead of the system defaults. After activating your virtual environment, you can install the needed libraries and packages for your project and they will be installed inside the virtualenv subdirectory inside your project’s directory. Due to the fact that now all your environment sits on user space, you don’t need to use sudo to install packages and libraries inside the virtual environment through Pip. After you finish installing the needed libraries and packages, you should use the command pip freeze > requirements.txt to create a requirements file that will contain all the packages and libraries followed by their versions. With this file in hand it’s trivial to re-setup your environment on other machines or even on deployment to production by using the command pip install -r requirements.txt.

Now that your development environment is ready, we can start showing the main framework options to develop a web application using Python.

All listings presented in this article are available on github, as listed in “On the Web” section. There, we listed the packages required for the example to run.

Frameworks

When developing a web application or a web service, you may choose to write it from scratch using the libraries that come with Python distribution or you may use framework. A framework may save you a lot of time, but it comes with a learning curve. Django is the most complete framework and suitable for developing a full web application, but it may not be the best option if all you need is to write a simple web-service. In this case, Web.py may be your best choice. In the end, the decision depends on what you need to build, what you and your team already know and the time frame you have for the project. In this section, we will show the main framework options and show a simple hello example, in order to help you choose the best framework for your project.

Web.py

web.py is a small web framework that aims at simplicity and not getting in the way. It is currently used by Yandex, according to its website. Mainly, it consists of a regular expression based url routing map and a class to server requests through methods named after the HTTP request method in use. Lets look at a simple example in Listing 1.

Listing 1. Simple web.py example import web

class MyService:

def GET(self, name):

return “Hello {0}”.format(str(name))

urls = ( ‘/(.*)’, ‘MyService’ )

app = web.application(urls, globals()) if __name__ == “__main__”:

app.run()

In the example, all requests will return the string “Hello uri”, where uri will be replaced by whatever is sent in the url after the server name/port. Uris are mapped by a tuple:

urls = ( ‘/(.*)’, ‘MyService’ )

The mapping consists of every two elements in the tuple, an uri regexp and a class that provides a handler function. If you need to map more uris, you can just insert them in the tuple, as you can see in Listing 2.

Listing 2. Mapping uris to handler classes

urls = (

‘/’, ‘MyService’,

‘/users/(.*)’, ‘MyUsersService’,

‘/groups/(.*)’, ‘MyGroupsService’

)

Every request to a uri will generate a new instance of the class associated with it. Within the object, the application will search for a function with the same name as the request method (GET, POST, etc. ). This function must return a string containing the response body.

Twisted

Twisted is a full featured event driven networking engine. It provides, among many features, an HTTP Server. It is currently being used in many projects.

While being a very powerful networking and web framework, twisted may be intimidating due to the overly technical (or, sometimes, the lack of) documentation.

In twisted you must define a class inheriting Resource which will handle requests. A Resource is then associated with a Site. You may route different Resources associating them as children of a root resource. In Listing 3, you can seehow the same example presented in web.py looks in twisted.

Listing 3. Simple twisted example

from twisted.web import server, resource

from twisted.internet import reactor

class MyServiceResource(resource.Resource):

isLeaf = True

def render_GET(self, request):

request.setHeader(“content-type”, “text/plain”)

return “Hello {0}”.format(request.path[1:]) if __name__ == “__main__”:

factory = server.Site(MyServiceResource())

reactor.listenTCP(8080, factory)

reactor.run()

In the example above, all requests will return the string “Hello uri”, where uri will be replaced by whatever is sent in the url after the server name/port for any uri accessed.

Every request to a uri will use the same instance of the class associated with it. Within the object, the application will search for a function name consisting of render_ and the request method (render_GET, render_ POST, etc...). This function must return a string containing the response body.

isLeaf is a variable set to indicate end of resource call chain. Resources may be set as children of another resource using putChild.

To access a resource in the url /service or /custom you must setup a root resource and insert a child for each url. That is called resource nesting and it is presented in Listing 4.

Listing 4. Resource nesting with twisted if __name__ == “__main__”:

root = Resource()

root.putChild(“service”, MyServiceResource())

root.putChild(“custom”, MyCustomResource())

factory = server.Site(root)

reactor.listenTCP(8080, factory)

reactor.run()

SimpleHTTPServer

Originally built to serve files from a directory, simpleHTTPServer is an internal HTTP server normally distributed with python. It is a great tool for environments where you can’t add an extra package to the default python installation. It does not provide a networking interface, so we must wrap it using a SocketServer.