首页 新闻 会员 周边 捐助

django随笔

0
悬赏园豆:5 [已关闭问题] 关闭于 2015-05-06 14:27
def build(request):
    buildinfo = request.POST
    user = request.user
    buildinfo.user = user.username.lower()
    buildinfo.service_id = buildinfo['id']
    rootpath = os.path.abspath(__file__ + '/../../../') + os.path.sep
    username = buildinfo['svn_account']
    password = buildinfo['svn_password']
    username = username[0:1] + username[1:].upper()
    config_svn_url = buildinfo['config_svn_url']
    # 判断是否为svn路径
    if not config_svn_url.startswith("http://"):
        if config_svn_url.startswith("/"):
            config_svn_url = config_svn_url[1:]
        if config_svn_url.endswith("/"):
            config_svn_url = buildinfo['branch_svn_urls'] + config_svn_url
        else:
            config_svn_url = buildinfo['branch_svn_urls'] + '/' + config_svn_url

    conf_path = os.path.abspath(__file__ + '/../../conf/') + os.path.sep + buildinfo['name']
    # 判断conf文件夹下边是否有service_name为名的文件夹
    service_path = os.path.abspath(__file__ + '/../../conf/') + os.path.sep + buildinfo['name']
    if os.path.exists(service_path):
        shutil.rmtree(service_path)

    cmdStr = "svn.bat export {config_svn_url} {conf_path} --username {username} --password {password}".format(
        config_svn_url=config_svn_url, conf_path=conf_path, username=username, password=password)
    logger.info(cmdStr)
    childPro = subprocess.Popen(cmdStr, stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
    std_out_data, std_err_data = childPro.communicate()
问题补充:
if std_err_data != None:
        logger.error("svn export error")
        return HttpResponse(json.dumps({'err': std_err_data}), content_type='application/json')
    else:
        logger.info("svn export success")
        project_path = conf_path + '\\project.xml'
        try:
            projectfile = open(project_path, 'r')
        except Exception:
            return HttpResponse(
                json.dumps({'err': True, "message": 'Can not open file.'}),
                content_type='application/json')
        buildArr = []
        for b in buildinfo['build_template[]'].split(","):
            buildFile = b.split('^')[1]
            if not buildFile.endswith('.xml'):
                buildFile = buildFile + '.xml'
            buildArr.append(conf_path +'\\' + buildFile)
        resultFile = projectfile
        for file in buildArr:
            try:
                sfile = open(file, 'r')
            except Exception:
                return HttpResponse(
                    json.dumps({'err': True, "message": 'Can not open file.'}),
                    content_type='application/json')

            # 合并xml文件
            resultFile = merger(resultFile, 'project', sfile, 'job', 'build')
            sfile.close()
Klaus.Fenng的主页 Klaus.Fenng | 初学一级 | 园豆:199
提问于:2015-05-05 17:38
< >
分享
所有回答(1)
0
logger.info("merge file ok!")
        newProjectFile = conf_path + '\\' + buildinfo['name'] + '.xml'
        try:
            project_file = open(newProjectFile, 'w')
        except Exception:
            return HttpResponse(
                json.dumps({'err': True, "message": 'Can not write file.'}),
                content_type='application/json')
        writer = codecs.lookup('utf-8')[3](project_file)
        resultFile.writexml(writer, encoding='utf-8')
        writer.close()
        project_file.close()
        logger.info("write project xml file ok!")
        url = 'http://' + buildinfo['master_ip'] + ':' + buildinfo['master_port'] + '/rest/projects/start'
Klaus.Fenng | 园豆:199 (初学一级) | 2015-05-05 17:47
dataDict = {
            "data": {
                "trigger": request.user.username,
                "proj_conf_file":
                    conf_path + '\\' + buildinfo['name'] + '.xml',
                "task_conf_file": conf_path  + '\\taskconf.xml',
                "proj_conf_content": open(conf_path +'\\' + buildinfo['name'] + '.xml').read(),
                "task_conf_content": open(conf_path + '\\taskconf.xml').read(),
                "properties": {
                    "SVN_REVISION": buildinfo['revision'],
                    "PACKAGE_ADDRESS": buildinfo['package_address']

                }
            }
        }
        for pro in buildinfo["properties"].split(" "):
            if pro != "":
                proArr = pro.split("=")
                dataDict["data"]["properties"][proArr[0]] = proArr[1]
        head = {'content-type': 'application/json'}
        out = requests.post(url, data=json.dumps(dataDict), headers=head)

 

支持(0) 反对(0) Klaus.Fenng | 园豆:199 (初学一级) | 2015-05-05 17:48

@Klaus.Fenng: 

if json.loads(out.content):
            logger.info("get build result ok")
            content = json.loads(out.content)
            if content["errno"] == 0:
                logger.info("panda build success")
                data = content["data"]
                save_detail(data, request)
                return HttpResponse(json.dumps({'err': False}), content_type='application/json')
            else:
                logger.info("panda build failed")
                return HttpResponse(
                    json.dumps({'err': True, "message": 'Internal error, please check the configuration'}),
                    content_type='application/json')
支持(0) 反对(0) Klaus.Fenng | 园豆:199 (初学一级) | 2015-05-05 17:48

@Klaus.Fenng: 

def get_build_info_from_uci(options):
    # import urllib
    # import urllib2

    result = ''
    # data = urllib.urlencode(options)
    url = 'http://' + options['hostname'] + ':' + str(options['port']) + options['path']
    result = requests.get(url, )
    if result.status_code is 200:
        return {"err": False, "data": result}
    else:
        return {"err": True, "data": None}
        # req = urllib2.Request(url)
        # resp>
支持(0) 反对(0) Klaus.Fenng | 园豆:199 (初学一级) | 2015-05-05 17:49

@Klaus.Fenng: 

def read_status_from_uci(master_ip, build_id, service_name):
    option = {"hostname": master_ip,
              "port": 3000,
              "path": '/rest/projects/' + service_name + '/buildid/' + build_id + '/buildinfo',
              "method": "GET",
              "headers": {
                  "Content-Type": "application/x-www-form-urlencoded"
              }
    }

    while (True):
        logger.info("begin to query status")
        result = get_build_info_from_uci(option)
        if result['err']:
            return ''
        else:
            re = json.loads(result['data'].content)
            if re['errno']:
                logger.error(result.data['message'])
支持(0) 反对(0) Klaus.Fenng | 园豆:199 (初学一级) | 2015-05-05 17:50

@Klaus.Fenng: 

else:
                data = re['data']
                if result['err']:
                    return ''
                else:
                    Build.objects.filter(build_id=data['build_id']).update(status=data['status'],
                                                                           start_time=data['start_time'],
                                                                           exit_code=data['exit_code'],
                                                                           trigger=data['trigger'],
                                                                           run_time=data['run_time'])
                    if data['status'] == 'RUNNING' or data['status'] == 'WAITING':
                        time.sleep(5)
                    if data['status'] == 'FINISH' or data['status'] == 'FAILED':
                        break
支持(0) 反对(0) Klaus.Fenng | 园豆:199 (初学一级) | 2015-05-05 17:50

@Klaus.Fenng: 

python发送邮件示例

import sys   
import smtplib
from email.mime.multipart import MIMEMultipart  
from email.mime.text import MIMEText
from xlrd import open_workbook

def sendMail(toUser,file):
    data = readFromXls(file)
    emailContent = makeMailContent(data)
    
    msgRoot = MIMEMultipart('related')  
    msgRoot['From'] = 'pmail_udeck@notesmail.huawei.com'
    msgRoot['To'] = toUser    
    msgRoot['Subject'] = 'this is a email from python demo'
      
    msgText = MIMEText(emailContent,'html','gbk')  
    msgRoot.attach(msgText) 

    smtp = smtplib.SMTP()    
    smtp.connect("smtpscn.huawei.com")    
    smtp.login('pmail_udeck', 'Uci-12345')    
    smtp.sendmail('pmail_udeck@notesmail.huawei.com', toUser, msgRoot.as_string())    
    smtp.quit()  

def readFromXls(file):
 
    book = open_workbook(file)    
    sheet = book.sheet_by_index(0)
    data = []
    print sheet
 
    for row in range(15):
        values = []
        for col in range(1,11):
            values.append(sheet.cell(row,col).value)
        
        data.append(values)
支持(0) 反对(0) Klaus.Fenng | 园豆:199 (初学一级) | 2015-05-06 10:55

@Klaus.Fenng: 

for row in range(26,39):
        for col in range(11):
            cel = sheet.cell(row,col).value
    
    return data

def makeMailContent(data):
    htmlStr = "<table  style='border-collapse:collapse;font-size:12px;\
  padding:5px;color:#195d84' border='1' bordercolor='adc9da'>"
    for row in data:
        htmlStr = htmlStr + "<tr>"
        for col in row:
            info = col
            if isinstance(col, unicode):
                info = col.encode('gbk')
            else:
                info = str(col)
            htmlStr = htmlStr + "<td>" + info + "</td>"
        htmlStr = htmlStr + "</tr>"
    
    htmlStr = htmlStr + "</table>"
    #print htmlStr
    return htmlStr

if __name__ == "__main__":
    toUser = sys.argv[1]
    file = sys.argv[2]
    sendMail(toUser,file)
支持(0) 反对(0) Klaus.Fenng | 园豆:199 (初学一级) | 2015-05-06 10:56

@Klaus.Fenng: 

 1 # -*- coding: utf-8 -*-
 2 from django.db import models
 3 from cube.workspace.models import Workspace
 4 from cube.pubauth.models import User
 5 
 6 
 7 class Service(models.Model):
 8     id = models.AutoField(primary_key=True)
 9     name = models.CharField(max_length=1024)
10     product_line = models.CharField(max_length=1024)
11     product = models.CharField(max_length=1024)
12     version_r = models.CharField(max_length=1024)
13     version_c = models.CharField(max_length=1024)
14     master_ip = models.CharField(max_length=1024)
15     master_port = models.CharField(max_length=1024)
16     svn_account = models.CharField(max_length=1024)
17     svn_password = models.CharField(max_length=1024)
18     base_svn_url = models.URLField()
19     branch_svn_urls = models.CharField(max_length=1024, default='')
20     config_svn_url = models.CharField(max_length=1024, default='')
21     package_address = models.CharField(max_length=1024, default='')

model模块

支持(0) 反对(0) Klaus.Fenng | 园豆:199 (初学一级) | 2015-05-06 14:25

@Klaus.Fenng: 

 1 build_template = models.CharField(max_length=1024, default='')
 2     workspace = models.ForeignKey(Workspace)
 3     author = models.ForeignKey(User, to_field='username')
 4     create_time = models.CharField(max_length=1024)
 5     properties = models.CharField(max_length=1024, default='')
 6     enable_user = models.CharField(max_length=1024, default='')
 7     visible_user = models.CharField(max_length=1024, default='')
 8 
 9     def __unicode__(self):
10         return self.name
11 class Properties(models.Model):
12     pass
13 
14 class Build(models.Model):
15     no = models.CharField(max_length=1024)
16     user = models.ForeignKey(User, to_field='username')
17     branch_svn_urls = models.CharField(max_length=1024)
18     build_id = models.CharField(max_length=1024)
19     master_ip = models.CharField(max_length=1024)
20     master_port = models.CharField(max_length=1024)
21     package_address = models.CharField(max_length=1024)
22     product_line = models.CharField(max_length=1024)
23     product = models.CharField(max_length=1024)
24     version_r = models.CharField(max_length=1024)
25     version_c = models.CharField(max_length=1024)
26     reversion = models.CharField(max_length=1024)
27     service = models.ForeignKey(Service, to_field='id')
28     service_name = models.CharField(max_length=1024)
29     start_time = models.CharField(max_length=1024)
30     status = models.CharField(max_length=1024)
31     task_path = models.CharField(max_length=1024)
32     trigger = models.CharField(max_length=1024)
33     run_time = models.CharField(max_length=1024, default=0)
34     exit_code = models.CharField(max_length=5, default='')
35     properties = models.CharField(max_length=1024, default=0)
支持(0) 反对(0) Klaus.Fenng | 园豆:199 (初学一级) | 2015-05-06 14:26

@Klaus.Fenng: 

 1 def copy_value_from_post(self, request):
 2         self.user = request.user
 3         self.service_name = request.POST['name']
 4         self.master_ip = request.POST['master_ip']
 5         self.revision = request.POST['revision']
 6         self.product = request.POST['product']
 7         self.version_c = request.POST['version_c']
 8         self.version_r = request.POST['version_r']
 9         self.branch_svn_urls = request.POST['branch_svn_urls']
10         self.package_address = request.POST['package_address']
11         self.properties = request.POST['properties']
12         self.build_template = request.POST['build_template[]']
13         self.product_line = request.POST['product_line']
14         self.config_svn_url = request.POST['config_svn_url']
15         self.service_id = request.POST['id']
16         self.master_port = request.POST['master_port']
17         self.config_svn_url = request.POST['config_svn_url']
18 
19 
20     def __unicode__(self):
21         return self.build_id + self.service_name + self.workspace
支持(0) 反对(0) Klaus.Fenng | 园豆:199 (初学一级) | 2015-05-06 14:27

@Klaus.Fenng: 

python线程怎么用

 1 #-*- coding: utf-8 -*-
 2 
 3 import threading
 4 
 5 def thread_test():
 6     t = threading.Thread(target=demo_print,name='thread_test',args=(),)
 7     
 8     print ('threading is ready to start' + "\n")
 9     t.start()
10  
11 def demo_print():
12     print ('threading is startttttttttttttt')
13     
14 if __name__ == "__main__":
15     thread_test()
支持(0) 反对(0) Klaus.Fenng | 园豆:199 (初学一级) | 2015-05-06 14:47
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册