Installing Flask and hosting a simple Flask app in Heroku PART 1

Install pip or easy_install to install python packages on ubuntu
FOR PIP

sudo apt-get install python-pip

or
FOR easy_install

sudo apt-get install python-setuptools

Install virtualenv
——————

sudo easy_install virtualenv
pip install virtualenv

After installing virtaulenv isuue this command

virtualenv flask

you will get a folder named flask change directory to this folder

cd flask

It contains a complete Python environment ready to be used for this project
Virtual environments can be activated and deactivated, if desired. An activated environment adds the location of its bin folder to the system path, so that for example, when you type python you get the environment’s version and not the system’s one.

Now install flask

flask/bin/pip install flask

Create a Heroku account and Install the Heroku tool belt

https://devcenter.heroku.com/articles/getting-started-with-python#introduction

touch run.py

and inserting the basic “Hello World” code

import os
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello World!'

Test your Flask install by running this webserver:

python run.py

You should see this in your terminal:
* Running on http://0.0.0.0:5000/

Screenshot from 2015-08-07 20:47:11

Now, navigate to localhost:5000 in your browser and make sure you can see “hello world” printed out in the browser window.

python static variable counter

How to implement a static variable counter inside a function using python?

import functools

def count_calls(func):
    @functools.wraps(func)
    def decor(*args, **kwargs):
        decor.count += 1
        return func(*args, **kwargs)
    decor.count = 0
    return decor
    
@count_calls
def Func_CALL():
	print Func_CALL.count

for i in range(10):
	Func_CALL()
	

So the counter will print the number of times the function Func_CALL() is called.

To count the numbers of instances a class being called we can use this method.

class Foo(object):
  counter = 0
  def __call__(self):
    Foo.counter += 1
    print Foo.counter

foo = Foo()

for i in range(10):
	foo()
		

Weekend Hack using python and CANMate

My weekend hack using our company’s(http://www.dthoughts.com) product CANMate (a high performance low cost CAN Analyzer) along with Python programming language.I wrote a python program to use CANMate in GNU/Linux and Windows which is freely vailable.I used Pythons Matplotlib library to plot the real time CAN message from a vehicle’s OBD port.

Happy Hacking 🙂

Plotting real-time data from Arduino using Python

The below Arduino sketch reads the values from analog pins A0 and A1 and prints it to the serial port.
This is the code

void setup()
{
  Serial.begin(9600); 
}

void loop()
{
  // read A0
  int val1 = analogRead(0);
  // read A1
  int val2 = analogRead(1);
  // print to serial
  Serial.print(val1);
  Serial.print(" ");
  Serial.print(val2);
  Serial.print("\n");
  // wait 
  delay(50);
}

The serial port sends values in this format

Screenshot--dev-ttyUSB5

Using python and Matplotlib am plotting this data as a function of time.I wanted to display this as a scrolling graph that moves to the right as data keeps coming in. For that, I am using the Python deque class to keep and update a fixed number of data points for each time frame.

import sys, serial
import numpy as np
from time import sleep
from collections import deque
from matplotlib import pyplot as plt

# class that holds analog data for N samples
class AnalogData:
  # constr
  def __init__(self, maxLen):
    self.ax = deque([0.0]*maxLen)
    self.ay = deque([0.0]*maxLen)
    self.maxLen = maxLen

  # ring buffer
  def addToBuf(self, buf, val):
    if len(buf) < self.maxLen:
      buf.append(val)
    else:
      buf.pop()
      buf.appendleft(val)

  # add data
  def add(self, data):
    assert(len(data) == 2)
    self.addToBuf(self.ax, data[0])
    self.addToBuf(self.ay, data[1])
    
# plot class
class AnalogPlot:
  # constr
  def __init__(self, analogData):
    # set plot to animated
    plt.ion() 
    self.axline, = plt.plot(analogData.ax)
    self.ayline, = plt.plot(analogData.ay)
    plt.ylim([0, 1023])

  # update plot
  def update(self, analogData):
    self.axline.set_ydata(analogData.ax)
    self.ayline.set_ydata(analogData.ay)
    plt.draw()

# main() function
def main():
  # expects 1 arg - serial port string
  if(len(sys.argv) != 2):
    print 'Example usage: python showdata.py "/dev/tty.usbmodem411"'
    exit(1)

 #strPort = '/dev/tty.usbserial-A7006Yqh'
  strPort = sys.argv[1];

  # plot parameters
  analogData = AnalogData(100)
  analogPlot = AnalogPlot(analogData)

  print 'plotting data...'

  # open serial port
  ser = serial.Serial(strPort, 9600)
  while True:
    try:
      line = ser.readline()
      data = [float(val) for val in line.split()]
      #print data
      if(len(data) == 2):
        analogData.add(data)
        analogPlot.update(analogData)
    except KeyboardInterrupt:
      print 'exiting'
      break
  # close serial
  ser.flush()
  ser.close()

# call main
if __name__ == '__main__':
  main()

The program must be run in this format

python showdata.py /dev/ttyUSB5

Instead of ttyUSB5 add your ttyUSB device.And this is how the plot looks like.

Screenshot-Figure 1

Happy Hacking 🙂

How to add a python program to run on startup the cli way

To make a python program run on startup..first create o file on /etc/init.d..am creating a file named timestamp.

touch /etc/init.d/timestamp

Now edit the file

vim  /etc/init.d/timestamp

and enter the following

#! /bin/bash
# Copyright (c) 1996-2012 My Company.
# All rights reserved.
#
# Author: Ganesh H, 2013
#
# Please send feedback to ganeshredcobra@gmail.com
#
# /etc/init.d/timestamp
#
### BEGIN INIT INFO
# Provides: timestamp
# Required-Start: 
# Should-Start: 
# Required-Stop: 
# Should-Stop:
# Default-Start:  2 3 4 5
# Default-Stop:   0 1 6
# Short-Description: Test daemon process
# Description:    Runs up the test daemon process
### END INIT INFO

# Activate the python virtual environment
#    . /path_to_virtualenv/activate

case "$1" in
  start)
    echo "Starting server"
    # Start the daemon 
    /usr/bin/python /home/ganesh/Pictures/timestamp.py start
    ;;
  stop)
    echo "Stopping server"
    # Stop the daemon
    /usr/bin/python /home/ganesh/Pictures/timestamp.py stop
    ;;
  restart)
    echo "Restarting server"
    /usr/bin/python /home/ganesh/Pictures/timestamp.py restart
    ;;
  *)
    # Refuse to do other stuff
    echo "Usage: /etc/init.d/timestamph {start|stop|restart}"
    exit 1
    ;;
esac

exit 0

give the correct path of the file..Now make the init.d file executable

chmod +x /etc/init.d/timestamp

Now add the script to bootup

sudo update-rc.d timestamp  defaults

or you can use chkconfig

chkconfig --add timestamp

To remove the startup

rm -fv /etc/rc*/*timestamp

or

chkconfig --del timestamp

To view all configured startup use the below command

chkconfig --list

Happy Hacking 🙂

How to make a python program run as daemon

To make a python program run as daemon process use the following program..

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
#       Copyright 2013 ganesh #ganeshredcobra@gmail.com#
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

from os import fork, chdir, setsid, umask
from sys import exit
import serial,os
import time
import syslog


def main():
    port = "/dev/ttyUSB0"
    ser = serial.Serial(port, 9600, timeout=0)
    last_received = ''
    buffer = ''
    while 1:
        #main daemon process loop
        

# Dual fork hack to make process run as a daemon
if __name__ == "__main__":
      try:
        pid = fork()
        if pid > 0:
          exit(0)
      except OSError, e:
        exit(1)

      chdir("/")
      setsid()
      umask(0)

      try:
        pid = fork()
        if pid > 0:
          exit(0)
      except OSError, e:
        exit(1)
main()
Put the program you want to daemonize inside the main function…now just run the program the process in main function will become daemon process..
to test the above program modify main function like this
def main():
     syslog.syslog('event occured')
     time.sleep(10)
Now run the program it becomes daemon and to check that
sudo tail -f  /var/log/syslog
you can see it will print “event occured” every ten seconds…
Happy hacking 🙂

SimpleHTTPServer using python

Python provides a simple http server so that you can share a specific folder on your network..Navigate tho the directory which you want to share using cd command… Now type this command in the terminal

python -m SimpleHTTPServer 7000

The command is case sensitive…no the content of the folder can be accessed by the entire network through web browser by typing by typing

http://<ip address of your machine>:<portnumber>  where port number is the 7000 we entered in command we can change the port number….