Shantanu's Blog

Corporate Consultant

January 30, 2016


Scrapping structured data using python

It is very difficult to find a bug if we are using bugzilla. For e.g. visit this page...

Choose "ALL" in status and "Socorro" in Product to search for a bug. The bug database is also accessible using API and the URL will look something like this...,id,resolution,summary

We can programatically access this page using 4 lines of python code:

params={'product': u'Socorro', 'component': u'Backend', 'include_fields': 'status,id,resolution,summary'}

import requests
bugs=requests.get(url, params=params).json()

Let's try to add this bugs list to pandas dataframe.

import pandas as pd

This will create a row for each bug, but all the fields are merged into one. We need separate column for each one like status, id, title so that we can manage, sort and export data.

documents = []
for bug in bugs['bugs']:
        'url': '{}'.format(bug['id']),
        'title': bug['summary'],
        'id': bug['id'],
        'status': bug['status'],
        'popularity': bug['id'],
        'group': 'Socorro',
        'resolution': bug['resolution']

We created a list of dictionaries called documents. This object can be imported in pandas without any problem.

import pandas as pd

Once we have all the data, it can be easily exported to another service as shown here...

Labels: , ,

January 28, 2016


Adding a record to dynamoDB using API

Lambda Function:

import boto3

client = boto3.resource('dynamodb')
table = client.Table('minfo')

def lambda_handler(event, context):
    item = {
        'marker': int(event['mar']),
        'latitude': str(event['late']),
        'longitude': str(event['long'])}
    return event['mar']

Link the above lambda function name for e.g. "dyno" to the API gateway.
It is important to correctly specify the mapping for API get method execution request:

"mar": "$input.params('mar')",
"late": "$input.params('late')",
"long": "$input.params('long')"

Once deployed, the URL will look something like this...

The latitude and longitude are saved to dynamoDB database with key as "mar".
Python code is short (10 lines) and readable. Creating API gateway takes a few minutes and the cost is minimum.

This can also be achieved by using the instructions found here...

Labels: , , ,

January 23, 2016


Upload a file to S3

This lambda code will copy the given URL to S3

import boto3
import os
import urllib2

bucket = 'billingac'

s3 = boto3.resource('s3')
s3_client = boto3.client('s3')

def lambda_handler(event, context):
    url = event['url']
    key = os.path.basename(url)
    response = urllib2.urlopen(url)

    with open("/tmp/", 'w') as f:

    s3_client.upload_file('/tmp/', bucket, key)
We can link this function to API gateway so that we can access it from the browser something like this...

Labels: ,

January 22, 2016


email notification about ec2 instance activity

There are times when you need an email alert when-ever an instance is initiated or terminated from your account. There is an excellent blog post about how to do it.

Based on that post, I have written a python script that should be called which should be uploaded to lambda along with requests module.

ip install requests -t .


import logging
logger = logging.getLogger()
import requests
import json

key = 'key-xxx'
sandbox = ''
request_url = '{0}/messages'.format(sandbox)

def lambda_handler(event, context):'got event{}'.format(event))

    myfile = '{}'.format(event)
    import ast
    myfile2 = ast.literal_eval(myfile)
    myfile1=json.dumps(myfile2, indent=4, sort_keys=True)

    request =, auth=('api', key), data={
        'from': '',
        'to': recipient,
        'subject': 'status alert',
        'text': myfile1

Compress all the files along with sub-directories and then upload it to lambda.

zip -r .

It has been explained in the blog post about how to create an event.

Labels: ,

January 20, 2016


Lambda function to open port

I can create an API that will take the current IP of requesting client and add that IP address to a security group to open up certain ports.

Integration request:
content-type: application/json

"sourceip": "$context.identity.sourceIp"

The lambda function will look something like this...

def lambda_handler(event, context):
    from boto3.session import Session
    session = Session(aws_access_key_id='XXX', aws_secret_access_key='YYY')
    ec2 = session.resource('ec2')
    security_group = ec2.SecurityGroup('sg-f682c78f')
    return (event['sourceip'])

Labels: , , , ,

January 18, 2016


Mumbai ward API

Here is an API that will return the Mumbai Municipal ward name for a given location. For e.g. if you want to find in which ward does lat=19.1645972 and lon=72.8496286

The above page will correctly return P/S (p south ward). If you provide Nariman Point co-ordinates in the URL then it will return "A" ward as shown below...

The python code can be found here...

Labels: ,

January 17, 2016


Overview of Unix commands

Here is an incomplete list of commands admins must be using frequently.

common commands:
cd, cp, file, cat, head, less more, tail, locate, ls, mkdir, mv, pwd, rm, rmdir, scp, ssh, wc, split, md5sum, date, man, clear, nice, nohup, passwd, screen, script, spell, su, find, grep (egrep, fgrep), strings, tar, gzip, gunzip, bzip2, bunzip2, cpio, zcat (gzcat), crontab,df, du, env, kill, ps, who, awk, sed, grep,  cut, join, paste, sort, tr, uniq, vi, xargs , iconv, parallel

Example commands:
ln -s /tmp/mysql.sock /var/lib/mysql/mysqld.sock
chown mysql:mysql /var/lib/mysql/
chmod 700 nov15a.pem

cmp Compare two files, byte by byte
comm COmpare items in two sorted files
diff compare two files, line by line
dircmp compare directories
sdiff Compare two files, side by side

Shell Programming:


January 10, 2016


Building cloud API on top of your own in-house API

You can create Amazon Cloud API that will simply redirect to your own API hosted on your server.

1) Choose "Create API" link from API Gateway homepage. The "API name" can be something like circle_data.

2) Click on Create Resouce to add a URL resource for e.g. "getcircle"

3) Select the circle Resource and choose Create Method: GET

4) Select GET method and choose "HTTP Proxy" in Integration type. The endpoint URL will be your own server API. for e.g.

Endpoint URL:

5) Select GET method created in the last step and choose Method Request:
URL Query String Parameters:  Add Query string:

6) Select GET method again and then choose Integration Requst:
URL Query String Parameters: Add query string:
Name: destination
mapped from: method.request.querystring.destination

7) Click on Deploy API button:
Add a name for e.g. staging and save.

8) You will get Invoke URL something like this...

After adding resource and query string (like circle?destination=1234567890) the final URL will look something like this...

The advantage of building a cloud API on top of current in-house API are:

1) Security: You can hide your own URL and publish the Amazon URL
2) Amazon Provides API Cache so the requests are faster.
3) CloudWatch setting allows us to save request - response info that can help to debug and troubleshoot problems. It will also help us to log who is accessing data and from where.
4) Throttling settings allow us to manage high load.


January 09, 2016


EMI Calculator

Here is an example how you can build simple hosted API services for anyone (free!)  Let's assume you need to calculate the Equal Monthly Installment for a given loan amount. The user will send the amount, rate of interest and tenure in months. You should get back the monthly installment that the financial institution should charge. For e.g. if you pass the amount 7692 followed by interest rate 18% and repayment period of 12 months, you should get back 705.2 as shown here...

We are using 2 services provided by Amazon.
1) API Gateway - This will generate a dynamic URL that will have the get method with all 3 variables.
2) Lambda - Python code that will actually do all the calculation.

1) API Gateway:
a) Method Execution - Get Method Request - URL Query String Parameters - add 3 variables i, amt and nper
b) Method Execution - Get Integration Request - Mapping Templates - Content-Type - application/json - Mapping template

"amt": "$input.params('amt')",
"i": "$input.params('i')",
"nper": "$input.params('nper')"

The above will link the variables received from the API gateway to the lambda function event dictionary.

2) Lambda function:
def lambda_handler(event, context):
    i = i/12  
    i1 = i + 1  
    return round(amt*i1**nper*i/(i1**nper-1),2)

Since this function is only 7 lines and there are no external dependencies, we can directly copy - paste this function code. In other cases, you will beed to upload a zip file.

Labels: ,


send web contents

Here is a web service that will email the contents of the website. For e.g. I want the contents of webpage maharashtra times to be sent to

The API gateway Mapping template in this case will look something like this...

"url": "$input.params('url')",
"email": "$input.params('email')"

The lambda function code needs "requests" module. We can embed that module using the following command...

pip install requests -t /path/to/python_code/

The filename should be named "" and the main function will be "lambda_handler"
import requests
import urllib2
def lambda_handler(event, context):
    url = event['url']
    if event['email']:
    url1 = urllib2.unquote(url)
                        auth=("api", "key-1234"),
                        files=[("attachment", myfile)
                               #("attachment", open("files/test.txt"))
                        data={"from": "Excited User ",
                              "to": email,
                              #"cc": "",
                              #"bcc": "",
                              "subject": "Hello",
                              "text": "Testing some awesomness with attachments!",
                              "html": myfile})

You may need to increase the default timeout from 3 seconds to 1 minute because some sites may be slow and take more time to process. This can be done using Configuration - Advance Settings - Timeout. You can also increase the memory allocated to this function.

Labels: ,


Check and alert site status

This is a simple AWS Lambda function that will check a website for it's content. If the dictionary response is not "Ok" then it will send an alert mail to the user.

def reportUser():
    import requests
    key = 'key-1234'
    sandbox = ''
    recipient = ''
    request_url = '{0}/messages'.format(sandbox)
    request =, auth=('api', key), data={
        'from': '',
        'to': recipient,
        'subject': 'status alert',
        'text': 'done server status not ok at'

    print 'Status: {0}'.format(request.status_code)
    print 'Body:   {0}'.format(request.text)

import urllib, json

def lambda_handler(event, context):
url = ""
response = urllib.urlopen(url)
data = json.loads(

if data['responseMsg'] == 'Ok':
            return 'ok'
            return 'error'

Since this function is using "requests" module to send mails, we will need to embed that module as well in a zip file and upload the code to lambda. This lambda function should be called every 5 minutes just like cron. There is an option in "Event sources" to configure just that.

We do not need to use API gateway in this case because this is like cron application.

Labels: ,


June 2001   July 2001   January 2003   May 2003   September 2003   October 2003   December 2003   January 2004   February 2004   March 2004   April 2004   May 2004   June 2004   July 2004   August 2004   September 2004   October 2004   November 2004   December 2004   January 2005   February 2005   March 2005   April 2005   May 2005   June 2005   July 2005   August 2005   September 2005   October 2005   November 2005   December 2005   January 2006   February 2006   March 2006   April 2006   May 2006   June 2006   July 2006   August 2006   September 2006   October 2006   November 2006   December 2006   January 2007   February 2007   March 2007   April 2007   June 2007   July 2007   August 2007   September 2007   October 2007   November 2007   December 2007   January 2008   February 2008   March 2008   April 2008   July 2008   August 2008   September 2008   October 2008   November 2008   December 2008   January 2009   February 2009   March 2009   April 2009   May 2009   June 2009   July 2009   August 2009   September 2009   October 2009   November 2009   December 2009   January 2010   February 2010   March 2010   April 2010   May 2010   June 2010   July 2010   August 2010   September 2010   October 2010   November 2010   December 2010   January 2011   February 2011   March 2011   April 2011   May 2011   June 2011   July 2011   August 2011   September 2011   October 2011   November 2011   December 2011   January 2012   February 2012   March 2012   April 2012   May 2012   June 2012   July 2012   August 2012   October 2012   November 2012   December 2012   January 2013   February 2013   March 2013   April 2013   May 2013   June 2013   July 2013   September 2013   October 2013   January 2014   March 2014   April 2014   May 2014   July 2014   August 2014   September 2014   October 2014   November 2014   December 2014   January 2015   February 2015   March 2015   April 2015   May 2015   June 2015   July 2015   August 2015   September 2015   January 2016   February 2016   March 2016   April 2016   May 2016   June 2016   July 2016   August 2016   September 2016   October 2016   November 2016   December 2016   January 2017   February 2017   April 2017   May 2017  

This page is powered by Blogger. Isn't yours?