Skip to content

Commit

Permalink
python2&3 compatibility changes
Browse files Browse the repository at this point in the history
Signed-off-by: Vikrant Balyan (vvb) <vvb@cisco.com>
  • Loading branch information
vvb committed Aug 23, 2018
1 parent cb4fd32 commit 63250ce
Show file tree
Hide file tree
Showing 14 changed files with 65 additions and 101 deletions.
2 changes: 1 addition & 1 deletion imcsdk/apis/admin/ipmi.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def ipmi_enable(handle, priv=CommIpmiLanConsts.PRIV_ADMIN,
Example:
if ipmi_enable(handle):
print "IPMI Enabled"
print("IPMI Enabled")
"""

# Verify key is a hex number
Expand Down
12 changes: 5 additions & 7 deletions imcsdk/apis/server/vmedia.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,14 @@
import time
import re
import logging
try:
from urllib.parse import urlsplit
except ImportError:
from urlparse import urlsplit

from imcsdk.mometa.comm.CommVMedia import CommVMedia
from imcsdk.mometa.comm.CommVMediaMap import CommVMediaMap
from imcsdk.imcexception import ImcOperationError
from imcsdk.apis.admin.ipmi import _get_comm_mo_dn

from six.moves import urllib

log = logging.getLogger('imc')

CIFS_URI_PATTERN = re.compile('^//\d+\.\d+\.\d+\.\d+\/')
Expand Down Expand Up @@ -293,9 +291,9 @@ def vmedia_mount_iso_uri(handle, uri, volume_name=None, user_id=None,
mount_options = "noauto"

# Set the Map based on the protocol
if urlsplit(uri).scheme == 'http':
if urllib.parse.urlsplit(uri).scheme == 'http':
mount_protocol = "www"
elif urlsplit(uri).scheme == 'https':
elif urllib.parse.urlsplit(uri).scheme == 'https':
mount_protocol = "www"
elif CIFS_URI_PATTERN.match(uri):
mount_protocol = "cifs"
Expand All @@ -304,7 +302,7 @@ def vmedia_mount_iso_uri(handle, uri, volume_name=None, user_id=None,
else:
# Raise ValueError and bail
raise ValueError("Unsupported protocol: " +
urlsplit(uri).scheme)
urllib.parse.urlsplit(uri).scheme)

# Use remote filename if no volume_name givien
if not volume_name:
Expand Down
2 changes: 1 addition & 1 deletion imcsdk/apis/v2/admin/ipmi.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def ipmi_enable(handle, priv=None, key=None, server_id=1):
Example:
if ipmi_enable(handle):
print "IPMI Enabled"
print("IPMI Enabled")
"""

# Verify key is a hex number
Expand Down
10 changes: 6 additions & 4 deletions imcsdk/apis/v2/server/vmedia.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
"""
import os
import time
import urlparse
import re
import logging

Expand All @@ -26,6 +25,9 @@
from imcsdk.imcexception import ImcOperationError
from imcsdk.apis.admin.ipmi import _get_comm_mo_dn

from six.moves import urllib


log = logging.getLogger('imc')

CIFS_URI_PATTERN = re.compile('^//\d+\.\d+\.\d+\.\d+\/')
Expand Down Expand Up @@ -302,9 +304,9 @@ def vmedia_mount_iso_uri(handle, uri, user_id=None, password=None,
mount_options = "noauto"

# Set the Map based on the protocol
if urlparse.urlsplit(uri).scheme == 'http':
if urllib.parse.urlsplit(uri).scheme == 'http':
mount_protocol = "www"
elif urlparse.urlsplit(uri).scheme == 'https':
elif urllib.parse.urlsplit(uri).scheme == 'https':
mount_protocol = "www"
elif CIFS_URI_PATTERN.match(uri):
mount_protocol = "cifs"
Expand All @@ -313,7 +315,7 @@ def vmedia_mount_iso_uri(handle, uri, user_id=None, password=None,
else:
# Raise ValueError and bail
raise ValueError("Unsupported protocol: " +
urlparse.urlsplit(uri).scheme)
urllib.parse.urlsplit(uri).scheme)

# Convert no user/pass to blank strings
if not user_id:
Expand Down
19 changes: 11 additions & 8 deletions imcsdk/imcbasetype.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,15 @@
from .imccore import BaseObject


import six


class Method(BaseObject):
"""This is Method class."""
def __init__(self, **kwargs):
BaseObject.__init__(self, "Method", "method")
if kwargs:
for n, v in kwargs.iteritems():
for n, v in six.iteritems(kwargs):
self.attr_set(n, v)


Expand All @@ -34,7 +37,7 @@ class ConfigConfig(BaseObject):
def __init__(self, **kwargs):
BaseObject.__init__(self, "ConfigConfig", "configConfig")
if kwargs:
for n, v in kwargs.iteritems():
for n, v in six.iteritems(kwargs):
self.attr_set(n, v)


Expand All @@ -43,7 +46,7 @@ class ConfigMap(BaseObject):
def __init__(self, **kwargs):
BaseObject.__init__(self, "ConfigMap", "configMap")
if kwargs:
for n, v in kwargs.iteritems():
for n, v in six.iteritems(kwargs):
self.attr_set(n, v)


Expand All @@ -52,7 +55,7 @@ class ConfigSet(BaseObject):
def __init__(self, **kwargs):
BaseObject.__init__(self, "ConfigSet", "configSet")
if kwargs:
for n, v in kwargs.iteritems():
for n, v in six.iteritems(kwargs):
self.attr_set(n, v)


Expand All @@ -65,7 +68,7 @@ def __init__(self, **kwargs):
self.error_descr = None
self.name = None
if kwargs:
for n, v in kwargs.iteritems():
for n, v in six.iteritems(kwargs):
self.attr_set(n, v)


Expand All @@ -74,7 +77,7 @@ class FailedMos(BaseObject):
def __init__(self, **kwargs):
BaseObject.__init__(self, "FailedMos", "failedMos")
if kwargs:
for n, v in kwargs.iteritems():
for n, v in six.iteritems(kwargs):
self.attr_set(n, v)


Expand All @@ -83,7 +86,7 @@ class FilterFilter(BaseObject):
def __init__(self, **kwargs):
BaseObject.__init__(self, "FilterFilter", "filter")
if kwargs:
for n, v in kwargs.iteritems():
for n, v in six.iteritems(kwargs):
self.attr_set(n, v)


Expand All @@ -93,6 +96,6 @@ def __init__(self, **kwargs):
BaseObject.__init__(self, "Pair", "pair")
self.key = None
if kwargs:
for n, v in kwargs.iteritems():
for n, v in six.iteritems(kwargs):
self.attr_set(n, v)

7 changes: 2 additions & 5 deletions imcsdk/imccoreutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,6 @@ def find_class_id_in_mo_meta_ignore_case(class_id):
return None
if class_id in MO_CLASS_ID:
return class_id
# print class_id
l_class_id = class_id.lower()
for key in MO_CLASS_ID:
if key.lower() == l_class_id:
Expand Down Expand Up @@ -272,10 +271,10 @@ def write_object(mo_or_list):
for mo in mo_or_list:
if (isinstance(mo, imcmo.ManagedObject) or
isinstance(mo, imcmo.GenericMo)):
print (mo)
print(mo)
elif (isinstance(mo_or_list, imcmo.ManagedObject) or
isinstance(mo_or_list, imcmo.GenericMo)):
print (mo_or_list)
print(mo_or_list)


def extract_molist_from_method_response(method_response,
Expand Down Expand Up @@ -387,8 +386,6 @@ def write_mo_tree(mo, level=0, depth=None, show_level=[],
else:
tree_dict[key_all_mo][mo.class_id].append(mo)

# print tree_dict

if print_tree:
if not show_level:
print("%s %s (%s)" % (level_indent, mo.dn, mo.class_id))
Expand Down
34 changes: 15 additions & 19 deletions imcsdk/imcdriver.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,19 @@
import sys
import socket
import ssl
import logging

try:
import urllib2
import httplib
from urllib2 import HTTPError
except:
import urllib.request as urllib2
import http.client as httplib
from urllib.error import HTTPError

from six.moves import urllib as urllib2
from six.moves import http_client as httplib
from six.moves.urllib import request as Request
from six.moves.urllib.error import HTTPError
from six.moves.urllib.request import HTTPRedirectHandler, HTTPSHandler

import logging

log = logging.getLogger('imc')


class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
class SmartRedirectHandler(HTTPRedirectHandler):
"""This class is to handle redirection error."""

def http_error_301(self, req, fp, code, msg, headers):
Expand All @@ -47,11 +43,11 @@ def http_error_302(self, req, fp, code, msg, headers):
return resp_status


class TLS1Handler(urllib2.HTTPSHandler):
class TLS1Handler(HTTPSHandler):
"""Like HTTPSHandler but more specific"""

def __init__(self):
urllib2.HTTPSHandler.__init__(self)
HTTPSHandler.__init__(self)

def https_open(self, req):
return self.do_open(TLS1Connection, req)
Expand Down Expand Up @@ -85,11 +81,11 @@ def connect(self):
ssl_version=ssl.PROTOCOL_TLSv1)


class TLSHandler(urllib2.HTTPSHandler):
class TLSHandler(HTTPSHandler):
"""Like HTTPSHandler but more specific"""

def __init__(self):
urllib2.HTTPSHandler.__init__(self)
HTTPSHandler.__init__(self)

def https_open(self, req):
return self.do_open(TLSConnection, req)
Expand Down Expand Up @@ -225,7 +221,7 @@ def __create_request(self, uri, data=None):
web request object
"""

request_ = urllib2.Request(url=uri, data=data)
request_ = Request.Request(url=uri, data=data)
headers = self.__headers
for header in headers:
request_.add_header(header, headers[header])
Expand Down Expand Up @@ -259,7 +255,7 @@ def post(self, uri, data=None, dump_xml=False, read=True, timeout=None):
if dump_xml:
log.debug('%s ====> %s' % (uri, data))

opener = urllib2.build_opener(*self.__handlers)
opener = Request.build_opener(*self.__handlers)
try:
response = opener.open(request, timeout=timeout)
except Exception as e:
Expand All @@ -273,7 +269,7 @@ def post(self, uri, data=None, dump_xml=False, read=True, timeout=None):

# Fallback to TLSv1 for this server
self.update_handlers(tls_proto="tlsv1")
opener = urllib2.build_opener(*self.__handlers)
opener = Request.build_opener(*self.__handlers)
response = opener.open(request, timeout=timeout)

if type(response) is list:
Expand All @@ -286,7 +282,7 @@ def post(self, uri, data=None, dump_xml=False, read=True, timeout=None):
if dump_xml:
log.debug('%s <==== %s' % (uri, data))

opener = urllib2.build_opener(*self.__handlers)
opener = Request.build_opener(*self.__handlers)
response = opener.open(request, timeout=timeout)
# response = urllib2.urlopen(request)
if read:
Expand Down
11 changes: 4 additions & 7 deletions imcsdk/imceventhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,13 @@

from __future__ import print_function

try:
from Queue import Queue
except:
from queue import Queue

from threading import Condition, Lock, Thread
import datetime
import logging
import time

from threading import Condition, Lock, Thread
from six.moves import queue

from . import imcmo
from . import imccoreutils
from . import imcxmlcodec as xc
Expand Down Expand Up @@ -64,7 +61,7 @@ def __init__(self, params, fmce, capacity, callback):
self.params = params
self.overflow = False
self.error_code = 0 # TODO:error_code to call notify as per PowerTool
self.event_q = Queue() # infinite size Queue
self.event_q = queue.Queue() # infinite size Queue

def dequeue(self, miliseconds_timeout):
"""Internal method to dequeue the events."""
Expand Down
4 changes: 2 additions & 2 deletions imcsdk/imcfilter.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def and_operator(toks):
"""

# print str, loc, toks
# print toks[0][0::2]
# print(toks[0][0::2])
and_filter = AndFilter()
for op_filter in toks[0][0::2]:
and_filter.child_add(op_filter)
Expand All @@ -102,7 +102,7 @@ def or_operator(toks):
"""

# print str, loc, toks
# print toks[0][0::2]
# print(toks[0][0::2])
or_filter = OrFilter()
for op_filter in toks[0][0::2]:
or_filter.child_add(op_filter)
Expand Down
Loading

0 comments on commit 63250ce

Please sign in to comment.