Tornado Web Server CORS

January 11th, 2016

To implement CORS (Cross -Origin Resource Sharing) in an Tornado Web Application, we must set the headers.

CORS is the standard used when you need access to resources, deployed in a domain, from other different domain. CORS allows web scripts to interact more openly with content outside of the original domain, leading to better integration between web services Check here.

BACKEND SERVICE

Service.py, is a service that return a JSON {"code" : 1, "name" : "David", timestamp : "2016-01-11 20:59:37.479657"}. The service is deployed in a Tornado Web Server in the Backend

Tornado Web Server publish the Resource in backend-domain.com/person

import tornado.ioloop
import tornado.web
from datetime import datetime
  
class BaseHandler(tornado.web.RequestHandler):
     def set_default_headers(self):
          self.set_header("Access-Control-Allow-Origin", "*")
          self.set_header("Access-Control-Allow-Methods", "GET,PUT,POST")
          self.set_header("Access-Control-Allow-Headers",
                            "Content-Type, Depth, User-Agent, X-File-Size, 
                             X-Requested-With, X-Requested-By, 
                             If-Modified-Since, X-File-Name, 
                             Cache-Control")

class PersonService(BaseHandler):
     def get(self):
          self.set_header('Content-Type','application/json')
          self.write('{"code" : "1", 
                       "name" : "David", 
                       "timestamp" : "'+str(datetime.now())+'"}')

if __name__ == '__main__':
     try:
          print("Start Service")
          app = tornado.web.Application([(r'/person',PersonService),])
          app.listen(8080)
          tornado.ioloop.IOLoop.instance().start()
     except KeyboardInterrupt:
          print("\nStop Service")

FRONTEND APPLICATION

You have a JQuery application in other Server (Your FrontEnd). You can invoke the service from otther domain, you can use Angular or JQuery, we use JQuery

$.ajax({
        type : "GET",
	url : "http://backend-domain.com/person",
	dataType : "json",
	success : function(data) {
			$("#code").html(data.code);
			$("#name").html(data.name);
			$("#timestamp").html(data.timestamp);
		}
	});

Apache Camel Routes

December 5th, 2015

This is an example of the functioning and utility of Apache Camel and Framework for the implementation of routes, automation and integration of technologies under a Service Oriented Architecture (SOA).

The example is the development of an automated process that consumes a REST API data with financial indicators. The process triggered by a timer every 12 hours, generating a JSON message with the name of the indicator and the current date; with these values the indicator value is rescued from the Internet (consuming a REST API), incorporating the retrieved value to the original message (the message enriches JSON) value, gives a format tweet (140 characters), publishes a tweet Twitter account (@ClDatos) and finally the message (resulting JSON) is stored in a NoSQL database (MongoDB).

The defined route, integrates several actors and components (and related technologies). On the way to enrich an original message, it consumes a Internet REST API (www.mindicador.cl), where the value of a financial indicator for the current date are consulted; after transforms the JSON in a tweet to be posted on twitter (@ClDatos account) and finally, the resulting JSON is stored in a database MongoDB.

To development of this route, we use:

To deploy the route (war) on the cloud, we use Openshift with Tomcat 7 (JBoss EWS 2.0) and MongoDB 2.4 cartridges.

See in riute un http://indicadores-devcon.rhcloud.com/

Finally, you can see the results on @ClDatos (the end of the route).

 

How develop and deploy an application in the cloud. A referencial architecture (Part 1)

February 10th, 2014

Link: https://github.com/rancavil/django-py3-openshift-quickstart/wiki/How-develop-and-deploy-an-application-in-the-cloud.-A-referencial-architecture-(Part-1).

See how we can implement an Architecture using the cloud services, Openshift Django / Python and Redis in the Cloud.

Python and MongoLab (Mongo in the Cloud)

January 19th, 2014

This is a little tutorial how use MongoDB on the Cloud.

First we need find Mongo in the cloud...I will use MongoLab for demonstrate how work pymongo.

We need to create a account on https://mongolab.com and complete the form https://mongolab.com/signup/

Follow the instructions to create a database and create a user on MongoLab web console.

To connect using a driver via the standard URI:

mongodb://<dbuser>:<dbpassword>@ds0<port>.mongolab.com:<port>/<database>

When you create a database on MongoLab a port is assigned to the resource.

For our example, we create a database called db_posts.

Assume that port 28012 is created

mongodb://<dbuser>:<dbpassword>@ds028012.mongolab.com:28012/db_posts

Important: you must create the dbuser (https://mongolab.com/databases/db_posts#users), this is not the user account.

Well, now we go to write the python code.

Create the create.py file to insert a document into the collection:

1  from pymongo import MongoClient
2
3  client = MongoClient('ds028012.mongolab.com:28012')
4  client.db.authenticate('joe','pass12345',source='db_posts')
5 
6  db = client.db_posts
7  posts = db.posts
8  post = {'author':'rodrigo','text':'Hello world'}
9
10 id_post = posts.insert(post)
11 print 'Create the id : %s'%id_post
12 
13 client.close()

Create the read.py file to retrieve documents from the collection:

1  from pymongo import MongoClient
2
3  client = MongoClient('ds028012.mongolab.com:28012')
4  client.db.authenticate('joe','pass12345',source='db_posts')
5 
6  db = client.db_posts
7
8  results_posts = db.posts.find()
9  for post in results_posts:
10     print post
11 
12 client.close()

I hope with this you can see how work python and mongo in the cloud, If you like MongoHQ, that is similar to use MongoLab.

Enjoy!!!

The Classic Hello World!!!

January 4th, 2012

We will develop the classic hello world!!! like a SOAP web service.

The purpose of this example is to explain how tornado-webservices works, with the use of the classic Hello World.

Note: For this example you must to use tornadows-0.9.3.2.

Step 1: Create a file named HelloService.py

1  import tornado.httpserver
2 import tornado.ioloop
3 from tornadows import soaphandler
4 from tornadows import webservices
5 from tornadows.soaphandler import webservice
6
7 class HelloWorldService(soaphandler.SoapHandler):
8 @webservice(_params=None,_returns=str)
9 def sayHello(self):
10 return 'Hello World!!!'
11
12 if __name__ == '__main__':
13 service = [('HelloService',HelloWorldService)]
14 app = webservices.WebService(service)
15 ws = tornado.httpserver.HTTPServer(app)
16 ws.listen(8080)
17 tornado.ioloop.IOLoop.instance().start()

First, the class HelloWorldService (lines 7 to 10) is the service that holds the operation or methods that contains the logical of the service.

With the decorator @webservice, indicates that the method sayHello () (lines 8 to 10) is the operation of the service.

In the line 13, service = [('HelloService','HelloWorldService')], indicates the name of the service that will be published on the net.

The tuple ('HelloWorld','HelloWorldService') associates the name of the service with the class of python. By this way the service can be accesed like:

http://localhost:8080/HelloService?wsdl

Finally, in  the line 16, indicates that we are listening from the port 8080.

Step 2: Running the service.

Simply execute:

$ python HelloService.py

Step 3: Testing with a client.

Now, I will created a client to HelloService with suds (0.3.7).

Create a file named ClientHelloService.py with this code:

1  import suds
2
3 url = 'http://localhost:8080/HelloService?wsdl'
4 client = suds.client.Client(url,cache=None)
5 print client.service.sayHello()

Note that we don't pass any parameters to the operation sayHello().

line 1: we import the api python-suds.

line3: indicates the url with the Web Service Description Language (WSDL), in other words, the location of web service.

line 4: is created the client of the web service.

line 5: finally, is printed the result. The result should be (of course): "Hello World!!!"

For running the client, simply execute:

$ python ClientHelloWorld.py

Hello World!!!

You can see more examples in:

https://github.com/rancavil/tornado-webservices/tree/master/demos

And documentation in:

https://github.com/rancavil/tornado-webservices/wiki

You can download directly from:

https://github.com/rancavil/tornado-webservices/downloads/tornadows-0.9.3.2.tar.gz

For check prerequisites and install see:

https://github.com/rancavil/tornado-webservices/wiki/Python-Web-Services-with-Tornado