Advanced Python Training at VMWare - Day 2

Apr 02-04, 2018 Vikrant Patil

These notes are available online at http://notes.pipal.in/2018/vmware-advanced-apr

© Pipal Academy LLP

Day 1 | Day 2 | Day 3

Python distribution

We will be using anaconda (python 3) distribution for this training. it can be downloaded from

https://www.anaconda.com/download/

In [5]:
class A:
    pass

class B(A):
    pass

class C:
    pass

class D(A,C):
    pass

#class E(A,B):
#   pass
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-14d8d145d07e> in <module>()
     11     pass
     12 
---> 13 class E(A,B):
     14     pass

TypeError: Cannot create a consistent method resolution
order (MRO) for bases A, B
In [10]:
D.__module__
Out[10]:
'__main__'
In [11]:
D.__mro__
Out[11]:
(__main__.D, __main__.A, __main__.C, object)

You want to create a class whose instances are created millions of times...you want to makee sure memory efficiecy

In [13]:
class OptimizedDate:
    __slots__ = ['day','month','year']
    
    def __init__(self, d, m ,y):
        self.day = d
        self.month = m
        self.year = y
        
    def __repr__(self):
        return "OptimizedDate({},{},{})".format(self.day, self.month, self.year)
In [14]:
o = OptimizedDate(1,1,2018)
In [15]:
o
Out[15]:
OptimizedDate(1,1,2018)
In [16]:
o.x = 0
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-16-689673674177> in <module>()
----> 1 o.x = 0

AttributeError: 'OptimizedDate' object has no attribute 'x'
In [17]:
o.day = 2
In [18]:
o.day = [1,2,3,4]
In [19]:
o
Out[19]:
OptimizedDate([1, 2, 3, 4],1,2018)

class decorators

functions decorators get function as argument and they return function as return value. class decorator will recieve class as an argument and return class

In [20]:
def debug(cls):
    print(cls)
    return cls

@debug
class Foo: ## Foo = debug(Foo)
    
    def __init__(self):
        pass
    
    def method1(self):
        pass
    
    def method2(self):
        pass  
    
<class '__main__.Foo'>
In [21]:
Foo()
Out[21]:
<__main__.Foo at 0x7f84643b6748>
In [24]:
def debug(cls):
    
    def logger(f):
        def wrapper(*args, **kwargs):
            print("Begning..", f.__qualname__)
            return f(*args, **kwargs)
        return wrapper
    
    
    for name, value in vars(cls).items():
        if callable(value):
            setattr(cls, name, logger(value))
    return cls

@debug
class Foo: ## Foo = debug(Foo)
    
    def __init__(self):
        pass
    
    def method1(self):
        pass
    
    def method2(self):
        pass  
    
In [25]:
f = Foo()
Begning.. Foo.__init__
In [26]:
f.method1()
Begning.. Foo.method1
In [27]:
f.method2()
Begning.. Foo.method2

staticmethod and classmethod

In [33]:
class A:
    
    def smethod():
        print("A: Hello from smethod")
In [41]:
class B:
    @staticmethod
    def smethod():
        print("B: Hello from smethod")
In [35]:
A
Out[35]:
__main__.A
In [36]:
B
Out[36]:
__main__.B
In [37]:
A.smethod()
A: Hello from smethod
In [38]:
B.smethod()
B: Hello from smethod
In [39]:
a = A()
In [40]:
a.smethod()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-3737d6e3c9e8> in <module>()
----> 1 a.smethod()

TypeError: smethod() takes 0 positional arguments but 1 was given
In [42]:
b = B()
In [43]:
b.smethod()
B: Hello from smethod
In [44]:
import datetime
In [45]:
class Mydatetime(datetime.datetime):
    pass
In [46]:
datetime.datetime.now()
Out[46]:
datetime.datetime(2018, 4, 4, 10, 23, 49, 201028)
In [47]:
Mydatetime.now()
Out[47]:
Mydatetime(2018, 4, 4, 10, 24, 9, 19754)
In [51]:
class A:
    @staticmethod
    def new():
        return A()
    
class B(A):
    
    pass
In [49]:
B.new()
Out[49]:
<__main__.A at 0x7f84643dad30>
In [50]:
A.new()
Out[50]:
<__main__.A at 0x7f84643da780>
In [52]:
class A:
    @classmethod
    def new(cls, *args):
        return cls()
    
class B(A):
    
    pass
In [53]:
B.new()
Out[53]:
<__main__.B at 0x7f84643e5e48>
In [54]:
class A:

    def f1():
        pass
    
    def f2(self):
        pass
    
    
In [55]:
a = A()
In [58]:
a.f1()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-58-1c74751ad4be> in <module>()
----> 1 a.f1()

TypeError: f1() takes 0 positional arguments but 1 was given
In [60]:
A.f1
Out[60]:
<function __main__.A.f1>
In [61]:
A.f2
Out[61]:
<function __main__.A.f2>
In [63]:
A.f2(a) ## >> a.f2()
In [65]:
A.f1() 
In [66]:
a.f1() ## >>> A.f1(a)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-66-17770d46bab0> in <module>()
----> 1 a.f1() ## >>> A.f1(a)

TypeError: f1() takes 0 positional arguments but 1 was given

properties

In [73]:
class Person:
    
    def __init__(self, name, surname, email):
        self._name = name
        self._surname = surname
        self._email = email
    
    @property
    def name(self):
        return " ".join([self._name, self._surname])
    
    @name.setter
    def name(self, value):
        self._name, self._surname = value.split(" ")
    
    @name.deleter
    def name(self):
        raise Exception("Can not delete")
        
    
In [74]:
p = Person("David", "Beazly", "david@python.org")
In [75]:
p.name
Out[75]:
'David Beazly'
In [76]:
p.name = "Anand Chitipothu"
In [77]:
p.name
Out[77]:
'Anand Chitipothu'
In [78]:
del p.name
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-78-82a48009a62c> in <module>()
----> 1 del p.name

<ipython-input-73-9297581764f2> in name(self)
     16     @name.deleter
     17     def name(self):
---> 18         raise Exception("Can not delete")
     19 
     20 

Exception: Can not delete
In [79]:
type(p.name)
Out[79]:
str

Descriptors

In [92]:
# Descriptor attribute for an integer type-checked attribute 
# recepie taken from python cookbook, by brian k jones and david beazley 

class Integer:
    def __init__(self, name):
        self.name = name

    def __get__(self, instance, cls):
        print("__get__ from", self)
        if instance is None:
            return self
        elif self.name not in instance.__dict__:
            raise AttributeError("No such attribute")
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        print("__set__ from ", self)
        if not isinstance(value, int):
            raise TypeError('Expected an int')
       
        instance.__dict__[self.name] = value

    def __delete__(self, instance):
        print("__del__ from", self)
        del instance.__dict__[self.name]
    
    def __str__(self):
        return "Integer<{0.name!s}>".format(self)
In [93]:
class Point:
    x = Integer('x')
    y = Integer('y')
    
    def __init__(self, x, y):
        self.x = x
        self.y = y
In [94]:
p = Point(2,3)
__set__ from  Integer<x>
__set__ from  Integer<y>
In [95]:
p.x
__get__ from Integer<x>
Out[95]:
2
In [96]:
type(p.x)
__get__ from Integer<x>
Out[96]:
int
In [97]:
del p.x
__del__ from Integer<x>
In [98]:
p.x
__get__ from Integer<x>
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-98-87ad85736430> in <module>()
----> 1 p.x

<ipython-input-92-be7a5dd81159> in __get__(self, instance, cls)
     11             return self
     12         elif self.name not in instance.__dict__:
---> 13             raise AttributeError("No such attribute")
     14         return instance.__dict__[self.name]
     15 

AttributeError: No such attribute

problem

  • Write your own my_property kind of framework/class which behaves like in build property
In [164]:
class Person:
    
    def __init__(self, name, surname, email):
        self._name = name
        self._surname = surname
        self._email = email
    
    @property
    def name(self):
        return " ".join([self._name, self._surname])
    
    @name.setter
    def name(self, value):
        self._name, self._surname = value.split(" ")
    
    @name.deleter
    def name(self):
        raise Exception("Can not delete")
        

class my_property:
    
    def __init__(self, f):
        self.function = f
    
    def __get__(self, instance, cls):
        if not instance:
            return self
        else:
            return self.function(instance)
    
    def __set__(self, instance, value):
        return self.function(instance, value)
        
    def __delete__(self, instance):
        return self.function(instance)
        
    @classmethod
    def setter(cls, f):
        return cls(f)
        
    @classmethod
    def deleter(cls, f):
        return cls(f)
        
class P:
    
    def __init__(self, name):
        self._name = name
    
    @my_property
    def email(self):
        return "@".join([self._name, "vmware.com"])
    
  
In [165]:
p = P("xyz")
In [166]:
p.email
Out[166]:
'xyz@vmware.com'
In [113]:
# Descriptor attribute for an integer type-checked attribute 
# recepie taken from python cookbook, by brian k jones and david beazley 

class Integer:
    def __init__(self, name):
        self.name = name

    def __get__(self, instance, cls):
        print("__get__ from", self,"*", instance,"*", cls)
        if instance is None:
            return self
        elif self.name not in instance.__dict__:
            raise AttributeError("No such attribute")
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        print("__set__ from ", self, instance, value)
        if not isinstance(value, int):
            raise TypeError('Expected an int')
       
        instance.__dict__[self.name] = value

    def __delete__(self, instance):
        print("__del__ from", self, instance)
        del instance.__dict__[self.name]
    
    def __str__(self):
        return "Integer<{0.name!s}>".format(self)


class Point:
    x = Integer('x')
    y = Integer('y')
    
    def __init__(self, x, y):
        self.x = x
        self.y = y
In [111]:
point = Point(1,2)
__set__ from  Integer<x> <__main__.Point object at 0x7f84643805f8> 1
__set__ from  Integer<y> <__main__.Point object at 0x7f84643805f8> 2
In [114]:
Point.x
__get__ from Integer<x> * None * <class '__main__.Point'>
Out[114]:
<__main__.Integer at 0x7f8464390588>

Context managers

In [115]:
with open("data.csv") as f:
    print(f.read())
1,2,3,4,5,6,7,8,9,10
2,4,6,8,10,12,14,16,18,20
3,6,9,12,15,18,21,24,27,30
4,8,12,16,20,24,28,32,36,40
5,10,15,20,25,30,35,40,45,50

In [120]:
%%file mytcpserver.py
import socketserver
import socket
import sys


class MyTCPHandler(socketserver.BaseRequestHandler):

    def handle(self):
        data = self.request.recv(2048).strip()
        print ("%s wrote: " % self.client_address[0])
        print (data)
        if data=="close":
            self.request.close()
            self.server.shutdown()
        else:
            self.request.send(data.upper())

def start_server():
    HOST, PORT = "127.0.0.1", 3456
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()

def send_client_msg():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("localhost",3456))
    s.send("This is junk data KJHJKASGHD jhG ASDGH AHSGDJASGH DFJKAGH:OP{IO "*10)
    received = s.recv(1024)
    s.close()
    print ("Received: " + received)

if __name__ == "__main__":
    start_server()
Writing mytcpserver.py
In [ ]:
 
In [122]:
from socket import socket, AF_INET, SOCK_STREAM #from python cookbook, 3rd edition

class LazyConnection:
    def __init__(self, address, family=AF_INET, type=SOCK_STREAM):
        self.address = address
        self.family = AF_INET
        self.type = SOCK_STREAM
        self.sock = None
        
    def __enter__(self):
        print("__enter__")
        if self.sock is not None:
            raise RuntimeError("Already connected")
        self.sock = socket(self.family, self.type)
        self.sock.connect(self.address)
        return self.sock
        
    def __exit__(self, exception_type, exception_value, traceback):
        print("__exit__")
        self.sock.close()
        self.sock = None
In [123]:
import time
address = ("127.0.0.1", 3456)
with LazyConnection(address) as conn:## here enter will be called
    time.sleep(3)
    conn.send(b"Hello")
    msg = conn.recv(1024)
    print(msg.decode())
    #here exit will be called
__enter__
HELLO
__exit__

Multithreading

In [124]:
import threading
In [128]:
import time
def tick(n):
    for i in range(n):
        print("Tick", i)
        time.sleep(1)
        
thread = threading.Thread(target=tick, args=(10,))
thread.start()
Tick 0
Tick 1
Tick 2
Tick 3
Tick 4
Tick 5
Tick 6
Tick 7
Tick 8
Tick 9
In [131]:
import time
def tick(n):
    for i in range(n):
        print("Tick", i)
        time.sleep(2)
        
thread = threading.Thread(target=tick, args=(10,))
thread.start()
thread.join() # waits till thread finishes
Tick 0
Tick 1
Tick 2
Tick 3
Tick 4
Tick 5
Tick 6
Tick 7
Tick 8
Tick 9
In [132]:
2 + 3
Out[132]:
5
In [135]:
%%file thread.py
import threading
import time
def tick(n):
    for i in range(n):
        print("Tick", i)
        time.sleep(2)
        
if __name__ == "__main__":
    thread = threading.Thread(target=tick, args=(5,))
    thread.start()
    thread.join() # waits till thread finishes
    print("Thread is over!")
Overwriting thread.py
In [136]:
!python thread.py
Tick 0
Tick 1
Tick 2
Tick 3
Tick 4
Thread is over!
In [154]:
%%file tdownload.py
import threading
import requests
import sys
import time


def wait(*args):
    time.sleep(1)
    
def download(url):
    requests.get(url)
    #print("Finished!")

def executetask(concurrency, tasksize=10):
    argsq = [("http://httpbin.org/html",) for i in range(tasksize)]
    while argsq:
        numt = concurrency if len(argsq)>concurrency else len(argsq)
        threads = [threading.Thread(target=wait, args=argsq.pop()) for i in range(numt)]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
    
    
if __name__ == "__main__":
    executetask(int(sys.argv[1]))
Overwriting tdownload.py
In [155]:
!python tdownload.py 1
In [145]:
!python tdownload.py 2
Finished!
Finished!
Finished!
Finished!
Finished!
Finished!
Finished!
Finished!
Finished!
Finished!
In [156]:
!time -p python tdownload.py 1
real 10.42
user 0.36
sys 0.03
In [157]:
!time -p python tdownload.py 2
real 5.42
user 0.37
sys 0.03
In [158]:
!time -p python tdownload.py 4
real 3.42
user 0.38
sys 0.02
In [173]:
%%file tpdownload.py
from multiprocessing.pool import ThreadPool
import requests
import sys
import time


def wait(*args):
    time.sleep(1)
    
def download(url):
    requests.get(url)
    #print("Finished!")

def executetask(concurrency, tasksize=10):
    argsq = [("http://httpbin.org/html",) for i in range(tasksize)]
    pool = ThreadPool(concurrency)
    r = pool.map(wait, argsq)
    print(r)
    
if __name__ == "__main__":
    executetask(int(sys.argv[1]))
Overwriting tpdownload.py
In [175]:
!time -p python tpdownload.py 1
[None, None, None, None, None, None, None, None, None, None]
real 10.43
user 0.37
sys 0.03
In [176]:
!time -p python tpdownload.py 2
[None, None, None, None, None, None, None, None, None, None]
real 6.44
user 0.40
sys 0.03
In [177]:
!time -p python tpdownload.py 4
[None, None, None, None, None, None, None, None, None, None]
real 3.42
user 0.40
sys 0.02
In [193]:
%%file tcpu.py
from multiprocessing.pool import ThreadPool
import requests
import sys
import time


def saxpy(*args):
    s = 0
    for i in range(1000):
        for j in range(10000):
            s += i*j*1.0
    return s
    
def executetask(concurrency, tasksize=10):
    argsq = [("http://httpbin.org/html",) for i in range(tasksize)]
    pool = ThreadPool(concurrency)
    r = pool.map(saxpy, argsq)
    print(r)
    
if __name__ == "__main__":
    executetask(int(sys.argv[1]))
Overwriting tcpu.py
In [189]:
!time -p python tcpu.py 1
[24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0]
real 17.35
user 17.25
sys 0.02
In [190]:
!time -p python tcpu.py 2
[24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0]
real 18.96
user 18.44
sys 0.08
In [192]:
%%file pcpu.py
from multiprocessing import Pool
import requests
import sys
import time


def saxpy(*args):
    s = 0
    for i in range(1000):
        for j in range(10000):
            s += i*j*1.0
    return s
    
def executetask(concurrency, tasksize=10):
    argsq = [("http://httpbin.org/html",) for i in range(tasksize)]
    pool = Pool(concurrency)
    r = pool.map(saxpy, argsq)
    print(r)
    
if __name__ == "__main__":
    executetask(int(sys.argv[1]))
Overwriting pcpu.py
In [194]:
!time -p python pcpu.py 1
[24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0]
real 18.44
user 18.31
sys 0.04
In [195]:
!time -p python pcpu.py 2
[24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0]
real 11.55
user 18.88
sys 0.03
In [196]:
!time -p python pcpu.py 4
[24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0, 24972502500000.0]
real 11.10
user 35.72
sys 0.09

Communicating to thread

In [223]:
from threading import Event
import time
class Clock(threading.Thread):
    
    def setEvent(self, e):
        self.stopevent = e
        
    def run(self):
        i = 0
        while not self.stopevent.isSet():
            print("Tick ", i)
            i += 1
            time.sleep(2)

    
In [228]:
e = Event()
In [229]:
c = Clock()
c.setEvent(e)
c.start()
Tick  0
Tick  1
Tick  2
Tick  3
In [230]:
e.set()
In [231]:
int("saldk")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-231-e2d4ff9321f3> in <module>()
----> 1 int("saldk")

ValueError: invalid literal for int() with base 10: 'saldk'

Testing

In [237]:
%%file functionstest.py
import pytest

def fib(n):
    if n in [1,2]:
        return 1
    return fib(n-1)+ fib(n-2)

def parseint(strnum):
    try:
        return int(strnum)
    except ValueError as v:
        if strnum.lower()=="nan" or strnum=="":
            return 0
        else:
            raise v
            
def test_fib():
    assert fib(1) == 1
    assert fib(2) == 1
    #assert fib(3) == 3
    
def test_parseint():
    assert parseint(" 2") == 2
    assert parseint("Nan") == 0
    with pytest.raises(ValueError):
        parseint("asasd")
Overwriting functionstest.py
In [238]:
!py.test -v functionstest.py
============================= test session starts ==============================
platform linux -- Python 3.6.1, pytest-3.0.7, py-1.4.33, pluggy-0.4.0 -- /home/vikrant/usr/local/anaconda3/bin/python
cachedir: .cache
rootdir: /home/vikrant/trainings/2018/vmware-advanced-apr, inifile:
collected 2 items 

functionstest.py::test_fib PASSED
functionstest.py::test_parseint PASSED

=========================== 2 passed in 0.01 seconds ===========================
In [239]:
t = datetime.datetime.now()
In [ ]:
t.strftime
In [240]:
%%file weekday.py

import datetime

def now():
    return datetime.datetime.now()

def weekday():
    n = now()
    return n.strftime("%A")
Writing weekday.py
In [241]:
import weekday
In [242]:
weekday.weekday()
Out[242]:
'Wednesday'
In [253]:
%%file test_weekday.py
import weekday
import pytest
import datetime

def test_weekday(monkeypatch):
    def mydate(y, m, d):
        return datetime.datetime(y,m,d)
    
    def fakenow():
        return mydate(*date)

    monkeypatch.setattr(weekday, "now", fakenow)
    
    date = (2018,4,4)
    assert weekday.weekday() == "Wednesday"

    date = (2018,2,28)
    assert weekday.weekday() == "Wednesday"
Overwriting test_weekday.py
In [254]:
!py.test test_weekday.py
============================= test session starts ==============================
platform linux -- Python 3.6.1, pytest-3.0.7, py-1.4.33, pluggy-0.4.0
rootdir: /home/vikrant/trainings/2018/vmware-advanced-apr, inifile:
collected 1 items 

test_weekday.py .

=========================== 1 passed in 0.01 seconds ===========================
In [256]:
help(os.removedirs)
Help on function removedirs in module os:

removedirs(name)
    removedirs(name)
    
    Super-rmdir; remove a leaf directory and all empty intermediate
    ones.  Works like rmdir except that, if the leaf directory is
    successfully removed, directories corresponding to rightmost path
    segments will be pruned away until either the whole path is
    consumed or an error occurs.  Errors during this latter phase are
    ignored -- they generally mean that a directory was not empty.

In [261]:
%%file setupteardown.py
import pytest
import os, time


def writefile(filename):
    d = [[str(i*j) for i in range(1,5)] for j in range(1,10)]
    with open(filename, "w") as f:
        for row in d:
            f.write(",".join(row))
            f.write("\n")
    

@pytest.fixture
def setup_teardown():
    os.mkdir("test")
    time.sleep(5)
    yield os.path.join(os.getcwd(),"test")
    time.sleep(3)
    os.removedirs("test")
    
def test_writefile(setup_teardown):
    path = os.path.join(setup_teardown,"data.csv")
    writefile(path)
    assert os.path.exists(path)
    assert os.path.isfile(path)
    os.remove(path)
    
Overwriting setupteardown.py
In [263]:
!py.test -v setupteardown.py
============================= test session starts ==============================
platform linux -- Python 3.6.1, pytest-3.0.7, py-1.4.33, pluggy-0.4.0 -- /home/vikrant/usr/local/anaconda3/bin/python
cachedir: .cache
rootdir: /home/vikrant/trainings/2018/vmware-advanced-apr, inifile:
collected 1 items 

setupteardown.py::test_writefile PASSED

=========================== 1 passed in 8.02 seconds ===========================

Downloading from web

In [264]:
import requests
In [265]:
resp = requests.get("http://httpbin.org/html")
In [266]:
resp.status_code
Out[266]:
200
In [269]:
print(resp.text[:100])
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
      <h1>Herman Melville - Moby-Dick</h1>

     
In [272]:
resp = requests.get("http://httpbin.org/get", params={"a":"xyz","python":"hello"})
In [273]:
resp.status_code
Out[273]:
200
In [274]:
print(resp.text)
{
  "args": {
    "a": "xyz", 
    "python": "hello"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.14.2"
  }, 
  "origin": "103.19.212.8", 
  "url": "http://httpbin.org/get?a=xyz&python=hello"
}

In [275]:
url = "https://duckduckgo.com/"
data = {"q":"pytest","t":"lm","ia":"web"}
In [276]:
resp = requests.get(url, params=data)
In [277]:
resp.status_code
Out[277]:
200
In [283]:
print(resp.text)
<!DOCTYPE html><!--[if IEMobile 7 ]> <html lang="en_US" class="no-js iem7"> <![endif]--><!--[if lt IE 7]> <html lang="en_US" class="no-js ie6 lt-ie10 lt-ie9 lt-ie8 lt-ie7"><![endif]--><!--[if IE 7]>    <html lang="en_US" class="no-js ie7 lt-ie10 lt-ie9 lt-ie8"> <![endif]--><!--[if IE 8]>    <html lang="en_US" class="no-js ie8 lt-ie10 lt-ie9  has-zcm"><![endif]--><!--[if IE 9]>    <html lang="en_US" class="no-js ie9 lt-ie10 has-zcm"> <![endif]--><!--[if (gte IE 9)|(gt IEMobile 7)|!(IEMobile)|!(IE)]><!--><html class="no-js has-zcm  "><!--<![endif]--><head><meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1"><meta http-equiv="content-type" content="text/html; charset=utf-8"><title>pytest at DuckDuckGo</title><link rel="stylesheet" href="/s1573.css" type="text/css"><link rel="stylesheet" href="/r1573.css" type="text/css"><link rel="manifest" href="manifest.json"><meta name="robots" content="noindex,nofollow"><meta name="referrer" content="origin"><link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" sizes="16x16 24x24 32x32 64x64"/><link rel="apple-touch-icon" href="/assets/icons/meta/DDG-iOS-icon_60x60.png"/><link rel="apple-touch-icon" sizes="76x76" href="/assets/icons/meta/DDG-iOS-icon_76x76.png"/><link rel="apple-touch-icon" sizes="120x120" href="/assets/icons/meta/DDG-iOS-icon_120x120.png"/><link rel="apple-touch-icon" sizes="152x152" href="/assets/icons/meta/DDG-iOS-icon_152x152.png"/><link rel="image_src" href="/assets/icons/meta/DDG-icon_256x256.png"/><script type="text/javascript">var ct,fd,fq,it,iqa,iqm,iqs,iqp,iqq,qw,dl,ra,rv,rad,r1hc,r1c,r2c,r3c,rfq,rq,rds,rs,rt,rl,y,y1,ti,tig,iqd,locale,settings_js_version='s2371',is_twitter='';fq=0;fd=1;it=0;iqa=0;iqbi=0;iqm=0;iqs=0;iqp=0;iqq=0;qw=1;dl='';ct='IN';iqd=0;r1hc=0;r1c=0;r3c=0;rq='pytest';rqd="pytest";rfq=0;rt='';ra='lm';rv='';rad='';rds=30;rs=0;spice_version='1368';spice_paths='{}';locale='en_US';settings_url_params={};rl='wt-wt';rlo=0;df='';ds='';sfq='';iar='';vqd='337670626555545433621251206104130039698';</script><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" /><meta name="HandheldFriendly" content="true" /><meta name="apple-mobile-web-app-capable" content="no" /></head><body class="body--serp"><input id="state_hidden" name="state_hidden" type="text" size="1"><span class="hide">Ignore this box please.</span><div id="spacing_hidden_wrapper"><div id="spacing_hidden"></div></div><script type="text/javascript" src="/locales/en_US/LC_MESSAGES/duckduckgo-duckduckgo+sprintf+gettext+locale-simple.20180401.213004.js"></script><script type="text/javascript" src="/lib/l110.js"></script><script type="text/javascript" src="/util/u187.js"></script><script type="text/javascript" src="/d2371.js"></script><div class="site-wrapper  js-site-wrapper"><div id="header_wrapper" class="header-wrap js-header-wrap"><div id="header" class="header  cw"><div class="header__search-wrap"><a tabindex="-1" href="/?t=lm" class="header__logo-wrap js-header-logo"><span class="header__logo js-logo-ddg">DuckDuckGo</span></a><div class="header__content  header__search"><form id="search_form" class="search--adv  search--header  js-search-form" name="x" action="/"><input type="text" name="q" tabindex="1" autocomplete="off" id="search_form_input" class="search__input--adv  js-search-input" value="pytest"><input id="search_form_input_clear" class="search__clear  js-search-clear" type="button" tabindex="3" value="X"/><input id="search_button" class="search__button  js-search-button" type="submit" tabindex="2" value="S" /><a id="search_dropdown" class="search__dropdown" href="javascript:;" tabindex="4"></a><div id="search_elements_hidden" class="search__hidden  js-search-hidden"></div></form></div></div><div id="duckbar" class="zcm-wrap  zcm-wrap--header  is-noscript-hidden"></div></div><div class="header--aside js-header-aside"></div></div><div id="zero_click_wrapper" class="zci-wrap"></div><div id="vertical_wrapper" class="verticals"></div><div id="web_content_wrapper" class="content-wrap "><div class="serp__top-right  js-serp-top-right"></div><div class="serp__bottom-right  js-serp-bottom-right"><div class="js-feedback-btn-wrap"></div></div><div class="cw"><div id="links_wrapper" class="serp__results js-serp-results"><div class="results--main"><div class="search-filters-wrap"><div class="js-search-filters search-filters"></div></div><noscript><meta http-equiv="refresh" content="0;URL=/html?q=pytest"><link href="/css/noscript.css" rel="stylesheet" type="text/css"><div class="msg msg--noscript"><p class="msg-title--noscript">You are being redirected to the non-JavaScript site.</p>Click <a href="/html/?q=pytest">here</a> if it doesn't happen automatically.</div></noscript><div class="ia-modules js-ia-modules"></div><div id="message" class="results--message"></div><div id="ads" class="results--ads results--ads--main is-hidden js-results-ads"></div><div id="links" class="results is-hidden js-results"></div></div><div class="results--sidebar js-results-sidebar"><div class="sidebar-modules js-sidebar-modules"></div><div class="is-hidden js-sidebar-ads"></div></div></div></div></div><div id="bottom_spacing2"> </div></div><script type="text/javascript"></script><script type="text/JavaScript">function nrji() {nrj('/t.js?q=pytest&l=wt-wt&p=1&s=0&ct=IN&ss_mkt=us&yhs=1');nrje('/d.js?q=pytest&l=wt-wt&p=1&s=0&a=lm&ct=IN&ss_mkt=us&vqd=337670626555545433621251206104130039698&yhs=1&sp=1','/d.js?q=pytest&l=wt-wt&p=1&s=0&a=lm&ct=IN&ss_mkt=us&vqd=337670626555545433621251206104130039698&yhs=1&sp=1');;};DDG.ready(nrji, 1);</script><script src="/g1871.js"></script><script type="text/javascript">DDG.page = new DDG.Pages.SERP({ showSafeSearch: 0, instantAnswerAds: false });</script><div id="z2"> </div><div id="z"></div></body></html>
In [284]:
resp = requests.post("http://httpbin.org/post", data={"name":"python","passwd":"xxxx"})
In [286]:
print(resp.text)
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "name": "python", 
    "passwd": "xxxx"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "23", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.14.2"
  }, 
  "json": null, 
  "origin": "103.19.212.8", 
  "url": "http://httpbin.org/post"
}

In [287]:
import requests
url = "https://api.github.com/orgs/vmware/repos"
repos = requests.get(url).json()
In [ ]:
 
In [288]:
type(repos)
Out[288]:
list
In [291]:
repos[0]
Out[291]:
{'archive_url': 'https://api.github.com/repos/vmware/pyvco/{archive_format}{/ref}',
 'archived': False,
 'assignees_url': 'https://api.github.com/repos/vmware/pyvco/assignees{/user}',
 'blobs_url': 'https://api.github.com/repos/vmware/pyvco/git/blobs{/sha}',
 'branches_url': 'https://api.github.com/repos/vmware/pyvco/branches{/branch}',
 'clone_url': 'https://github.com/vmware/pyvco.git',
 'collaborators_url': 'https://api.github.com/repos/vmware/pyvco/collaborators{/collaborator}',
 'comments_url': 'https://api.github.com/repos/vmware/pyvco/comments{/number}',
 'commits_url': 'https://api.github.com/repos/vmware/pyvco/commits{/sha}',
 'compare_url': 'https://api.github.com/repos/vmware/pyvco/compare/{base}...{head}',
 'contents_url': 'https://api.github.com/repos/vmware/pyvco/contents/{+path}',
 'contributors_url': 'https://api.github.com/repos/vmware/pyvco/contributors',
 'created_at': '2011-03-23T18:18:26Z',
 'default_branch': 'master',
 'deployments_url': 'https://api.github.com/repos/vmware/pyvco/deployments',
 'description': 'Python bindings for VMware Orchestrator',
 'downloads_url': 'https://api.github.com/repos/vmware/pyvco/downloads',
 'events_url': 'https://api.github.com/repos/vmware/pyvco/events',
 'fork': True,
 'forks': 3,
 'forks_count': 3,
 'forks_url': 'https://api.github.com/repos/vmware/pyvco/forks',
 'full_name': 'vmware/pyvco',
 'git_commits_url': 'https://api.github.com/repos/vmware/pyvco/git/commits{/sha}',
 'git_refs_url': 'https://api.github.com/repos/vmware/pyvco/git/refs{/sha}',
 'git_tags_url': 'https://api.github.com/repos/vmware/pyvco/git/tags{/sha}',
 'git_url': 'git://github.com/vmware/pyvco.git',
 'has_downloads': True,
 'has_issues': False,
 'has_pages': True,
 'has_projects': True,
 'has_wiki': True,
 'homepage': 'http://sigma.github.com/vmw.vco',
 'hooks_url': 'https://api.github.com/repos/vmware/pyvco/hooks',
 'html_url': 'https://github.com/vmware/pyvco',
 'id': 1517508,
 'issue_comment_url': 'https://api.github.com/repos/vmware/pyvco/issues/comments{/number}',
 'issue_events_url': 'https://api.github.com/repos/vmware/pyvco/issues/events{/number}',
 'issues_url': 'https://api.github.com/repos/vmware/pyvco/issues{/number}',
 'keys_url': 'https://api.github.com/repos/vmware/pyvco/keys{/key_id}',
 'labels_url': 'https://api.github.com/repos/vmware/pyvco/labels{/name}',
 'language': 'Python',
 'languages_url': 'https://api.github.com/repos/vmware/pyvco/languages',
 'license': {'key': 'mit',
  'name': 'MIT License',
  'spdx_id': 'MIT',
  'url': 'https://api.github.com/licenses/mit'},
 'merges_url': 'https://api.github.com/repos/vmware/pyvco/merges',
 'milestones_url': 'https://api.github.com/repos/vmware/pyvco/milestones{/number}',
 'mirror_url': None,
 'name': 'pyvco',
 'notifications_url': 'https://api.github.com/repos/vmware/pyvco/notifications{?since,all,participating}',
 'open_issues': 0,
 'open_issues_count': 0,
 'owner': {'avatar_url': 'https://avatars0.githubusercontent.com/u/473334?v=4',
  'events_url': 'https://api.github.com/users/vmware/events{/privacy}',
  'followers_url': 'https://api.github.com/users/vmware/followers',
  'following_url': 'https://api.github.com/users/vmware/following{/other_user}',
  'gists_url': 'https://api.github.com/users/vmware/gists{/gist_id}',
  'gravatar_id': '',
  'html_url': 'https://github.com/vmware',
  'id': 473334,
  'login': 'vmware',
  'organizations_url': 'https://api.github.com/users/vmware/orgs',
  'received_events_url': 'https://api.github.com/users/vmware/received_events',
  'repos_url': 'https://api.github.com/users/vmware/repos',
  'site_admin': False,
  'starred_url': 'https://api.github.com/users/vmware/starred{/owner}{/repo}',
  'subscriptions_url': 'https://api.github.com/users/vmware/subscriptions',
  'type': 'Organization',
  'url': 'https://api.github.com/users/vmware'},
 'permissions': {'admin': False, 'pull': True, 'push': False},
 'private': False,
 'pulls_url': 'https://api.github.com/repos/vmware/pyvco/pulls{/number}',
 'pushed_at': '2010-11-07T15:55:51Z',
 'releases_url': 'https://api.github.com/repos/vmware/pyvco/releases{/id}',
 'size': 225,
 'ssh_url': 'git@github.com:vmware/pyvco.git',
 'stargazers_count': 10,
 'stargazers_url': 'https://api.github.com/repos/vmware/pyvco/stargazers',
 'statuses_url': 'https://api.github.com/repos/vmware/pyvco/statuses/{sha}',
 'subscribers_url': 'https://api.github.com/repos/vmware/pyvco/subscribers',
 'subscription_url': 'https://api.github.com/repos/vmware/pyvco/subscription',
 'svn_url': 'https://github.com/vmware/pyvco',
 'tags_url': 'https://api.github.com/repos/vmware/pyvco/tags',
 'teams_url': 'https://api.github.com/repos/vmware/pyvco/teams',
 'trees_url': 'https://api.github.com/repos/vmware/pyvco/git/trees{/sha}',
 'updated_at': '2018-03-02T08:41:42Z',
 'url': 'https://api.github.com/repos/vmware/pyvco',
 'watchers': 10,
 'watchers_count': 10}
In [292]:
for r in repos:
    print(r['full_name'], r['forks'], r['watchers'])
vmware/pyvco 3 10
vmware/rvc 45 229
vmware/rbvmomi 157 273
vmware/vprobe-toolkit 9 31
vmware/CloudFS 16 36
vmware/vcd-nclient 2 3
vmware/lmock 5 7
vmware/FireBreath 2 3
vmware/weasel 1 12
vmware/vmware-vcenter 92 70
vmware/vmware-vshield 6 8
vmware/vcloud-rest 38 29
vmware/GemstoneWebTools 0 0
vmware/vmware-vcsa 18 23
vmware/vmware-vmware_lib 26 12
vmware/saml20serviceprovider 1 2
vmware/pg_rewind 18 127
vmware/vco-powershel-plugin 2 2
vmware/jenkins-reviewbot 12 27
vmware/dbeekeeper 0 0
vmware/thinapp_factory 16 30
vmware/vmware-cassandra 4 2
vmware/vmware-java 0 1
vmware/data-driven-framework 3 3
vmware/pyvmomi 500 1054
vmware/pyvmomi-community-samples 430 432
vmware/open-vm-tools 166 749
vmware/pyvmomi-tools 20 61
vmware/upgrade-framework 11 15
vmware/webcommander 32 135
In [295]:
for r in sorted(repos, key=lambda r:r['watchers'], reverse=True):
    print(r['full_name'], r['forks'], r['watchers'])
vmware/pyvmomi 500 1054
vmware/open-vm-tools 166 749
vmware/pyvmomi-community-samples 430 432
vmware/rbvmomi 157 273
vmware/rvc 45 229
vmware/webcommander 32 135
vmware/pg_rewind 18 127
vmware/vmware-vcenter 92 70
vmware/pyvmomi-tools 20 61
vmware/CloudFS 16 36
vmware/vprobe-toolkit 9 31
vmware/thinapp_factory 16 30
vmware/vcloud-rest 38 29
vmware/jenkins-reviewbot 12 27
vmware/vmware-vcsa 18 23
vmware/upgrade-framework 11 15
vmware/weasel 1 12
vmware/vmware-vmware_lib 26 12
vmware/pyvco 3 10
vmware/vmware-vshield 6 8
vmware/lmock 5 7
vmware/vcd-nclient 2 3
vmware/FireBreath 2 3
vmware/data-driven-framework 3 3
vmware/saml20serviceprovider 1 2
vmware/vco-powershel-plugin 2 2
vmware/vmware-cassandra 4 2
vmware/vmware-java 0 1
vmware/GemstoneWebTools 0 0
vmware/dbeekeeper 0 0

Problem

  • How do you find distance between two cities using google maps API?
    url for map api is "https://maps.googleapis.com/maps/api/distancematrix/json"
    parameters of above get url are

      origins
      destinations
      units (metric)

References for further reading

  • google for python docs
  • python cookbook by david beazly and Brian ...
  • Metaprogramming by David beazly
  • Concurrency from bottom up ..vidio by david beazly
In [ ]: