Showing posts with label webserver. Show all posts
Showing posts with label webserver. Show all posts

Wednesday, 28 January 2015

Read properties from configuration file in Python

It's always recommended to keep properties such as username, password, .. etc in .cfg files, instead of code. (Debate of appropriate/correct approach is out of context :) )

Let's say we have application configurations in a file "app.cfg". Contents of the "app.cfg" file:

[default]
host=abc.xyz.com
...
...

[mysql]
username=root
password=root
...

Let's look at the python code snippet to read the above application properties.

import ConfigParser

# class definition
class <class_name>:
    def __init__(self):
        ##### read properties
        config = ConfigParser.RawConfigParser()
        config.read(self.__file_path('app.cfg'))
        user = config.get('mysql', 'user')
        password = config.get('mysql', 'password')

# some other code funtionality
....


Tuesday, 27 January 2015

Python web server using Cherrypy

Recently, I came across a situation where I was supposed to use python to build a web service. At that time, I didn't even know the syntax of python language. Thanks to Cherrypy module, it's very easy and robust.

I will be showing here the code snippet to create a web service (restful api end point)

(I am not giving steps to install python or cherrypy module installation)

Create a file, say, helloworld.py and add below content.

# import cherrypy module
import cherrypy

# class definition
class HelloWorldService(object):
     # this annotation exposes the behavior
    @cherrypy.expose
    # status behavior definition
    def status(self):
        return"OK"

    @cherrypy.expose
    # sayhello behavior with path params

    def sayhello(selfi, *args):
        pathParam = args[0]
        msg = "Hello %s" %(pathParam)
        return msg

# define configuration
if __name__ == '__main__':
    conf = {
          '/' : {
                        'tools.response_headers.on': True,
                        'tools.response_headers.headers': [('Content-Type', 'application/json'), ('Server', '')]
           }
    }

webapp = HelloWorldService()
# starting the server, by default it run on port 8080, we can change this un-comment below line

# cherrypy.config.update({'server.socket_host': '0.0.0.0','server.socket_port': 8090,})
cherrypy.quickstart(webapp, '/', conf)

After this, start the server.
$ python helloworld.py

Once it starts, try accessing below url.
http://localhost:8080/status/
http://localhost:8080/sayhello/sateesh/