Posts

Showing posts with the label Python

A better example of Class Inheritance in Python

Lots of people ask me, why should they use classes at all ? Well. I think its about control, and ease . It solves the headache of data sharing and accessibility. I am going to show you an example , which hopefully proves that classes and fundamentals like inheritance  are brilliant.

Example:

I have  two classes in the below program. Person and Manager . Manager has inherited the Person class (because he is a person too....almost (lol)) .


class Person: def __init__(self, name, job, pay=0): self.name = name self.job = job self.pay = pay def lastName(self): return self.name.split()[-1] def giveRaise(self, percent): self.pay = int(self.pay * (1 + float(percent)/100)) def __str__(self): return'[Person: %s, %s]' % (self.name, self.pay) class Manager(Person): def giveRaise(self, percent): self.pay = int(self.pay * (1 + ((float(percent)+10)/100)))
The only diff between a Manager is , he gets an extra 10% h…

How to run a Python program over the internet?

Image
What am I trying to solve? I want to run a python program whenever I need and get some information out of it. The problem is, I want to call that through internet. And I want to show the content on a web page or some UI container. That's it. Let put this as a requirement.Problem: Display some information on my web page calculated by a python program. 
How do we do it on our local computer? We run our program as : python my_program.py .So may be I can do something like: www.mywebsite.com/my_program.py . Can we? No idea.

I expect to collect the response in some variable (no idea how can I create a variable in the first place on html) and then display the contents of this variable . Displaying a simple text on html is known , so that should be easy.


The program You must remember that we want some information from our program . It's a basic GET call where you just ask for some information from a server. You may or may not pass some inputs while doing this.

fromflaskimportFlaskfromflas…

Numpy...why so serious?

What can we really do with Numpy? Why should we use it at all ?

Start with : import numpy

1. We can create arrays .
method: numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)


>>> a = numpy.array(range(10)) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> a.dtype dtype('int32')
In the above array, there are 10 columns and 1 row.

Note : The concept of rows and columns applies when you have a 2D array. However, the array numpy.array([1,2,3,4]) is a 1D array and so has only one dimension, therefore shape rightly returns a single valued iterable.

Refer this link

2. We can create/convert array of a particular type (immediate conversion of your list to a desired type)

>>> s = numpy.array(range(10), dtype=str) >>> s array(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], dtype='|S1')-------------------------------…

Test server that accepts GET/POST calls using Python Flask

I was trying out Flask. In the process, I made a website that behaves like a server. It can help you test GET and POST calls.

It goes like this .


fromflaskimport Flask, request app = Flask(__name__) @app.route('/method', methods=['GET', 'POST']) @app.route('/method/<wish>', methods=['GET', 'POST']) defmethod_used(wish=None): if request.method =='GET': if wish: if wish indir(request): ans =None s ="ans = str(request.%s)"% wish exec s return ans else: return'This wish is not available. The following are the available wishes: %s'% [method for method indir(request) if'_'notin method] else: return'This is just a GET method'else: return"You are using POST"
When I run this, this…

How to test POST call using Python?

I got into a situation recently where I needed to test if my POST function was indeed working.

Its easy to test GET method . You just visit the URL and that's it . But for POST, you an use PlugIns.

But unfortunately I can't do that , because my browser (admin restrictions ) doesn't allow me to install plugins . Fortunately if you have Python , you can easily do that .

The request module is a handy module when it comes to testing web responses etc. It also has support for POST methods. You can literally fill a form using this . Let's test our url .

This is our POST method. (It is a Flask code).


@app.route('/method',methods=['GET','POST'])defmethod_used():ifrequest.method=='GET':return"Method used: %s"%request.methodelse:return"You are using POST"
So if its a GET method, the response we expect is Method used: GET . And if its a POST method, we expect "You are using POST"

Now lets bring out the request module. I have …

Something about Python Argparse

Its been decades I have been using sys.argv for simple tasks related to argument parsing. But the thing is, sometimes we don't realize how good something is unless we use it . Like the argparse module.

The official document got me totally confused. So I wrote my own tutorial. Let's get started.

So the module to be imported is 'argparse'. First thing to do is , create a parser object.


parser = argparse.ArgumentParser()
Then we can add what arguments we want . These are the requirements.
I want a username. I also want to set a default.  If nothing is provided, then the default user will be used. If User name is provided , then that should be used. We should tell the user about this requirement through some kind of help instruction.
parser.add_argument("-user",default='Admin')
So to pass a username, one needs to use the '-user' option. 

args=parser.parse_args()
Then we need to call the above. This will create a namespace.


>>>argsNamespace(u…

Writing context managers using Python

We use. We forget. This is for myself so I remember the magic called Context Manager. You already must have used the "with statement" for file handling, threads, socket and other operations. I am going to talk about creating you OWN context managers.

The magic operator to be used is : @contextmanager. It can be imported from the module "contextlib"

To create a context manager, use the decorator contextlib.contextmanager


@contextlib.contextmanagerdefgetListCounts(x): try: fromcollectionsimport Counter yield Counter(x) finally: print'No of elements in the list : %d' % len(x)

Let's now use the above context manager 

Example 1:
>>> with getListCount([10, 10, 12]) as c: print "Element occurring the most is %d" % c.most_common()[0][0] Element occurring the most is 10 No of elements in the list : 3
Example 2:
>>> with getListCount([10, 10, 12]) as c: print "Element occurring the least is %d"…

Python: Super class examples

Hi all. We are going to see some examples of usage of keyword 'super' here . 
Below code shows two classes Employee and Developer. A parent and a child.


classEmployee(object):def__init__(self,first,last):self.first=firstself.last=lastprint'Employee: {0}, {1}'.format(first,last)defhike_category(self):hike=0ifself.grade=='A':hike=(0.1*self.pay)+self.pay#percentelifself.grade=='B':hike=(0.15*self.pay)+self.pay#percentelifself.grade=='C':hike=(0.20*self.pay)+self.pay#percentreturn'{0},{1} gets {2}'.format(self.first,self.last,hike)classDeveloper(Employee):def__init__(self,fname,lname,grade,pay):super(Developer,self).__init__(fname,lname)self.grade=gradeself.pay=pay
Lets run the above program.

Results:

>>> d = Developer('arc', 'roy', 'C', 10000) Employee: arc, roy >>> d.hike_category() 'arc,roy gets 12000.0'
Observations and things to note
Above programming is done in Python 2.7. In 2.7, the class …

Quick guide to Logging in different files using Python

This is for quick setup of a file logging system 
Step 1: importing the logging module.

import logging

Step 2: Create a logger for yourself. 
logger = logging.getLogger(__name__)

Step 3: Set Logger level
logger.setLevel(logging.DEBUG)

Step 4: Create a handler. 

hdlr = logging.FileHandler(settings.BASE_LOG_FILE, mode='w')

Step 5: Create a formatter

formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')

Step 6: Set formatter and handler

>>> hdlr.setFormatter(formatter) >>> logger.addHandler(hdlr)