Day 25: cooperate with tornado, mongodb and angularjs for application development


Editor’s note: we have found an interesting series of articles “30 days to learn 30 new technologies”, which are being translated, updated one by one, year-end gift package. Here’s day 23.

In today’s 30 days of learning 30 new technologies, I decided to put aside the content of JavaScript for a while and learn a web framework called tornado. The reason I decided to learn tornado was that I could write web programs in Python. I only learned about the flask framework, so I think tornado should be able to increase my knowledge of Python web development. The application described in this blog uses tornado as the rest backend, mongodb as the database, angularjs as the JavaScript MVC framework on the client side, and openshift as the deployment platform.
Day 25: cooperate with tornado, mongodb and angularjs for application development

What is tornado?

Tornado is an open-source Python web framework, a non blocking web server. It was first developed in FriendFeed. After FriendFeed was acquired, Facebook maintained and continued to develop tornado. Because of its non blocking network I / O characteristics, it has excellent scalability and can support more than 1000 connections at the same time.

Application case

In this post, we will develop a social bookmarking application that allows users to post and share links. You can see the real application running on openshift here. This is the application we developed on day 22, so you can refer to that blog post to better understand this application case.

GitHub warehouse

The code for this demo application can be found on GitHub today: day25 tornado demo app.

preparation in advance

Before we start tornado, we need to install Python and virtualenv on the machine. In this post, I use Python version 2.7

This application uses mongodb as the data storage software, so please download the latest mongodb distribution corresponding to your operating system.

Development of tornado mongodb application

We will usepipInstall tornado. For those unfamiliarpipIn factpipIs a python package manager. We can install it from the official websitepip。 Open the terminal, go to any convenient directory on the file system, and then run the following command:

$ mkdir getbookmarks
$ cd getbookmarks
$ virtualenv venv --python=python2.7
$ . venv/bin/activate
$ pip install tornado
$ pip install pymongo

The above command will create a getbookmarks directory on the local machine, activate virtualenv in Python 2.7, install the tornado package, and finally install pymongo. Among them, pymongo is the python driver of the official mongodb; we will use it to write stories to mongodb.

In the getbookmarks directory, create a file named

$ touch

Copy the following code and paste it into the source file of

import os
from tornado import ioloop,web
from pymongo import MongoClient
import json
from bson import json_util
from bson.objectid import ObjectId

class IndexHandler(web.RequestHandler):
    def get(self):
        self.write("Hello World!!")

settings = {
    "template_path": os.path.join(os.path.dirname(__file__), "templates"),
    "static_path": os.path.join(os.path.dirname(__file__), "static"),
    "debug" : True

application = web.Application([
    (r'/', IndexHandler),
    (r'/index', IndexHandler),

if __name__ == "__main__":

The above code does the following:
1. We start from importing the required library;
2. Next, we define a new class of extension class web.requesthandler: indexhandler. A tornado web application will map URLs or URL patterns to the subclass of web.requesthandler. These classes defineget()post()Wait for the method to process the HTTP get or post request to access the URL. When a get request is received under the address’ / ‘, the indexhandler returns a “Hello world!!”
3. Then we define some application settings.template_pathSetting is to tell tornado app totemplateDirectory to find application templates.static_pathSettings tell app to usestaticStatic files such as CSS, image and JavaScript files in the directory. By settingdebugbyTrue, after you make changes to the project, it will be automatically overloaded without restarting to see the effect. We will keep the debugger running in the background during application development. This can provide an efficient development environment.
4. Next, we create a tornado application instance, and route routes) andsettingsPass it on.
5. Finally, we usepython getbookmarks.pyCommand the startup server to run the application

Open http: / / localhost: 8888 and http: / / localhost: 8888 / index to see if you see “Hello world!!”

Configure mongodb

After importing the library, add the following statement:

MONGODB_DB_URL = os.environ.get('OPENSHIFT_MONGODB_DB_URL') if os.environ.get('OPENSHIFT_MONGODB_DB_URL') else 'mongodb://localhost:27017/'
MONGODB_DB_NAME = os.environ.get('OPENSHIFT_APP_NAME') if os.environ.get('OPENSHIFT_APP_NAME') else 'getbookmarks'

client = MongoClient(MONGODB_DB_URL)
db = client[MONGODB_DB_NAME]

We defined the route of mongodb connection and the name of the database. If the application is deployed to openshift, the openshift specific environment variables will be used first. If not, the configuration on the local machine will be used.

We created a mongoclient instance and passed in the route of the connection. This connection route is a mongod instance that only wants to run. Then we use the mongoclient instance to use the database

Create and list all stories

Now we’re going to add the ability to create new stories and list all of them. First, we add the route to the following application examples:

application = web.Application([
    (r'/', IndexHandler),
    (r'/index', IndexHandler),

Next, we define a story handler that stores stories in mongodb and finds all stories in it:

class StoriesHandler(web.RequestHandler):
    def get(self):
        stories = db.stories.find()
        self.set_header("Content-Type", "application/json")

    def post(self):
        story_data = json.loads(self.request.body)
        story_id = db.stories.insert(story_data)
        print('story created with id ' + str(story_id))
        self.set_header("Content-Type", "application/json")

In the above code:
1. When a user sends a get request to/api/v1/storiesWe will issue a find () method request to mongodb. Since we don’t specifically declare any query, it will retrieve all the stories from mongodb. We set the content type toapplication/json, and then dump the JSON response.
2. When the user sends a post request to/api/v1/stories, and then we first decode the content of JSON to a dictionary, and then write the data to mongodb. We will set the response status to 201 (created).

View individual stories

The last back-end function is to view a separate story. Let’s first point out the route:

application = web.Application([
    (r'/', IndexHandler),
    (r'/index', IndexHandler),
    (r'/api/v1/stories/(.*)', StoryHandler)

We write story handler

class StoryHandler(web.RequestHandler):
    def get(self , story_id):
        story = db.stories.find_one({"_id":ObjectId(str(story_id))})
        self.set_header("Content-Type", "application/json")

Find the corresponding code abovestory_idAnd then turn out the JSON response.

Angualarjs front end

I decided to reuse the front end that I wrote on day 22. Day 22 shows how to use angularjs with the Java spring framework as the back end. The best place to use the JavaScript MVC architecture is that you can reuse the front-end code if your application meets the requirements of the rest interface client. You can read more about day 22.

You can download the angularjs front end in my gihub repository. Copy the static file and template folder and paste it into the folder where is located.

Deploy application to openshift

Before building the application, we need to make some settings:

  1. Sign up for an openshift account. Registration is completely free. Red hat gives each user three free gears to run your app with. At the time of writing, each user can use a total of 1.5 GB of memory and 3 GB of hard disk space for free.

  2. Install the RHC client tools.rhcIt’s Ruby gem, so you need to have ruby 1.8.7 or higher on your machine. Just inputsudo gem install rhcRHC can be installed. If you have already installed it, make sure it is the latest version. Functionsudo gem update rhcUpgrade. For more information about configuring the RHC command-line tools, see:

  3. Use RHC’s setup command to configure your openshift account. This command will help you create a namespace and upload your SSH public key to the openshift server.

Deployment application

You can deploy the application to openshift by entering the following command:

$ rhc create-app day25demo python-2.7 mongodb-2 --from-code

This command will create the application, set the public DNS, create a private git repository, and finally deploy the application using the code in your GitHub repository. The application can be accessed at # /.

That’s it today. Welcome to feedback.

Day 25: Tornado — combining tornado, mongodb, and angularjs to build an app
Translate segmentfault