def request(self, *args, **kwargs): kwargs.setdefault('headers', kwargs.get('headers', {})) kwargs['headers']['User-Agent'] = self.USER_AGENT kwargs['headers']['Accept'] = self.accept kwargs['headers']['Accept-Charset'] = self.encoding if 'body' in kwargs: kwargs['headers']['Content-Type'] = self.content_type if '/json' in self.content_type: kwargs['body'] = json.dumps(kwargs['body']) else: kwargs['body'] = urlencode(kwargs['body']) LOG.debug('sending request: %s || %s', args, kwargs) resp, body = super(HTTPClient, self).request(*args, **kwargs) content_type = resp.get('content-type') # may not be the same as ['headers']['Accept'] if body and content_type: body = self._extra_body(content_type, body) if resp.status in (400, 401, 403, 404, 408, 409, 413, 500, 501): raise exceptions.from_response(resp, body) return resp, body
def create_slug(): ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 8)) LOG.info(ran_str) if check_slug(ran_str): return create_slug() else: return ran_str
def sysbench_run_job(param): # ips,threads,times,numberoftest,interval sbjob = param[0] dbhosts= sbjob.dbhosts sbhost = sbjob.sbhost threads=eval(sbjob.threads) times=int(sbjob.times) numberoftest=int(sbjob.numberoftest) interval=int(sbjob.interval) f = open("job1.txt","w") x = PrettyTable(["ip", "threads", "times", "No.", "tps","qps","avgLatency","%%user","%%nice","%%system","%%iowait","%%steal","%%idle"]) for ip in dbhosts.keys(): for t in threads: for i in xrange(1,numberoftest + 1): LOG('GREEN','Perform %dth/%s test(ip=%s,threads=%d,times=%d)'%(i,numberoftest,ip,t,times)) param=(dbhosts[ip],sbhost,t,times) result = sysbench_run(param) print result row= [ip,t,times,i] + list(result) print row x.add_row(row) f.write(str(row)) LOG('GREEN','Sleep %d seconds'%(interval)) time.sleep(interval) print x f.close()
def run_commander(param): hosts = param[0] cmd = param[1] for h in hosts.values(): LOG('GREEN', '=' * 60) LOG('GREEN', 'Target Host:%s' % (h.ip)) rssh = ssh(h.ip, user=h.user, passwd=h.passwd) rssh.ssh_run(cmd)
def change_root_passwd(param): hosts = param[0] new_pwd = param[1] for h in hosts.values(): print h LOG('GREEN', 'Target Host:%s' % (h.ip)) rssh = ssh(h.ip, h.user, passwd=h.passwd) # 修改root密码* LOG('GREEN', 'Set the root user password') rssh.ssh_run("echo '%s'|sudo passwd --stdin root" % (new_pwd))
def create_policy( org_id, app_name, sources_dict, sinks_dict, methods_list, files_loc_list, policy_file, ): """Method to create a sample policy file for the app""" if os.path.exists(policy_file): LOG.info(f"WARNING: {policy_file} would be overwritten") with open(policy_file, mode="w") as fp: fp.write(POLICY_TEMPLATE) fp.write("#" * 79 + "\n") fp.write("# Sink methods #\n") fp.write("#" * 79 + "\n") for category, sinks_list in sinks_dict.items(): fp.write("\n") fp.write("#" * 79 + "\n") fp.write(f"# Category {category} #\n") fp.write("#" * 79 + "\n") for sink in sorted(sinks_list): fp.write(CHECK_METHOD_TEMPLATE % dict(method_name=sink)) fp.write("#" * 79 + "\n\n") fp.write("#" * 79 + "\n") fp.write("# All methods (Uncomment as needed) #\n") fp.write("#" * 79 + "\n") for method in sorted(methods_list): fp.write("# " + CHECK_METHOD_TEMPLATE % dict(method_name=method)) console.print( Panel( f"Sample policy file [bold]{policy_file}[/bold] created successfully.\nEdit this file and include only the required methods.\nThen, to use this policy perform the below steps as a ShiftLeft administrator", title="ShiftLeft Policy Generator", expand=False, )) policy_label = app_name.replace("-", "_") md = Markdown(f""" ``` sl policy validate {policy_file} sl policy push {policy_label} {policy_file} sl policy assignment set --project {app_name} {org_id}/{policy_label}:latest # Or to make the policy the default for your organization # sl policy assignment set {org_id}/{policy_label}:latest ``` """) console.print(md) console.print(f"Then perform sl analyze as normal\n") console.print( Panel( f"Using this policy file as-is would suppress all findings for {app_name}!", title="NOTE", expand=False, ))
def logout(request): ''' ##用户登出 --- **参数说明** ''' user = request.user user.session_key = None user.save() django_logout(request) LOG.debug(user.session_key) return Response({'message': '您已安全退出'})
def _extra_body(self, content_type, body): if '/xml' in content_type: try: return str_to_xml_tree(body) except ValueError: LOG.debug('can not extra body as XML ElementTree: %s', body) if '/json' in content_type: try: return json.loads(body) except ValueError: LOG.debug('can not dump body as JSON: %s', body) return body # nothing changed
def my_exception_handler(exc, context): # 200 will never be here # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) if response is None: # force 500 to 200, for the same error msg format exc_info = sys.exc_info() LOG.exception(exc) return Response({'error_code': 500, 'error': u'服务器繁忙,请稍后再试'}) # add the HTTP status code to the response & force 200 return Response({ 'error_code': response.status_code, 'error': response.data.get('detail') })
def comment_page(request, page_id): page = get_object_or_404(Page, id=page_id) if request.method == 'POST': content = request.POST.getlist('content') try: comment = PageComment(user=request.user, content=content) except Exception, e: LOG.exception(e) messages.error(request, _(u'输入错误,请重新输入')) else: for c in comments: c.save() order.comment_time = django_now() order.save() messages.success(request, _(u'评论完成,已经添加到产品详细页面中。')) return redirect('/order/%s/' % order_id)
def utc2local(utc_datetime, utc_format='%Y-%m-%dT%H:%M:%SZ'): ''' The DateTime format of UTC is not the same even in the same OpenStack: - instance: %Y-%m-%dT%H:%M:%SZ - volume: %Y-%m-%d %H:%M:%S - swift: %Y-%m-%dT%H:%M:%S.%f (eg: 2012-06-26T08:44:09.557970) ''' try: if isinstance(utc_datetime, unicode) or isinstance(utc_datetime, str): utc_datetime = datetime.strptime(utc_datetime.replace(' ', ''), utc_format) utc_dt = pytz.utc.localize(utc_datetime) local_dt = LOCAL_TIME_ZONE.normalize(utc_dt.astimezone(LOCAL_TIME_ZONE)) return local_dt except Exception, e: LOG.error(e) return utc_datetime
def uninstall_mysql(hosts): for hostinfo in hosts: LOG('GREEN','Target Host:%s'%(hostinfo[0])) rssh = ssh(hostinfo,ROOT_USER,passwd=ROOT_USER_PASSWORD) # 关闭mysql数据库 rssh.ssh_run("pkill -9 mysql") # 卸载MySQL软件 for pkg in mysqlInstallPkgs: LOG('GREEN','UnInstall MySQL Package: %s'%pkg) rtn = rssh.ssh_run('rpm -e %s'%pkg[:-4]) # 删除数据文件和配置文件 rssh.ssh_run("rm -rf /opt/huawei/db") rssh.ssh_run("rm /etc/my.cnf") # 删除mysql安装文件 rssh.ssh_run("rm -rf /root/source")
def put(self, request): ''' Load request data into request.PUT refs: https://bitbucket.org/jespern/django-piston/src/c4b2d21db51a/piston/utils.py ''' if hasattr(request, '_post'): del request._post del request._files try: request.method = 'POST' request._load_post_and_files() request.method = 'PUT' except AttributeError, e: LOG.exception(e) request.META['REQUEST_METHOD'] = 'POST' request._load_post_and_files() request.META['REQUEST_METHOD'] = 'PUT'
def fixEnv(hosts): for hostinfo in hosts: LOG('GREEN', 'Target Host:%s' % (hostinfo[0])) rssh = ssh(hostinfo, ROOT_USER, passwd=ROOT_USER_PASSWORD) # 检查安装环境是否具备 # 判断/opt/huawei目录是否挂载 LOG('GREEN', 'Check if mount point /opt/huawei is exists') rtn = rssh.ssh_run(testMountCmd) if int(rtn.split(_mess_part)[1]) < 1: # 挂载磁盘/opt/huawei LOG('GREEN', 'Begin to Create Mount Point:/opt/huawei') rssh.ssh_run("mkfs.ext4 /dev/nvme1n1") rssh.ssh_run("mkdir -p /opt/huawei") rssh.ssh_run("mount /dev/nvme1n1 /opt/huawei") # 安装os相关包 for pkg in osDependencePkgs: LOG('GREEN', 'Install OS Dependence Package:%s' % (pkg)) rssh.ssh_run('yum -y install %s' % (pkg))
def _login_user(request, user): if not user.is_active: raise ParseError(u'你的账户有异常,请联系客服%s' % '正午') django_login(request, user) limit = 5 # 如果没有session_key尝试写入5次 while not request.session.session_key: LOG.warn('session is empty, try=%d', limit) for k, v in request.session.iteritems(): LOG.warn('%s = %s', k, v) django_logout(request) django_login(request, user) if not request.session.get('has_session'): request.session['has_session'] = True limit -= 1 if limit < 0: break user.session_key = request.session.session_key user.save() return UserSerializer(user).data
def start_slave_process(param): dbhosts = param[0] for h in dbhosts.values(): cnx = mysql.connector.connect(user=h.user, password=h.passwd,host=h.ip,database='test') cur = cnx.cursor() query = "show slave status" cur.execute(query) for (f1) in cur: Slave_IO_Running = f1[10] Slave_SQL_Running = f1[11] if Slave_IO_Running == "No" and Slave_SQL_Running == "No": # 启动MySQL的slave进程 LOG('GREEN','Start MySQL Slave Process:%s'%(h.ip)) cur.execute("start slave") elif Slave_IO_Running != "Yes" and Slave_SQL_Running != "Yes": # 重新启动MySQL的slave进程 LOG('GREEN','Restart MySQL Slave Process:%s'%(h.ip)) cur.execute("stop slave") cur.execute("start slave")
def backup_mysql(hosts): for hostinfo in hosts: ip = hostinfo[0] role = "M" if hostinfo[1] == "" else "S" LOG('GREEN','='*60) LOG('GREEN','Target Host:%s'%(ip)) rssh = ssh(hostinfo,user=ROOT_USER,passwd=ROOT_USER_PASSWORD) # 停止mysql数据库 LOG('GREEN','Stop MySQL service') rssh.ssh_run("service mysql stop") # 物理拷贝文件 LOG('GREEN','Backup MySQL Datafile') todir = time.strftime('/opt/huawei/db%Y%m%d_%H%M') rssh.ssh_run("cp /opt/huawei/db %s -R"%(todir)) # 重启mysql数据库 LOG('GREEN','Restart MySQL service') rssh.ssh_run("service mysql start") # 启动MySQL内部的slave进程 if role == "S": LOG('GREEN','Restart slave process') rssh.ssh_run("mysql -uroot -proot -e 'start slave'")
def set_root_passwd(hosts): for hostinfo in hosts: ip = hostinfo[0] LOG('GREEN', '=' * 60) LOG('GREEN', 'Target Host:%s' % (ip)) rssh = ssh(hostinfo, USER_NAME, pem=USER_PEM) # 修改root密码* LOG('GREEN', 'Set the root user password') rssh.ssh_run("echo '%s'|sudo passwd --stdin root" % (ROOT_USER_PASSWORD)) # 修改ssh配置文件 LOG('GREEN', 'Modify ssh configuration file:/etc/ssh/sshd_config') rssh.ssh_run( "sudo sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' %s" % ("/etc/ssh/sshd_config")) # 重启sshd服务 LOG('GREEN', 'Restart sshd service') rssh.ssh_run("sudo service sshd restart") # 本地ssh登录测试 LOG('GREEN', 'Run a connection test using root user') rssh = ssh(hostinfo, user=ROOT_USER, passwd=ROOT_USER_PASSWORD) rssh.ssh_run("echo")
def login(request): ''' ##用户登录(普通用户) --- **参数说明** * username=admin * password=1234qwer **返回值** ''' pwd = request.data.get('password') LOG.debug("pwd %s", pwd) username = request.data.get('username') LOG.debug("username %s", username) user = authenticate(username=username, password=pwd) if user is None: user = authenticate(username=username, password=pwd) if user is None: raise ParseError(u'账号或者密码错误') data = Response(_login_user(request, user)) return data
def send_sms(mobile, content): if not mobile: LOG.debug('ERROR for mobile %s', mobile) return req = urllib2.Request(settings.SMS_ZZ_URL) data = { 'UserName': settings.SMS_ZZ_ACCOUNT, 'UserPass': settings.SMS_ZZ_KEY, 'Mobile': mobile, 'Content': content.encode('utf-8'), 'Subid': '01' } req.add_data(urllib.urlencode(data)) res = urllib2.urlopen(req) result = res.read() res.close() if not result.startswith('00') and not result.startswith('03'): LOG.debug('ERROR for sms %s', result) return True
def cpu_metric(fname): with open(fname) as f: lines = f.readlines() lastline = lines[len(lines) - 1] if lastline.startswith("Average:"): fields = lastline.strip().split() user= fields[2] nice= fields[3] system= fields[4] iowait= fields[5] steal= fields[6] idle= fields[7] return user,nice,system,iowait,steal,idle else: LOG('RED','%s content is incomplete or corrupt'%(fname)) return ""
def checkEnvReady(param): hosts = param[0] pkgs = param[1] for h in hosts.values(): print h LOG('GREEN', 'Target Host:%s' % (h.ip)) rssh = ssh(h.ip, h.user, passwd=h.passwd) # 检查安装环境是否具备 # 1.检查目录是否挂载 LOG('GREEN', 'Check whether mount point /opt/huawei is exists') rtn = rssh.ssh_run(testMountCmd) if int(rtn.split(_mess_part)[1]) < 1: LOG('RED', 'Failure') else: LOG('GREEN', "OK") # 2.检查相关包是否安装 for pkg in pkgs: LOG('GREEN', 'Check whether OS Dependence Package is installed:%s' % (pkg)) rtn = rssh.ssh_run('rpm -qa|grep %s|wc -l' % (pkg)) if int(rtn.split(_mess_part)[1]) < 1: LOG('RED', 'Failure') else: LOG('GREEN', "OK")
def sysbench_run(param): dbhost = param[0] sbhost = param[1] threads = param[2] times = param[3] ip = dbhost.ip uuid = time.strftime('%m%d_%H%M') sarlog = '/opt/huawei/%s_%d_%d_%s_sar.log'%(ip,threads,times,uuid) sblog = '/opt/huawei/%s_%d_%d_%s_sysbench.log'%(ip,threads,times,uuid) local_sarlog = '/opt/huawei/%s/'%(uuid) local_sblog = '' LOG('GREEN','='*60) LOG('GREEN','Target MySQL Host:%s'%(ip)) rssh = ssh(dbhost.ip,user=dbhost.user,passwd=dbhost.passwd) # 启动sar监控命令 LOG('GREEN','Start sar to collect cpu statistic data') cmd = "sar 1 %s >%s &"%(times,sarlog) rssh.ssh_run(cmd) # 执行sysbench测试命令 LOG('GREEN','Start sysbench') rssh_sb = ssh(sbhost.ip,user=sbhost.user,passwd=sbhost.passwd) cmd = "sysbench /root/sysbench/src/lua/oltp_read_write.lua --mysql-host=%s \ --mysql-port=3306 --mysql-db=test --mysql-user=root --mysql-password=root --table_size=10000000 --tables=10 --threads=%s --time=%s --report-interval=10 --db-driver=mysql run > %s "%(ip,threads,times,sblog) print cmd rssh_sb.ssh_run(cmd) print(time.strftime('%m%d_%H%M%S')) time.sleep(10) # 收集sysbench日志 LOG('GREEN','Download sysbench log file') rssh_sb.sftp_download_file(sblog,sblog) # 收集sar日志 LOG('GREEN','Download sar log file') rssh.sftp_download_file(sarlog,sarlog) return sysbench_metric(sblog) + cpu_metric(sarlog)
send_balance_increase_sms(p, tenant, increase) except Exception, e: LOG.error(e) raise e else: pass #处理完毕 LOG.debug( "Trade completed processed: out_trade_no: %s\n total_fee:%s\n transaction_id:%s\n" % (out_trade_no, total_fee, transaction_id)) return "success" else: LOG.debug( "Check sign failed or trade err: trade_state=%s\n retcode=%s\n retmsg=%s\n" % (queryRes.getParameter("trade_state"), queryRes.getParameter("ret_code"), queryRes.getParameter("retmsg"))) return "fail" else: LOG.debug( "Communication with tenpay failed: responsecode=%s\n error_info=%s\n" % (httpClient.getResponseCode(), httpClient.getErrInfo())) return "fail" return "fail"
def index(request): LOG.debug('request.user is [%s]', request.user) return shortcuts.render_to_response('index.html', {'request':request})
def notify_url(request): #首先得到财付通的发来的GET请求 resHandler = ResponseHandler(request) resHandler.setKey(key) if resHandler.isTenpaySign(): #得到notify_id notify_id = resHandler.getParameter("notify_id") LOG.debug("got notify_id: %s" % notify_id) queryReq = RequestHandler() queryReq.init() queryReq.setKey(key) queryReq.setGateURL("https://gw.tenpay.com/gateway/verifynotifyid.xml") queryReq.setParameter("partner",partner) queryReq.setParameter("notify_id",notify_id) httpClient = TenpayHttpClient() httpClient.setTimeOut(5) httpClient.setReqContent(queryReq.getRequestURL()) LOG.debug("queryReq.getRequestURL() : %s" % queryReq.getRequestURL()) #根据得到的notify_id再次到财付通查询验证订单消息 if httpClient.call(): #负责解析httpClient从财付通得到的xml格式中的内容 queryRes = ClientResponseHandler() #加载由httpClient返回的内容 queryRes.setContent(httpClient.getResContent()) LOG.debug("queryRes.getALLParameters(): %s" % queryRes.getALLParameters()) LOG.debug("httpClient.getResContent() : %s" % httpClient.getResContent()) queryRes.setKey(key) if queryRes.isTenpaySign() and queryRes.getParameter("retcode") == "0" and queryRes.getParameter("trade_state") == "0" and queryRes.getParameter("trade_mode") == "1": out_trade_no = queryRes.getParameter("out_trade_no") transaction_id = queryRes.getParameter("transaction_id") trade_state = queryRes.getParameter("trade_state") trade_mode = queryRes.getParameter("trade_mode") total_fee = queryRes.getParameter("total_fee") discount = queryRes.getParameter("discount") #开始处理业务 #注意验证订单不要重复 #注意判断返回金额 p = PayOrder.objects.get(trade_no=out_trade_no) if p.total_fee == int(total_fee) and p.payment_info != '2': p.transaction_id = transaction_id p.trade_state = trade_state p.trade_mode = trade_mode p.ret_code = queryRes.getParameter("retcode") p.ret_msg = queryRes.getParameter("retmsg") p.payment_info = 2 p.save() try: tenant_id = p.tenant_id tenant = Tenant.objects.get(tenant_id=tenant_id) increase = (int(total_fee) * int(recharge_exchange_rate)) tenant.balance += increase tenant.save() if p.send_sms: send_balance_increase_sms(p, tenant, increase) except Exception,e: LOG.error(e) raise e else: pass #处理完毕 LOG.debug("Trade completed processed: out_trade_no: %s\n total_fee:%s\n transaction_id:%s\n" % (out_trade_no,total_fee,transaction_id)) return "success" else: LOG.debug("Check sign failed or trade err: trade_state=%s\n retcode=%s\n retmsg=%s\n" % (queryRes.getParameter("trade_state"), queryRes.getParameter("ret_code"), queryRes.getParameter("retmsg"))) return "fail"
def install_mysql(hosts): for hostinfo in hosts: ip = hostinfo[0] ser_id = ip[ip.rfind('.')+1:] LOG('GREEN','='*60) LOG('GREEN','Target Host:%s'%(ip)) rssh = ssh(hostinfo,ROOT_USER,passwd=ROOT_USER_PASSWORD) # 创建work目录 LOG('GREEN','1/9: Create MySQL Directory') rssh.ssh_run('mkdir -p /root/source') # 上传mysql文件 LOG('GREEN','2/9: Upload MySQL RPM Install Package') rssh.sftp_upload_file('/root/source/MySQL-server-5.6.38-1.el7.x86_64.rpm','/root/source/MySQL-server-5.6.38-1.el7.x86_64.rpm') rssh.sftp_upload_file('/root/source/MySQL-client-5.6.38-1.el7.x86_64.rpm','/root/source/MySQL-client-5.6.38-1.el7.x86_64.rpm') # 上传my.cnf文件 LOG('GREEN','3/9: Upload MySQL Configure File:/etc/my.cnf') rssh.sftp_upload_file('/root/my.cnf','/etc/my.cnf') # 修改my.cnf文件中的server-id rssh.ssh_run("sudo sed -i 's/18224/%s/g' %s"%(ip[ip.rfind('.')+1:],'/etc/my.cnf')) # 安装MySQL软件 for pkg in mysqlInstallPkgs: LOG('GREEN','4/9: Install MySQL Package: %s'%pkg) rtn = rssh.ssh_run('rpm -ivh %s%s'%(SoftDir,pkg)) # 创建目录和授权 LOG('GREEN','5/9: Create MySQL Data Dir: /opt/huawei/db') rssh.ssh_run("mkdir -p /opt/huawei/db/data") rssh.ssh_run("mkdir -p /opt/huawei/db/mysql_temp") rssh.ssh_run("chown mysql:mysql /opt/huawei/db -R") rssh.ssh_run("chmod 777 /opt/huawei/db -R") rssh.ssh_run("chown mysql:mysql /etc/my.cnf") # 执行建库脚本: LOG('GREEN','6/9: Run Install DB Script:/usr/bin/mysql_install_db') rssh.ssh_run("/usr/bin/mysql_install_db --user=mysql") # 启动mysql服务 LOG('GREEN','7/9: start mysql service') rtn = rssh.ssh_run('service mysql start') # 设置root密码 LOG('GREEN','8/9: Set the password of root user') rtn = rssh.ssh_run('/usr/bin/mysqladmin -u root password "root"') # 创建root账号 # grant all on *.* to 'root'@'%' identified by 'root'; # flush privileges; LOG('GREEN','9/9: Add new root user account') print('mysql -uroot -proot -e "%s"'%("grant all on *.* to 'root'@'%' identified by 'root';flush privileges;")) rtn = rssh.ssh_run('mysql -uroot -proot -e "%s"'%("grant all on *.* to 'root'@'%' identified by 'root';flush privileges;")) print(rtn)
def get(self, request): LOG.debug('GET - request.GET : %s', request.GET) return self.json(request.GET.dict())
increase = (int(total_fee) * int(recharge_exchange_rate)) tenant.balance += increase tenant.save() if p.send_sms: send_balance_increase_sms(p, tenant, increase) except Exception,e: LOG.error(e) raise e else: pass #处理完毕 LOG.debug("Trade completed processed: out_trade_no: %s\n total_fee:%s\n transaction_id:%s\n" % (out_trade_no,total_fee,transaction_id)) return "success" else: LOG.debug("Check sign failed or trade err: trade_state=%s\n retcode=%s\n retmsg=%s\n" % (queryRes.getParameter("trade_state"), queryRes.getParameter("ret_code"), queryRes.getParameter("retmsg"))) return "fail" else: LOG.debug("Communication with tenpay failed: responsecode=%s\n error_info=%s\n" % (httpClient.getResponseCode(),httpClient.getErrInfo())) return "fail" return "fail"
def post(self, request): LOG.debug('POST - request.POST : %s', request.POST) return self.json(request.POST.dict())
def notify_url(request): #首先得到财付通的发来的GET请求 resHandler = ResponseHandler(request) resHandler.setKey(key) if resHandler.isTenpaySign(): #得到notify_id notify_id = resHandler.getParameter("notify_id") LOG.debug("got notify_id: %s" % notify_id) queryReq = RequestHandler() queryReq.init() queryReq.setKey(key) queryReq.setGateURL("https://gw.tenpay.com/gateway/verifynotifyid.xml") queryReq.setParameter("partner", partner) queryReq.setParameter("notify_id", notify_id) httpClient = TenpayHttpClient() httpClient.setTimeOut(5) httpClient.setReqContent(queryReq.getRequestURL()) LOG.debug("queryReq.getRequestURL() : %s" % queryReq.getRequestURL()) #根据得到的notify_id再次到财付通查询验证订单消息 if httpClient.call(): #负责解析httpClient从财付通得到的xml格式中的内容 queryRes = ClientResponseHandler() #加载由httpClient返回的内容 queryRes.setContent(httpClient.getResContent()) LOG.debug("queryRes.getALLParameters(): %s" % queryRes.getALLParameters()) LOG.debug("httpClient.getResContent() : %s" % httpClient.getResContent()) queryRes.setKey(key) if queryRes.isTenpaySign() and queryRes.getParameter( "retcode") == "0" and queryRes.getParameter( "trade_state") == "0" and queryRes.getParameter( "trade_mode") == "1": out_trade_no = queryRes.getParameter("out_trade_no") transaction_id = queryRes.getParameter("transaction_id") trade_state = queryRes.getParameter("trade_state") trade_mode = queryRes.getParameter("trade_mode") total_fee = queryRes.getParameter("total_fee") discount = queryRes.getParameter("discount") #开始处理业务 #注意验证订单不要重复 #注意判断返回金额 p = PayOrder.objects.get(trade_no=out_trade_no) if p.total_fee == int(total_fee) and p.payment_info != '2': p.transaction_id = transaction_id p.trade_state = trade_state p.trade_mode = trade_mode p.ret_code = queryRes.getParameter("retcode") p.ret_msg = queryRes.getParameter("retmsg") p.payment_info = 2 p.save() try: tenant_id = p.tenant_id tenant = Tenant.objects.get(tenant_id=tenant_id) increase = (int(total_fee) * int(recharge_exchange_rate)) tenant.balance += increase tenant.save() if p.send_sms: send_balance_increase_sms(p, tenant, increase) except Exception, e: LOG.error(e) raise e else: pass #处理完毕 LOG.debug( "Trade completed processed: out_trade_no: %s\n total_fee:%s\n transaction_id:%s\n" % (out_trade_no, total_fee, transaction_id)) return "success" else: LOG.debug( "Check sign failed or trade err: trade_state=%s\n retcode=%s\n retmsg=%s\n" % (queryRes.getParameter("trade_state"), queryRes.getParameter("ret_code"), queryRes.getParameter("retmsg"))) return "fail"
def put(self, request): super(SampleRestView, self).put(request) LOG.debug('PUT - request.PUT : %s', request.PUT) return self.json(request.PUT.dict())
def i_add_new_item(step, commands, command, serv_as): """Add new item to memcache server (dict,str)""" result = getattr(world.memcache_client, world.memcache_maps[commands][command])('1000','test_value') LOG.debug('Result of command %s from memcache client is %s' % (command, result)) if not result: raise AssertionError('Suggested command is not added an element to memcache: world.memcache_client.%s' % str(world.memcache_maps[commands][command])+"('1000','test_value')")
def delete(self, request): super(SampleRestView, self).delete(request) LOG.debug('DELETE - request.DELETE : %s', request.DELETE) return self.json(request.DELETE.dict())
def month_name(dt): """ This may be replaced by default [date] filter: blog.created|date:'N' """ LOG.debug("##### month is: %s", dt.month) return MON_NAME.get(dt.month)
def startswith(string, prefix): if isinstance(string, str) or isinstance(string, unicode): return string.startswith(prefix) LOG.error("[%s] is not str object, return False", string) return False
def i_get_new_item(step, commands, command, serv_as): """Get item from memcache server for the key (dict,str)""" result = getattr(world.memcache_client, world.memcache_maps[commands][command])('1000') LOG.debug('Result of command %s from memcache client is %s' % (command, result)) if result != "test_value": raise AssertionError('Suggested command is not get element from memcache: world.memcache_client.%s' % str(world.memcache_maps[commands][command])+"('1000')")