Posts

Showing posts with the label Python

Creating your first Docker image for Python project

Image
Docker is the modern way to share ready made machines , so other can use it without the usual hassles of configuration and environment setup. I wanted to try it myself first hand, to see what the fuss is about.  I want to share what I found, so you start your project right now.

Before we start, for the absolute beginners who ABSOLUTELY NO IDEA about DOCKER, let me try to explain what it is:

It is a CONTAINER which CONTAINS ALL that you NEED to run your project. 
Dockers are the new generation Virtual Machines which totally remove the need to install another files on a system just to run or test something . They are just CONTAINERS with all the things necessary for our app to work. That's it .

Advantages:
1) User need not worry about , what he needs to install for the project.
2) He doesn't need to know the steps for building the project.
3) He doesn't need to worry about the correct versions and their respective correct libraries that need to be installed.
4) Its can easily…

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…

Python List sorting with key argument explored

Everybody uses lists as an array to store values. List provide a lot of in-build features.SortingMembershipIndexingIterationreversingAdding/RemovingPoppingCount
Lots of reasons to use lists. I think, one of the most used features is sorting. Internally , python uses Merge sort technique to sort the array items. But the sort method can be used in many other ways to have more control.

The python help says:


>>> help(list.sort) Help on method_descriptor: sort(...) L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; cmp(x, y) ->-1, 0, 1

Things to note: The sort method doesn't return anything. It saves the changes in the list permanently. Thats why it is faster than the method sorted

SIMPLE SORT


>>> l = ['c', 'b', 'd', 'a'] >>> l.sort() >>> l ['a', 'b', 'c', 'd']
If elements are strings, they gets sorted by alphabetical order.

SORT IN REVERSE ORDER


>>> l =…