From 930f9ddb757c299378381e3f87e1e00539fa71b0 Mon Sep 17 00:00:00 2001 From: cclauss Date: Thu, 29 Mar 2018 12:59:00 +0200 Subject: [PATCH] Modernize Python 2 code to get ready for Python 3 --- .travis.yml | 13 +++++++++- adminset/ldap.py | 20 ++++++++-------- cmdb/api.py | 4 ++-- cmdb/asset.py | 24 +++++++++++-------- delivery/tasks.py | 2 +- install/client/adminset_agent.py | 41 ++++++++++++++++---------------- requirements.txt | 4 ++-- 7 files changed, 61 insertions(+), 47 deletions(-) diff --git a/.travis.yml b/.travis.yml index b19e5644..8a9694e7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,18 @@ language: python python: - "2.7" + - "3.6" +matrix: + allow_failures: + - python: "3.6" # command to install dependencies -install: "pip install -r requirements.txt" +install: + - "pip install -r requirements.txt" + - "pip install flake8" +before_script: + # stop the build if there are Python syntax errors or undefined names + - flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics + # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide + - flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics # command to run tests script: pytest test.py diff --git a/adminset/ldap.py b/adminset/ldap.py index ef97fdef..8f46012d 100644 --- a/adminset/ldap.py +++ b/adminset/ldap.py @@ -22,8 +22,8 @@ def __init__(self,ldap_host=None,base_dn=None,user=None,password=None): try: self.ldapconn = ldap.open(ldap_host) self.ldapconn.simple_bind(user,password) - except ldap.LDAPError,e: - print e + except ldap.LDAPError as e: + print(e) #根据表单提交的用户名,检索该用户的dn,一条dn就相当于数据库里的一条记录。 #在ldap里类似cn=username,ou=users,dc=gccmx,dc=cn,验证用户密码,必须先检索出该DN @@ -48,8 +48,8 @@ def ldap_search_dn(self,uid=None): return result_data[0][0] else: return None - except ldap.LDAPError, e: - print e + except ldap.LDAPError as e: + print(e) #查询用户记录,返回需要的信息 def ldap_get_user(self,uid=None): @@ -69,8 +69,8 @@ def ldap_get_user(self,uid=None): return result else: return None - except ldap.LDAPError, e: - print e + except ldap.LDAPError as e: + print(e) #用户验证,根据传递来的用户名和密码,搜索LDAP,返回boolean值 def ldap_get_vaild(self,uid=None,passwd=None): @@ -81,8 +81,8 @@ def ldap_get_vaild(self,uid=None,passwd=None): return True else: return False - except ldap.LDAPError,e: - print e + except ldap.LDAPError as e: + print(e) #修改用户密码 def ldap_update_pass(self,uid=None,oldpass=None,newpass=None): @@ -93,5 +93,5 @@ def ldap_update_pass(self,uid=None,oldpass=None,newpass=None): obj.simple_bind_s(target_cn,oldpass) obj.passwd_s(target_cn,oldpass,newpass) return True - except ldap.LDAPError,e: - return False \ No newline at end of file + except ldap.LDAPError: + return False diff --git a/cmdb/api.py b/cmdb/api.py index 11ae670b..af3358d2 100644 --- a/cmdb/api.py +++ b/cmdb/api.py @@ -14,7 +14,7 @@ try: import json -except ImportError, e: +except ImportError: import simplejson as json @@ -191,4 +191,4 @@ def get_group(request): ret_hg['members'].append(ret_h) d.append(ret_hg) return HttpResponse(json.dumps(d)) - return HttpResponse(status=403) \ No newline at end of file + return HttpResponse(status=403) diff --git a/cmdb/asset.py b/cmdb/asset.py index efd16852..1dfddb5a 100644 --- a/cmdb/asset.py +++ b/cmdb/asset.py @@ -1,20 +1,24 @@ #! /usr/bin/env python # -*- coding: utf-8 -*- -from forms import AssetForm -from models import Host, Idc, HostGroup, ASSET_STATUS, ASSET_TYPE -from django.shortcuts import render, HttpResponse -from django.db.models import Q -from cmdb.api import get_object -from cmdb.api import pages, str2gb import csv import datetime -from django.contrib.auth.decorators import login_required +import sys + from accounts.permission import permission_verify +from cmdb.api import get_object, pages, str2gb from config.views import get_dir -import sys -reload(sys) -sys.setdefaultencoding('utf8') +from django.contrib.auth.decorators import login_required +from django.db.models import Q +from django.shortcuts import HttpResponse, render +from forms import AssetForm +from models import ASSET_STATUS, ASSET_TYPE, Host, HostGroup, Idc + +try: + reload(sys) # Python 2 + sys.setdefaultencoding('utf8') +except NameError: + pass # Python 3 @login_required() diff --git a/delivery/tasks.py b/delivery/tasks.py index 01f38d27..add4a7c4 100644 --- a/delivery/tasks.py +++ b/delivery/tasks.py @@ -30,7 +30,7 @@ def deploy(job_name, server_list, app_path, source_address, project_id, auth_inf if p1.build_clean or p1.version: try: shutil.rmtree("{0}code/".format(job_workspace)) - except StandardError as msg: + except Exception as msg: print("code dir is not exists, build clean over") if p1.job_name.source_type == "git": cmd = git_clone(job_workspace, auth_info, source_address, p1) diff --git a/install/client/adminset_agent.py b/install/client/adminset_agent.py index 875248e8..ccb83522 100755 --- a/install/client/adminset_agent.py +++ b/install/client/adminset_agent.py @@ -21,29 +21,29 @@ print("begining install psutil module, please waiting") p = Popen('pip install psutil==5.2.2', stdout=PIPE, shell=True) stdout, stderr = p.communicate() - print stdout + print(stdout) import psutil try: import schedule except ImportError as msg: - print msg + print(msg) print("------------------------------------------------") print("begining install schedule module, please waiting") p = Popen('pip install schedule==0.4.3', stdout=PIPE, shell=True) stdout, stderr = p.communicate() - print stdout + print(stdout) import schedule try: import requests except ImportError as msg: - print msg + print(msg) print("------------------------------------------------") print("begining install schedule module, please waiting") p = Popen('pip install requests==2.17.3', stdout=PIPE, shell=True) stdout, stderr = p.communicate() - print stdout + print(stdout) import requests @@ -145,11 +145,11 @@ def post_data(url, data): try: r = requests.post(url, data) if r.text: - print r.text + print(r.text) else: print("Server return http status code: {0}".format(r.status_code)) - except StandardError as msg: - print msg + except Exception as msg: + print(msg) return True @@ -175,9 +175,9 @@ def asset_info(): def asset_info_post(): osenv = os.environ["LANG"] os.environ["LANG"] = "us_EN.UTF8" - print 'Get the hardwave infos from host:' - print asset_info() - print '----------------------------------------------------------' + print('Get the hardwave infos from host:') + print(asset_info()) + print('----------------------------------------------------------') post_data("http://{0}/cmdb/collect".format(server_ip), asset_info()) os.environ["LANG"] = osenv return True @@ -277,18 +277,17 @@ def get_net_info(): def agg_sys_info(): - print 'Get the system infos from host:' - sys_info = dict() - sys_info['hostname'] = platform.node() - sys_info['cpu'] = get_sys_cpu() - sys_info['mem'] = get_sys_mem() - sys_info['disk'] = get_sys_disk() - sys_info['net'] = get_net_info() - sys_info['token'] = token + print('Get the system infos from host:') + sys_info = {'hostname': platform.node(), + 'cpu': get_sys_cpu(), + 'mem': get_sys_mem(), + 'disk': get_sys_disk(), + 'net': get_net_info(), + 'token': token} - print sys_info + print(sys_info) json_data = json.dumps(sys_info) - print '----------------------------------------------------------' + print('----------------------------------------------------------') post_data("http://{0}/monitor/received/sys/info/".format(server_ip), json_data) return True diff --git a/requirements.txt b/requirements.txt index 12b50029..b5393652 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,6 @@ django==1.11.9 sh==1.12.9 -mysql-python==1.2.5 +mysqlclient==1.3.12 pytest==3.0.7 celery==4.0.2 django-celery-beat==1.0.1 @@ -10,4 +10,4 @@ psutil==5.2.2 schedule==0.4.3 pymongo==3.3.0 requests==2.11.1 -django-db==0.0.7 \ No newline at end of file +django-db==0.0.7