Category Archives: Python

Hatalari Yakalayalim Beyler …

Iste , hata mesajimiz bu ve ciktinin onemli yeride “ValueError“. Asagidaki cikti yas soruldugunda string girildiginde alindi.

/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/vahricmuhtaryan/PycharmProjects/fonksiyonlar1/test1.py
Yasin Kacdfdf
Traceback (most recent call last):
File “/Users/vahricmuhtaryan/PycharmProjects/fonksiyonlar1/test1.py”, line 5, in <module>
a = int(raw_input(“Yasin Kac”))
ValueError: invalid literal for int() with base 10: ‘dfdf’

Process finished with exit code 1

Baska bir ornek , buradada onemli olan “urllib3.exceptions.MaxRetryError” . Aciklamasi normal boye bir site yok baglanilacak.

/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/vahricmuhtaryan/PycharmProjects/fonksiyonlar1/test1.py
Traceback (most recent call last):
File “/Users/vahricmuhtaryan/PycharmProjects/fonksiyonlar1/test1.py”, line 14, in <module>
istek = http_w_pool.request(‘get’,’http://www.yupyu42342342p.com&#8217;)
File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/request.py”, line 69, in request
**urlopen_kw)
File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/request.py”, line 90, in request_encode_url
return self.urlopen(method, url, **extra_kw)
File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/poolmanager.py”, line 165, in urlopen
response = conn.urlopen(method, u.request_uri, **kw)
File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/connectionpool.py”, line 628, in urlopen
release_conn=release_conn, **response_kw)
File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/connectionpool.py”, line 628, in urlopen
release_conn=release_conn, **response_kw)
File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/connectionpool.py”, line 628, in urlopen
release_conn=release_conn, **response_kw)
File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/connectionpool.py”, line 608, in urlopen
_stacktrace=sys.exc_info()[2])
File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/util/retry.py”, line 273, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host=’www.yupyu42342342p.com’, port=80): Max retries exceeded with url: / (Caused by NewConnectionError(‘<urllib3.connection.HTTPConnection object at 0x101def590>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known’,))

Process finished with exit code 1

Burada program hataya dusmeden bir uyari yaratmamiz gerekiyor , aslinda try icin gerekli kismi yaptik ve ValueError/urllib3.exceptions.MaxRetryError denen hatalari yakaladik onun icin kodu soyle duzenleyip bir sonraki adima gecebiliriz.
Read the rest of this entry

Biri debug mi dedi :) yok yok ben print kullaniyorum

🙂 Evet zaten birsey yazabildigimiz yok birde yalandan debug edecegiz diye dosyayi acip oraya print yok bu fonksiyonu cagirmis obur dosyaya print, cok cilgin oluyor : )

Diyeceksiniz ki IDE lerde zaten var bu is , yukaridan debug dugmesine tikliyorsunuz , sonra sol a iki top koyuyorsunuz , alta bir console geliyor muthis ama sunucu tarafinda birde sizin olmayan kodu , script’leri debug etmek istiyorsaniz Python Debugger -pdb- cok guzel …

Su anda en favori komutum su ; -m parametresi ile pdb modulunu yukluyoruz ve birinci satirdan itibaren adim adim ilermeye baslayabiliriz.


vahric:self_class vahricmuhtaryan$ python -m pdb file1.py 
> /Users/vahricmuhtaryan/PycharmProjects/self_class/file1.py(7)<module>()
-> class Eskiversionclass:
(Pdb) 

Read the rest of this entry

Python six module 1.5.2 cause project creation Openstack with Ansible

Issue is : Getting an error when try to create project with ansible in Openstack

Error is :  fatal: [localhost]: FAILED! => {“changed”: false, “failed”: true, “invocation”: {“module_name”: “os_project”}, “parsed”: false}

This is what version Ubuntu i have 

noroot@acc:~/ansible$ lsb_release -a

No LSB modules are available.

Distributor ID: Ubuntu

Description: Ubuntu 14.04.3 LTS

Release: 14.04

Codename: trusty

Solution is : remove six.py from /usr/lib/python2.7/dist-packages/ , download 1.10.0 from pypi and put the six.py

VM

Class Kemige Dayaninca :)

Uzun zamandir su OOP dir class dir , self dir , __init__ dir , constructer , inheritance , instance  derken bir turlu ilgilenememistim , simdi bir kod incelemesi sirasinda ihtiyac oldu , iyikide olmus, bir yerden baslamak gerekiyordu.

Burada class nedir, oop nedirden bahsetmeyecegim , sanki eristigimiz bir foknsiyon gibi class a erismek , self kullanimi ve constructer ornegi olacak.

Oncelikle dokumanlari okurken belki yanlis bir baslangic olabilir ama python da eski ve yeni version class tanimlamasi gibi birsey var. Yeni version dedigimiz class i yaratmak icin artik varsayili olarak inheritance yapmak gerekiyor.

Inheritance aslinda Windows kullanicilarininda bildigi gibi ustten ilgili dosya haklarini almanin class uyarlamasi gibi birsey, burada haklari almiyorsunuzda degerleri veya attribute leri aliyorsunuz , bir nevi klonlama , kopyalamada diyebiliriz.

En basitinden class ornegi ;

class Eskiversionclass:
    # pass burada ne yazicagimizi bilmedigimizden kod hata vermesin diye
    # kullanilan placeholder
    pass

class Yeniversion(object):
    pass

Simdir burada once __init__ e bir goz atalim , aslinda __init__ bir constructer veya constructer method’u degil , yani diyemeyiz ki __init__ == constructer .

Read the rest of this entry

Python – Hizlica *args ve **kwargs

Cok gorup ne olduguna bakarim dedigim *args ve **kwargs hakkinda bir iki ornek
# Fonksiyonun alacagi deger sayisi belli 2
def toplama1(deger1,deger2):
    return int(deger1) + int(deger2)

print toplama1("3","3")

# Fonksiyonun alacagi deger sayisi belli degil ise
def toplama2(*args):
    return sum(args)

print toplama2(2,3,6,7,8,9,0,1,24,6,7)

# args burada ozel degil asagidaki gibi farkli sekildede yazilabilir onemli olan yildiz
def toplama3(*zasfdfdf):
    return sum(zasfdfdf)

print toplama3(1,1)

# Farkli bir kullanim yapar isek * ayni zamanda ikideger olarak set edilen degiskeni bolerek fonksiyona verebiliyor
def toplama1ustu(deger1,deger2):
    return int(deger1) + int(deger2)

ikideger = [10,20]

print toplama1ustu(*ikideger)

"""
Yildiz sayisini ikiye cikarinca bu kez key value almaya basliyoruz
Python da dictionary olarak geciyor
Bu arada genel orneklerde anlasilsin diye key, value diye tanimlaniyr , ondan bagimsiz kullanabilecegimizi gostermek
icin ahmet i key olarak mehmeti value olarak kullandim
Bu arada *** ise yaramiyor farki birsey yapmiyor 🙂
"""

def degiskenleribas(**kwdegisken):
    for ahmet, mehmet in kwdegisken.items():
        print (ahmet,mehmet)

print degiskenleribas(a=5,b=6,c=8)

Kolay Gelsin
VM

Quick and Simple Tip – Connect Redis From Python

First install redis pakage

vahric:~ vahricmuhtaryan$ pip install redis

then make simple PUT/GET

import redis

connectredis = redis.Redis(host=’10.111.21.140′,db=0,port=6379)

#Put/Set Key/Value
connectredis.set(‘vahric_test2′,’deger2’)

#Get Value from Key
print connectredis.get(‘vahric_test2’)

Thats it

Python ,vCloud Director REST API Series for Beginners – Just get the list of Org

Hola Everybody, (I’m not Spanish or Catalan but under effect this days)

In my first article about vCloud REST and API , i just tried to describe how to get the token with very bad coding example in WordPress. Its good to find a way to share codes from WordPress, thanks for this article.

In this article I added getting org list from vCloud Director also made error handling and XML parse with ElementTree

I’m expecting in next article start to create something inside vCloud Director with REST API and python and extend the code


# coding=utf-8
def get_vcloud_token(vcd_hostname, password, api_version):
    import urllib2
    import base64

    vcloudsession_url = "https://" + vcd_hostname + "/api/sessions"
    encode_credentials = base64.b64encode(password)

    # Prepare headers we will post
    vcloudapi_version = "application/*+xml;version=" + api_version
    vcloudapi_auth = "Basic %s" % encode_credentials
    data = ""
    authheaders = {'Accept': vcloudapi_version, 'Authorization': vcloudapi_auth}
    request_format = urllib2.Request(vcloudsession_url, data, authheaders)
    make_request = urllib2.urlopen(request_format)
    # We will not need to read whole html out
    # result = make_request.read()
    # Just need to catch key provided by vCloud Director from header response
    token = make_request.info()['x-vcloud-authorization']
    # this function will turn result to get and use it where it called
    return token

def get_vcloud_org_list(exisiting_token):
    import urllib2
    import xml.etree.cElementTree as ET

    vcloudapi_url = "https://v.dorukcloud.com/api/" + "org/"
    api_version = "5.5"
    vcloudapi_version = "application/*+xml;version=" + api_version

    # Now use the requested token before for query the org list
    afterauthheader_org = {'Accept': vcloudapi_version, 'x-vcloud-authorization': exisiting_token}

    # Be careful, there is no PUT request here, we will make a GET because of that second parameter
    # described with headers = afterauthheader_org and if you do not set headers then second parameters
    # will be accepted as a data
    make_org_list_call = urllib2.Request(vcloudapi_url, headers=afterauthheader_org)

    # Also lets improve our code with exception handling
    try:
        make_org_list_request = urllib2.urlopen(make_org_list_call)
        # Now we take the response as a file like object
        org_list_response = make_org_list_request.read()
        org_list_in_xml = ET.fromstring(org_list_response)
        # Here because of result is file like its a string we are importing it and ET will parse it
        org_list_in_xml = ET.fromstring(org_list_response)

        # Pls print response to understand how is the result
        # You will see that its an XML out and OrgList is will be the root tag or root element, it will have some child(s)
        # it will be Org and Org will have some attributes like Name , Href and type
        # we will take the name attributes of each child(s)

        # Create an empty array
        org_name_array = []

        for child in org_list_in_xml:
            # Add child.attrib['name'] inside the array
            org_name_array.append(child.attrib['name'])

        return org_name_array

    except urllib2.URLError,e:
        print 'I guess wrong URL, SORRY ! '

# This is another function defined and name is main, you can see that inside main function we are calling get_vcloud_token function

def main():
    token_result = get_vcloud_token("you_vcloud_url", "Sit_Lord@System:password", "5.5")
    #This lines for tests , you can use it after remove the #
    #print token_result

    org_names = get_vcloud_org_list(token_result)

    #This lines for tests , you can use it after remove the #
    #print type(org_names)
    #for i in org_names:
    #    print i

main()