I'm a complete beginner learning Python. I'm writing code to get response of cloudstack api call 'listTemplates'. But what ever i did, it shows a error message like 'Unable to execute API command listtemplates due to missing parameter templatefilter'

i have tried to specify thar parameter but failed. can anyone show how to write the code to specify the parameter 'templatefilter' in this code

import getopt
import sys
import hmac
import hashlib
import base64
import urllib


def formattedCmd(api, cmd):
s = 'apiKey=' + api + '&' + cmd
return s


def encypt(string, key):
h = hmac.new(key, string, hashlib.sha1)
#  print '\n' + h.digest()
return base64.b64encode(h.digest())


def formattedUrl(baseUrl, api, cmd, signature):
url = baseUrl + '?' + formattedCmd(api, cmd) + '&' + urllib.urlencode({'signature': signature})
return url


def main():
print 'ffffffffffffffffffffffffff'
try:
    print getopt.getopt(sys.argv[1:], 'u:a:s:', ['help', 'output='])
    opts, args = getopt.getopt(sys.argv[1:], 'u:a:s:', ['help', 'output='])
    print opts, args,'print'
except getopt.GetoptError, err:
    print str(err)
    sys.exit(2)

baseUrl = 'http://10.176.14.26:8080/client/api'

cmd = 'command=listTemplates'   
temf= 'templatefilter=featured'
api = 'Qo9Qwfatwz9ARB328Btn9PftzL2Cf5LOWd8OFyJmiM513tpTIm-zKxJoWkWqf353Df397xcLdKXGk8_JO8nM3Q'
secret = '-kgkBuBUrGFeIC4gUvngSK_3Ypmi7fuF8XdVXIusnyyiEP2YUcG3FnPUGJGy3rp3Bw5ZNnqgS-9tIfyV1QnK1g'

for o, a in opts:
    if o == '-u':
        cmd = a
    elif o == '-a':
        api = a
    elif o == '-s':
        secret = a
    else:
        assert False, 'unhandled option'

newCmd = formattedCmd(api, cmd).lower()
signature = encypt(newCmd, secret)
url = formattedUrl(baseUrl, api, cmd, signature)

print '\n' + url

if __name__ == '__main__':
main()

Your indentation is incorrect.

The code as given won't work; the indentation is all off. Here is the program with what I presume is the correct indentation:`

import getopt
import sys
import hmac
import hashlib
import base64
import urllib


def formattedCmd(api, cmd):
    s = 'apiKey=' + api + '&' + cmd
    return s


def encypt(string, key):
    h = hmac.new(key, string, hashlib.sha1)
    #  print '\n' + h.digest()
    return base64.b64encode(h.digest())


def formattedUrl(baseUrl, api, cmd, signature):
    url = baseUrl + '?' + formattedCmd(api, cmd) + '&' + urllib.urlencode({'signature': signature})
    return url


def main():
    print 'ffffffffffffffffffffffffff'
    try:
        print getopt.getopt(sys.argv[1:], 'u:a:s:', ['help', 'output='])
        opts, args = getopt.getopt(sys.argv[1:], 'u:a:s:', ['help', 'output='])
        print opts, args,'print'
    except getopt.GetoptError, err:
        print str(err)
        sys.exit(2)

    baseUrl = 'http://10.176.14.26:8080/client/api'

    cmd = 'command=listTemplates'   
    temf= 'templatefilter=featured'
    api = 'Qo9Qwfatwz9ARB328Btn9PftzL2Cf5LOWd8OFyJmiM513tpTIm-zKxJoWkWqf353Df397xcLdKXGk8_JO8nM3Q'
    secret = '-kgkBuBUrGFeIC4gUvngSK_3Ypmi7fuF8XdVXIusnyyiEP2YUcG3FnPUGJGy3rp3Bw5ZNnqgS-9tIfyV1QnK1g'

    for o, a in opts:
        if o == '-u':
            cmd = a
        elif o == '-a':
            api = a
        elif o == '-s':
            secret = a
        else:
            assert False, 'unhandled option'

    newCmd = formattedCmd(api, cmd).lower()
    signature = encypt(newCmd, secret)
    url = formattedUrl(baseUrl, api, cmd, signature)

    print '\n' + url

if __name__ == '__main__':
    main()

This code runs, but doesn't do anything notable other than generate and print a URL.

Can you give us the exact error and the traceback on the code you were trying to run when you got the problem you mentioned?

when i paste the url in the browser, i should get an xml response showing list of templates in the cloudstack interface. but it is not working. you may not run this because you are not having the cloudstack.
I just want to know one thing that how can i pass the parameter 'templatefilter' in this code?

can you help me

thanks in advance

is the following line correct regarding to python?

cmd = 'command':'listTemplates', 'templatefilter':'executable'

after executed an error shown like :

c:\Python27>python cloudvm.py
File "cloudvm.py", line 41
cmd = 'command':'listTemplates', 'templatefilter':'executable'
               ^
SyntaxError: invalid syntax"

Looking at your code, I guess you just need to alter formattedCmd and formattedUrl to take temf as an additional parameter so you can add the parameter to the generated URL.
So perhaps something like this?

import getopt
import sys
import hmac
import hashlib
import base64
import urllib


def formattedCmd(api, cmd, temf):
    s = 'apiKey=' + api + '&' + cmd + '?' + temf
                # I don't know if this ^ should be ? or & or another character.
                # I'll leave you to work this out!
    return s


def encypt(string, key):
    h = hmac.new(key, string, hashlib.sha1)
    #  print '\n' + h.digest()
    return base64.b64encode(h.digest())


def formattedUrl(baseUrl, api, cmd, temf, signature):
    url = baseUrl + '?' + formattedCmd(api, cmd, temf) + '&' + urllib.urlencode({'signature': signature})
    return url


def main():
    print 'ffffffffffffffffffffffffff'
    try:
        print getopt.getopt(sys.argv[1:], 'u:a:s:', ['help', 'output='])
        opts, args = getopt.getopt(sys.argv[1:], 'u:a:s:', ['help', 'output='])
        print opts, args,'print'
    except getopt.GetoptError, err:
        print str(err)
        sys.exit(2)

    baseUrl = 'http://10.176.14.26:8080/client/api'

    cmd = 'command=listTemplates'   
    temf= 'templatefilter=featured'
    api = 'Qo9Qwfatwz9ARB328Btn9PftzL2Cf5LOWd8OFyJmiM513tpTIm-zKxJoWkWqf353Df397xcLdKXGk8_JO8nM3Q'
    secret = '-kgkBuBUrGFeIC4gUvngSK_3Ypmi7fuF8XdVXIusnyyiEP2YUcG3FnPUGJGy3rp3Bw5ZNnqgS-9tIfyV1QnK1g'

    for o, a in opts:
        if o == '-u':
            cmd = a
        elif o == '-a':
            api = a
        elif o == '-s':
            secret = a
        else:
            assert False, 'unhandled option'

    newCmd = formattedCmd(api, cmd, temf).lower()
    signature = encypt(newCmd, secret)
    url = formattedUrl(baseUrl, api, cmd, temf, signature)

    print '\n' + url

if __name__ == '__main__':
    main()

Is that what you were hoping to do?
In the above, the filter is appended to the URL immediately after the command.
I don't know how the web interface for CloudStack works, I've never used it. So I don't know how the URLs are supposed to be formed. Therefore I'm not sure what the correct syntax is to add parameters to the command in the URL, so I've just used a ? between the command and the parameter. I think I'll leave it to you to work out how to get the parameter correctly formatted for the URL.

Hopefully it's close to what you want!

EDIT:
Looking at this page:
http://www.shapeblue.com/2012/05/10/using-the-api-for-advanced-network-management/

I think the ? I added should be an &!

You are missing the curly braces for dictionary:

cmd = {'command':'listTemplates', 'templatefilter':'executable'}

Calling (procedural) function in Python example

def func(required, optional=None):
    print 'required = %s, optional = %s' % (required, optional)


func('something')
func('something', 'other')
func(optional='other', required='something')

"""Output:
required = something, optional = None
required = something, optional = other
required = something, optional = other
"""
commented: good +0

thanks JasonHippy, thanks for ur suggestion :)

but still error exists.
In the above code i have corrected myself some line as below.

  def main():
   print 'ffffffffffffffffffffffffff'
   try:
    print getopt.getopt(sys.argv[1:], 'u:a:t:s:', ['help', 'output='])
    opts, args = getopt.getopt(sys.argv[1:], 'u:a:t:s:', ['help', 'output='])
    print opts, args,'print'
except getopt.GetoptError, err:
    print str(err)
    sys.exit(3)

and the line below too..

 for o, a in opts:
    if o == '-u':
        cmd = a
    elif o == '-a':
         api = a
         elif o == '-t':
         tem = a
    elif o == '-s':
        secret = a
    else:
        assert False, 'unhandled option'

newCmd = formattedCmd(api, cmd, tem).lower()
signature = encypt(newCmd, secret)
url = formattedUrl(baseUrl, api, cmd, tem, signature)

when executed, it is showing the error,

 c:\Python27>python cloudvm.py
 File "cloudvm.py", line 53
  elif o == '-t':
   ^
SyntaxError: invalid syntax

please help.

line 6 is indented inproperly from second code part, as the error clearly indicates.

commented: good +0

can i pass the parameter 'templatefilter' to the cmd as below? is it correct?

cmd = {'command=listTemplates', 'templatefilter= executable'}

no, you are making cmd a set of strings,

cmd(command='listTemplates', templatefilter='executable')

like in my example.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.