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...

https://bugzilla.mozilla.org/query.cgi

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...

https://bugzilla.mozilla.org/rest/bug?product=Socorro&component=Backend&include_fields=status,id,resolution,summary

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

url='https://bugzilla.mozilla.org/rest/bug'
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
pd.DataFrame(bugs)

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']:
    documents.append({
        'url': 'https://bugzilla.mozilla.org/show_bug.cgi?id={}'.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
pd.DataFrame(documents)

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

https://gist.github.com/shantanuo/f9f4a595b7bee10e1f36

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'])}
    table.put_item(Item=item)   
    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...

https://t4pwupa9vc.execute-api.us-east-1.amazonaws.com/stag2/?mar=8&long=865&late=56

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...

https://aws.amazon.com/blogs/compute/using-amazon-api-gateway-as-a-proxy-for-dynamodb/

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)
    zipcontent= response.read()

    with open("/tmp/log.zip", 'w') as f:
        f.write(zipcontent)

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

https://12o3jwx4pi.execute-api.us-east-1.amazonaws.com/stag/?url=https://github.com/shantanuo/easyboto/archive/master.zip

https://12o3jwx4pi.execute-api.us-east-1.amazonaws.com/stag/?url=http://oksoft.blogspot.in/2016_01_01_archive.html

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.

https://aws.amazon.com/blogs/aws/new-cloudwatch-events-track-and-respond-to-changes-to-your-aws-resources/

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

ip install requests -t .

cat lambda_function.py

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

key = 'key-xxx'
sandbox = 'sandboxXXX.mailgun.org'
request_url = 'https://api.mailgun.net/v2/{0}/messages'.format(sandbox)

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

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

    request = requests.post(request_url, auth=('api', key), data={
        'from': 'xxx@gmail.com',
        'to': recipient,
        'subject': 'status alert',
        'text': myfile1
    })



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

zip -r myp.zip .

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

Template:
{
"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')
    myip=event['sourceip']+"/32"
    security_group.authorize_ingress(IpProtocol="tcp",CidrIp=myip,FromPort=80,ToPort=80)
    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

https://291w32lbja.execute-api.us-east-1.amazonaws.com/stag/mward?lat=19.1645972&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...

https://291w32lbja.execute-api.us-east-1.amazonaws.com/stag/mward?lat=18.92&lon=72.83

The python code can be found here...

https://gist.github.com/shantanuo/05187dd23b96f5e92f6b

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

Comparisons:
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:
basename
dirname
echo
expr
id
line
printf
sleep
test

Labels:


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: http://site.com/circle_info/InboundDetails.asmx/GetCallerDetails

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

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...
https://n10hs00rr8.execute-api.us-east-1.amazonaws.com/staging

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

https://x.execute-api.us-east-1.amazonaws.com/staging/getcircle?destination=1234567891

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.

Labels:


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...

https://mh9zd7l5ak.execute-api.us-east-1.amazonaws.com/staging/int-cal?amt=7692&i=18&nper=12

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):
    amt=int(event['amt'])
    i=int(event['i'])/100.0
    nper=int(event['nper'])
    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 shantanu.oak@gmail.com

https://t8hp2gl22l.execute-api.us-east-1.amazonaws.com/staging/sendmail?url=http://maharashtratimes.com&email=shantanu.oak@gmail.com

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 "lambda_function.py" and the main function will be "lambda_handler"
import requests
import urllib2
def lambda_handler(event, context):
    url = event['url']
    if event['email']:
        email=event['email']
    else:
        email='xxx@gmail.com'
    url1 = urllib2.unquote(url)
    myfile=urllib2.urlopen(url1)
    print requests.post("https://api.mailgun.net/v3/sandboxxxx.mailgun.org/messages",
                        auth=("api", "key-1234"),
                        files=[("attachment", myfile)
                               #("attachment", open("files/test.txt"))
                               ],
                        data={"from": "Excited User ",
                              "to": email,
                              #"cc": "YYY@yahoo.com",
                              #"bcc": "ZZZ@hotmail.com",
                              "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 = 'sandbox.mailgun.org'
    recipient = 'shantanu.oak@gmail.com'
    request_url = 'https://api.mailgun.net/v2/{0}/messages'.format(sandbox)
    request = requests.post(request_url, auth=('api', key), data={
        'from': 'shantanu.oak@gmail.com',
        'to': recipient,
        'subject': 'status alert',
        'text': 'done server status not ok at api.site.to:5000'
    })

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

import urllib, json

def lambda_handler(event, context):
url = "http://api.site.to:5000/site-server-status"
response = urllib.urlopen(url)
data = json.loads(response.read())

if data['responseMsg'] == 'Ok':
            return 'ok'
else:
   reportUser()
            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: ,


Archives

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   June 2017   July 2017   August 2017   September 2017   October 2017   November 2017  

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