Monday, October 23, 2017

Parsing configuration files using ConfigParser in Python

ConfigParser is used to parse configuration file easily in python. A configuration file  can be grouped by  sections with [section] header,  and entries can be added as in name: value  order.

Eg: settings.cfg

[LogSettings]
filepath='/Users/ratha/Desktop/Twisted.log'

[CustomerSettings]
customer1='/Users/ratha/Desktop/customer1'
customer2='/Users/ratha/Desktop/customer2'


In python;

import ConfigParser

  def loadSettings(self):
        config = ConfigParser.ConfigParser()
        config.read('./config/settings.cfg')  
      
        if config.has_section('CustomerSettings'):
            if len(config.options('CustomerSettings')) >0:
                for key,value in config.items('CustomerSettings'):
                    print value

        if config.has_section('LogSettings') :
            if len(config.options('LogSettings')) >0:            
                filepath = config.get('LogSettings', config.options('LogSettings')[0])
               
                print filepath  

Overcoming "No 'Access-Control-Allow-Origin' header is present on the requested resource." in jQuery

When calling a backend service via cross domain, if we do not set CORS header we will get above javascript error in browsers.
To overcome this issue in jQuery, we can set headers parameter.

eg:
$.ajax({
type : 'GET',
url : http://abc.com,
headers : {
'Access-Control-Allow-Origin' : '*'
},
success : function(data, textStatus) {
alert('success');
},
error : function(xhr, textStatus, errorThrown) {
alert('error');
}
});
At the same time, server too needs to allow cross domain requests to be served.

We can set request headers at server side..

Eg:
  request.setHeader('Access-Control-Allow-Origin', '*') 
  request.setHeader('Access-Control-Allow-Methods', 'GET')
  request.setHeader('Access-Control-Allow-Headers', 'x-prototype-version,x-requested-with')