예제 #1
0
def test_formatDate_Error(dateStr):
    """ Test DateUtil.formatDate() bad dates """
    # Call init fixture
    initEnv()

    with pytest.raises(ValueError):
        DateUtil.formatDate(dateStr)
예제 #2
0
def main():
    try:

        # 创建对象
        realtimehot = Top()
        # 进行查询
        realtimehot.get_top(
            "https://www.yidianzixun.com/home/q/hot_search_keywords?appid=web_yidian&_=%s"
            % DateUtil.getNowTimeMillisecond())
        print("yidian hot search start at time:%s" % DateUtil.nowSplit())
    except Exception as e:
        print(e)
예제 #3
0
    def get_top(self, url):
        # 进行http请求,获取response
        r = requests.get(url)
        # 获取response的返回值
        html = r.text
        soup = BeautifulSoup(html, 'lxml')
        # print(soup.prettify())
        # 定义一个返回值
        resultList = []
        # 循环处理
        for child in soup.tbody.children:
            # 定义一个map,存放地址,名称和数量
            tmp = {}
            if isinstance(child, bs4.element.Tag):
                if child.span and child.a:
                    if child.select('a["href_to"]'):
                        tmp["url"] = "http://s.weibo.com" + child.a["href_to"]
                    else:
                        tmp["url"] = "http://s.weibo.com" + child.a["href"]
                    tmp["title"] = child.a.text.strip()
                    tmp["count"] = child.span.string
                    tmp["createTime"] = DateUtil.nowSplit()
                    tmp["source"] = "weibo"
                    tmp["category"] = "hot_search"
                    # 加入list
                    resultList.append(tmp)

        # 插入mongo库
        MongoUtil.saveMongoForHotSearch(resultList)
예제 #4
0
 def get_top(self, url):
     # 进行http请求,获取response
     response = requests.get(url)
     # 获取response的返回值
     dataJson = json.loads(response.text)
     code = dataJson.get("code")
     if 0 == code:
         keywords = dataJson.get("keywords")
         # 定义一个返回值
         resultList = []
         # keywords结果为json,进行json处理
         count = 100
         for item in keywords:
             tmp = {}
             tmp["url"] = ""
             tmp["title"] = item.get("name")
             tmp["count"] = count
             count = count - 1
             tmp["createTime"] = DateUtil.nowSplit()
             tmp["source"] = "yidian"
             tmp["category"] = "hot_search"
             # 加入list
             resultList.append(tmp)
         # 插入mongo库
         MongoUtil.saveMongoForHotSearch(resultList)
예제 #5
0
def test_formatDate_OK(dateStr):
    """ Test DateUtil.formatDate() with correct dates no modification must appear """
    # Call init fixture
    initEnv()

    dateFormated = DateUtil.formatDate(dateStr)
    assert dateStr == dateFormated
예제 #6
0
 def sendMessage(self, user):
     try:
         _r2 = '--------order:%s---%s(%s)负责今天(%s)早会------------' % (
             str(user.order), user.name, user.account,
             DateUtil.getCurrentDate())
         self._logger.info(_r2)
         eReceivers = []
         tReceivers = []
         if user:
             eReceivers.append(user.email)
             tReceivers.append(user.tel)
             try:
                 content = user.name + '(' + user.account + ')' + '负责今天(' + getCurrentDate(
                 ) + ')早会'
                 EmailUtil.sendEmail(eReceivers, u'主持早会',
                                     content.encode("utf-8"))
             except Exception as e:
                 self._logger.error("邮件失败," + str(e))
                 pass
             try:
                 msg = "【主持早会】" + user.name + '(' + user.account + ')' + '负责今天(' + getCurrentDate(
                 ) + ')早会'
                 SMSUtil.sendSMS(tReceivers, msg.encode("utf-8"))
             except Exception as e:
                 self._logger.error("短信失败," + str(e))
                 pass
     except Exception as e:
         print(e)
예제 #7
0
    def get_top(self, url, category):
        # 进行http请求,获取response
        r = requests.get(url)
        r.encoding = 'gb18030'
        # 获取response的返回值
        html = r.text
        soup = BeautifulSoup(html, 'lxml')
        # print(soup.prettify())
        # 定义一个返回值
        resultList = []
        # 循环处理
        for child in soup.table.children:
            # 定义一个map,存放地址,名称和数量
            tmp = {}
            if isinstance(child, bs4.element.Tag):
                if child.span and child.a:
                    if child.select('a["class~=list-title"]'):
                        tmp["url"] = child.a["href"]
                    tmp["title"] = child.a.text.strip()
                    if child.select('span["class^=icon-"]'):
                        span = child.select('span["class^=icon-"]')[0].string
                        tmp["count"] = re.search("(\d+)", span).group(0)
                    tmp["createTime"] = DateUtil.nowSplit()
                    tmp["source"] = "baidu"
                    tmp["category"] = category
                    # 加入list
                    resultList.append(tmp)

        # 插入mongo库
        MongoUtil.saveMongoForHotSearch(resultList)
예제 #8
0
def updateCurrentSystemImage(request):
    #获取前端上传的图片
    file = request.FILES.getlist('files')
    product_id = _post(request, "id")
    file_name1 = ""
    
    #判断是否为空,默认
    if len(file) == 0:
        return;
    for f in file:
        name = f.name
        file_name = name.split(".")[0] + "_"+ DateUtil.time_stamp() +"."+ name.split(".")[1]
        img_path = os.path.join(Resp.IMAGEUPLOAD, file_name)
        file_name1+="/images/currentsystem_images/" + file_name+","
    #写入到文件中
        with open(img_path,'wb') as  ff:
            for item in f.chunks():
                ff.write(item)
    saveImageRow =  CurrentSystemService.updateCurrentSystemImage(file_name1, product_id)
    #路径保存到数据库
    respJson = {}
    if saveImageRow > 0:
        respJson["product_id"] = saveImageRow
    else:
        respJson["ERROR"] = Resp.ERROR
    return HttpResponse(toJson(respJson));
예제 #9
0
    def get_top(self, url):
        headers = {'Content-Type': 'application/json; charset=utf-8'}
        # 进行http请求,获取response
        r = requests.get(url, headers=headers)
        # 获取response的返回值
        resJson = r.text
        data = json.loads(resJson)
        searchJson = data.get('data')
        searchData = json.loads(searchJson)

        # 创建list[{}]
        resultList = []
        # 定义一个总量
        totalCount = 100
        # 循环处理
        for word in searchData.get('search_words'):
            tmp = {}
            tmp["url"] = word.get("link")
            tmp["title"] = word.get("q")
            totalCount = totalCount - 1
            tmp["count"] = totalCount
            tmp["createTime"] = DateUtil.nowSplit()
            tmp["source"] = "toutiao"
            tmp["category"] = "hot_search"
            # 加入列表
            resultList.append(tmp)
        # 插入mongo库
        MongoUtil.saveMongoForHotSearch(resultList)
예제 #10
0
def test_formatDate_convert_OK(dateStr, formatStr):
    """ Test DateUtil.formatDate() date reformatting """
    # Call init fixture
    initEnv()

    dateFormated = DateUtil.formatDate(dateStr)
    assert dateStr != dateFormated
    assert datetime.datetime.strptime(dateStr, formatStr) == \
            datetime.datetime.strptime(dateFormated, '%Y/%m/%d')
예제 #11
0
def main():
    try:
        # 创建对象
        realtimehot = Top()
        # 进行查询
        realtimehot.get_top("https://www.ixigua.com/hot_words/")
        print("xigua hot search start at time:%s" % DateUtil.nowSplit())
    except Exception as e:
        print(e)
예제 #12
0
def main():
    try:

        # 创建对象
        realtimehot = Top()
        # 进行查询
        realtimehot.get_top("http://s.weibo.com/top/summary?cate=realtimehot")
        print("weibo hot search start at time:%s" % DateUtil.nowSplit())
    except Exception as e:
        print(e)
예제 #13
0
def main():
    try:
        # 创建对象
        realtimehot = Top()
        # 进行查询
        realtimehot.get_top(
            "https://is.snssdk.com/2/wap/search/extra/hot_word_list/?use_wk=1&hide_bar=1&hide_status_bar=1&background_colorkey=3&disable_web_progressView=1&enable_jump=1&is_new_ui=1&source=title&iid=56902458375&device_id=58205562141&channel=oppo-cpa&aid=13&app_name=news_article&version_code=705&version_name=7.0.5&device_platform=android&abflag=3&device_type=PBEM00&device_brand=OPPO&language=zh&os_api=27&os_version=8.1.0&openudid=7284731287f985db&manifest_version_code=705&resolution=1080*2340&dpi=480&update_version_code=70515&_rticket=1546829616083&plugin=26958&fp=crT_cW4_FrGtFlwOLlU1F2KIFzKe&format=json"
        )
        print("toutiao hot search start at time:%s" % DateUtil.nowSplit())
    except Exception as e:
        print(e)
예제 #14
0
    def validate(self):
        """ Check Data entered by user
            if OK return True
        """
        isOK = False
        try:
            if self.nameVar.get() == "":
                raise ValueError(_("Please give a portion name"))
            if self.dateVar.get() == "":
                raise ValueError(_("Please give a date"))
            DateUtil.formatDate(self.dateVar.get())
            if self.patientCodeCombobox.get() == "":
                raise ValueError(_("Please give a patient code"))
            if self.portionTypeVar.get() == "":
                raise ValueError(_("Please give a portion type"))
            if self.periodCombobox.get() == "":
                raise ValueError(_("Please give a period"))

            # Ask if portion exists
            code, portionExists = self.database.getPortionCode(
                self.nameVar.get(), self.dateVar.get(),
                self.patientCodeCombobox.get())

            if portionExists:
                isMofificationOk = messagebox.askyesno(_("Add or modify Portion in database"),
                        _("Do you really want to modify this existing portion in database ?") + \
                        "\n" + _("Portion code") + " : " + str(code) + \
                        "\n" + _("Portion name") + " : " + self.nameVar.get() + \
                        "\n" + _("Date") + " : "  + self.dateVar.get() + \
                        "\n" + _("Patient code") + " : "  + self.patientCodeCombobox.get(),
                        icon='warning')
                if not isMofificationOk:
                    raise ValueError(_("Please modify portion identificators"))

            isOK = True
        except ValueError as exc:
            self.bell()
            messagebox.showwarning(_("Bad input"),
                                   message=_("Error") + " : " + str(exc) +
                                   " !")
        return isOK
예제 #15
0
 def clicExistingPortion(self, dummy):
     """ Update portion input field with chosen listbox item """
     # Get selection
     selectedExistingPortion = list(self.portionListBox.curselection())
     if len(selectedExistingPortion) > 0:
         nameDate = self.portionListBox.get(
             selectedExistingPortion[0]).split(" / ")
         self.nameVar.set(nameDate[0])
         dateRead = nameDate[1]
         try:
             DateUtil.formatDate(dateRead)
         except ValueError as exc:
             self.bell()
             messagebox.showwarning(
                 _("Loading values"),
                 str(exc) + "\n" + _("Please correct the date displayed") +
                 " !")
         self.dateVar.set(dateRead)
         self.patientCodeCombobox.set(nameDate[2])
         self.portionTypeVar.set(nameDate[3])
         self.periodCombobox.set(nameDate[4])
예제 #16
0
def downloadAndSaveFile(filmId, pageCount, filename):
    for i in range(1, pageCount + 1):
        print("%s,page=%d" % (dateUtil.timeToStr(time.localtime()), i))
        url = 'http://m.maoyan.com/mmdb/comments/movie/' + filmId + '.json?_v_=yes&offset=' + str(
            i)
        html = getPage(url)
        data = parsePage(html)
        for item in data:
            with open(filename + '.txt', 'a', encoding='utf-8') as f:
                # f.write(item['date'] + ','+item['nickname'] + ',' + item['city'] + ',' + str(item['rate']) + ',' + item['conment']+'\n')
                f.write(json.dumps(item, ensure_ascii=False) + '\n')
                #time.sleep(random.randint(1,100)/20)
        time.sleep(2)
예제 #17
0
def get_hour_index(date,
                   freq=FREQUENCY.FREQ_1_HOUR,
                   market=MARKET_TYPE.STOCK_CN):
    """获取不同市场股票小时线的index
    """

    # 参数校验
    if market not in MARKET_TYPE.TUPLE_MARKET_TYPE or freq not in FREQUENCY.TUPLE_FREQ_HOUR \
            or not DateUtil.is_valid_date(date):
        return None

    if market == MARKET_TYPE.STOCK_CN:
        return __get_market_cn_index(date, freq)
    elif market == MARKET_TYPE.STOCK_HK:
        return __get_market_hk_index(date, freq)
    else:
        return None
예제 #18
0
def get_min_index(date,
                  freq=FREQUENCY.FREQ_1_MIN,
                  market=MARKET_TYPE.STOCK_CN):
    """获取不同市场股票分钟线的index
    """

    # 参数校验
    if market not in MARKET_TYPE.TUPLE_MARKET_TYPE or freq not in FREQUENCY.TUPLE_FREQ_MIN \
            or not DateUtil.is_valid_date(date):
        return None

    # if QA_util_if_trade(day) is True:
    if market == MARKET_TYPE.STOCK_CN:
        return __get_market_cn_index(date, freq)
    elif market == MARKET_TYPE.STOCK_HK:
        return __get_market_hk_index(date, freq)
    else:
        return None
예제 #19
0
def main():
    try:
        # 创建对象
        realtimehot = Top()
        # 实时热点
        realtimehot.get_top("http://top.baidu.com/buzz?b=1&fr=topbuzz_b11",
                            "hot_realtime")
        # 今日热点
        realtimehot.get_top(
            "http://top.baidu.com/buzz?b=341&c=513&fr=topbuzz_b341_c513",
            "hot_today")
        # 民生热点
        realtimehot.get_top(
            "http://top.baidu.com/buzz?b=342&c=513&fr=topbuzz_b341_c513",
            "hot_livelihood")
        # 娱乐热点
        realtimehot.get_top(
            "http://top.baidu.com/buzz?b=344&c=513&fr=topbuzz_b342_c513",
            "hot_entertainment")
        print("baidu hot search start at time:%s" % DateUtil.nowSplit())
    except Exception as e:
        print(e)
예제 #20
0
def catch(source_url):
    curr_url, html = loadPage(source_url)
    # 解析
    # 判断内容解析方式
    content_item = parseContent(curr_url, html)
    content_item_common = CommonParse.parse(html) or {}
    content_item = content_item or {}
    title = content_item.get(u'title') or content_item_common.get(
        u'title') or u''
    post_date = content_item.get(u'post_date') or content_item_common.get(
        u'post_date') or u''
    content_html = content_item.get(
        u'content_html') or content_item_common.get(u'content_html') or u''
    if not title and not post_date and not content_html:
        return -100, u'没有抓取到相关内容', None
    else:
        # 得到最终的结果
        styles = u''
        if content_html:
            # styles = operateCss(content_item, content_item_common, html)

            content_html = downLoadImg(source_url, content_html)

            # 去除 image 的 alt title
            content_html = clearAltTitleHref(content_html)

            # 去除不要的标签内容
            clear_paths_in = content_item.get(
                u'clear_paths_in') or content_item_common.get(
                    u'clear_paths_in') or []
            clearPaths = [u'//script'] + clear_paths_in
            content_html = clearDOM(content_html, clearPaths)

            # 处理时间
            post_date = DateUtil.dateFormat(dateStr=post_date)
        return upload_result(title, post_date, content_html, styles)
예제 #21
0
        se.export()
        sc = StockCleaner(stock_code, end_date)
        sc.clean()
    else:
        logger.warn("No data found for stock code: " + stock_code)

if __name__ == '__main__':
    try:
        logger.info("Downloading full stock list....")

        sbd = StockBasicData()
        sbd.download_stock_list()
        logger.info("Download completed")

        now = datetime.now()
        today = du.convertDateToString(now, '%Y-%m-%d')
        #today = "1999-12-31"
        logger.debug("Today is: " + today)
        stock_list = sbd.get_stock_list(today)

        pool = mp.Pool(processes=1)
        #for stock in stock_list[:5]:
        for stock in stock_list:
            stock_code = stock[0]
            last_updated_date = du.convertDateToString(stock[1], '%Y-%m-%d')
            pool.apply_async(create_process, (stock_code, last_updated_date, today))

        pool.close()
        pool.join()
        logger.info("All stocks information is downloaded")
    except Exception, e:
예제 #22
0
 def POST(self):
     args = web.input()
     logger.info(u'入参:%s' %args)
     userCode = args.get('usercode')
     result = {}
     try:
         self.db.execute('SELECT flag FROM %s WHERE usercode = ?' %Global.GLOBAL_TABLE_PAYMENT_USER, (userCode,))
         userInfo = self.db.fetchone()
         dbFlag = userInfo['flag']
         if dbFlag == 1:
             dbFlag = 0
             result['busStatus'] = '一直可以缴费'
         else:
             dbFlag = 1
             result['busStatus'] = '缴费成功后无欠费'
         self.db.execute('UPDATE %s SET flag = ?, queryresultcode = ?, updatetime = ? WHERE usercode = ?' %Global.GLOBAL_TABLE_PAYMENT_USER, (dbFlag, '0000000', DateUtil.getDate(format='%Y-%m-%d %H:%M:%S'), userCode))
         self.conn.commit()
         result['status'] = 'SUCCESS'
         result['msg'] = '修改成功'
     except Exception, e:
         logger.error(u'切换状态失败')
         result['msg'] = u'修改失败'
예제 #23
0
 def POST(self):
     args = web.input()
     logger.info(u'入参:%s' %args)
     amount = args.get('amount')
     result = {}
     if not amount or len(amount) == 0:
         result['status'] = 'FAIL'
         return
     try:
         addbalance = float(amount)
         if addbalance <=0:
             result['status'] = 'FAIL'
             return
         self.db.execute('SELECT balance FROM %s WHERE merchantkey = ? ORDER BY updatetime desc limit 1' %Global.GLOBAL_TABLE_BALANCE, (Global.GLOBAL_MERCHANTS.get('lencee'),))
         querybalance = self.db.fetchone()
         balance = querybalance['balance']
         balance = float(format(balance + addbalance, '.2f'))
         self.db.execute('UPDATE %s SET balance = ?, updatetime = ? WHERE merchantkey = ?' %Global.GLOBAL_TABLE_BALANCE, (balance, DateUtil.getDate(format='%Y-%m-%d %H:%M:%S'), Global.GLOBAL_MERCHANTS.get('lencee')))
         self.conn.commit()
         result['status'] = 'SUCCESS'
         result['balance'] = balance
     except Exception, err:
         result['status'] = 'ABNORMAL'
         logger.error(u'增加商户预存款异常:%s' %err)
예제 #24
0
 def getresult(self, money, flagNum=0):
     result = {}
     if flagNum:
         num = flagNum
     else:
         num = random.randint(1,2)
     self.db.execute('SELECT balance FROM %s WHERE merchantkey = ? ORDER BY updatetime desc limit 1' %Global.GLOBAL_TABLE_BALANCE, (Global.GLOBAL_MERCHANTS.get('lencee'),))
     querybalance = self.db.fetchone()
     if not querybalance:
         # 商户预存款未找到
         pass
     balance = querybalance['balance']
     if num == 1:
         result['status'] = 'SUCCESS'
         result['resultCode'] = '0000000'
         balance = float(format(balance - float(money), '.2f'))
         self.db.execute('UPDATE %s SET balance = ?, updatetime = ? WHERE merchantkey = ?' %Global.GLOBAL_TABLE_BALANCE, (balance, DateUtil.getDate(format='%Y-%m-%d %H:%M:%S'), Global.GLOBAL_MERCHANTS.get('lencee')))
         self.conn.commit()
     else:
         result['status'] = 'FAIL'
         result['resultCode'] = '0000106'
     result['balance'] = balance
     return result
예제 #25
0
    def POST(self):
        args = web.input()
        logger.info(u'入参:%s' %args)
        userCode = args.get('usercode')
        channelCode = args.get('channelcode')
        result = {}
        try:
            # 修改欠费明细滞纳金
            self.db.execute('UPDATE %s SET breach = ?, updatetime = ? WHERE channelcode = ? AND usercode = ?' %Global.GLOBAL_TABLE_USER_ARREARS, ('0.0', DateUtil.getDate(format='%Y-%m-%d %H:%M:%S'), channelCode, userCode))
            self.conn.commit()

            # 查询用户总欠费、滞纳金
            self.db.execute('SELECT sum(itemmoney) paymentmoney, sum(breach) breach FROM %s WHERE usercode = ?' %Global.GLOBAL_TABLE_USER_ARREARS, (userCode, ))
            newInfo = self.db.fetchone()

            # 返回结果
            result['status'] = 'SUCCESS'
            result['breach'] = '0.0'
            result['totalmoney'] = float(format(newInfo['paymentmoney'], '.2f'))
            result['totalbreach'] = float(format(newInfo['breach'], '.2f'))
            result['msg'] = '修改成功'
        except Exception, e:
            logger.error(u'清空滞纳金失败')
            result['msg'] = u'修改失败'
예제 #26
0
    def execute(self):
        self.db.execute('SELECT * FROM easylife_payment_order WHERE status=? AND iskeephangup=?', ('PROCESSING', 0))
        procs = self.db.fetchall()
        account = {}
        for info in procs:
            self.db.execute('SELECT * FROM %s WHERE usercode = ?' %Global.GLOBAL_TABLE_PAYMENT_USER, (info['usercode'],))
            account = self.db.fetchone()
            flagNum = 0
            if account['rechangeStatus']:
                if account['rechangeStatus'] == 'SUCCESS':
                    flagNum = 1
                else:
                    flagNum = 2
            res = self.getresult(info['paymentAmount'], flagNum)
            self.db.execute('UPDATE easylife_payment_order SET status = ?, resultcode = ?, updatetime = ? WHERE easylifeorderno = ?', (res.get('status'), res.get('resultCode'), DateUtil.getDate(format='%Y-%m-%d %H:%M:%S'), info['easyLifeOrderNo']))
            self.conn.commit()

            # 如果用户表flag=1,更新用户查询结果码为:0000121
            if account['flag'] == 1:
                self.db.execute('UPDATE %s SET queryresultcode = ? WHERE usercode = ?' %Global.GLOBAL_TABLE_PAYMENT_USER, ('0000121', info['usercode']))
                self.conn.commit()
                logger.info(u'更新用户%s查询结果码:%s' %(info['usercode'], '0000121'))
            logger.info(u'修改订单:%s状态为%s,剩余备付金:%s' %(info['easyLifeOrderNo'], res.get('status'), res.get('balance')))
예제 #27
0
            sql = "UPDATE tj_news_clob SET news_group=" + str(
                group) + " WHERE  news_id='" + newsid + "'"
            cursor.execute(sql)
            if y_pred[i] in countdict.keys():
                countdict[y_pred[i]] = countdict[y_pred[i]] + 1
            else:
                countdict[y_pred[i]] = 1
        print('修改新闻类别成功')
        print('km.cluster_centers_.shape[0]:', km.cluster_centers_.shape[0])
        for k in range(km.cluster_centers_.shape[0]):
            sql1 = "INSERT INTO tj_cluster_centers (group_id, wv,count) VALUES (" + str(
                k) + ", '" + str(km.cluster_centers_[k]) + "'," + str(
                    countdict[k]) + ")"
            cursor.execute(sql1)
        db.close()
        print("修改类别成功")


np.set_printoptions(threshold=np.NaN)
start = DateUtil.nowToStrNormal()
print(start)
c = Cluster(stopword_path='hlt_stop_words.txt')
#分词
# c.wordcut()
#词向量
newsids, tdm = c.wordvector(sql=False)
print('tdm:', tdm.shape)
#kmeans
c.dokmeans(newsids, tdm, 200, 400)
print("start:", start, "  end:", DateUtil.nowToStrNormal())
예제 #28
0
     zsz = trContent[6].find_all("td")[1].text[3:][:-1]
     ltsz = trContent[7].find_all("td")[1].text[3:][:-1]
     print "jlv" + trContent[4].find_all("td")[1].text[4:]
 # 获得解禁时间
 jjSql = "select min(jjsj) jjsj from stock_jjsj where stockno='" + stockno + "' and jjsj>='" + importdate + "'"
 cursor.execute(jjSql)
 jjRow = cursor.fetchone()
 print jjRow
 if jjRow[0] == None:
     jjsj = ""
 else:
     jjsj = jjRow[0]
 # 获得上月收盘价
 # 获得本日收盘价
 # 获得上个月
 pre_month = dateutil.get_pre_month()
 print pre_month
 syspjSQL = (
     "select * from stock_day_data where date=(select max(date) from stock_day_data where code='"
     + stockno
     + "' and left(date,7)='"
     + pre_month
     + "') and code='"
     + stockno
     + "' "
 )
 brspjSQL = "select * from stock_day_data where date like'" + importdate + "%' and code='" + stockno + "'"
 cursor.execute(syspjSQL)
 syspjRow = cursor.fetchone()
 print syspjRow
 if syspjRow == None:
예제 #29
0
    def init():
        conn = SQLite.conn()
        conn.text_factory = str
        cursor = conn.cursor()
        # 创建缴费信息表
        cursor.execute('''CREATE TABLE IF NOT EXISTS %s(easylifeorderno text, outbizno text, status text, paymenttype text, usercode text, resultcode text, paymentamount real, iskeephangup integer, addtime datetime, updatetime datetime)''' %(Global.GLOBAL_TABLE_PAYMENT))
        # 创建商户预存款表
        cursor.execute('''CREATE TABLE IF NOT EXISTS %s(merchantkey text, balance real, addtime datetime, updatetime datetime)''' %(Global.GLOBAL_TABLE_BALANCE))
        # 创建缴费用户信息表
        cursor.execute('''CREATE TABLE IF NOT EXISTS %s(usercode text, username text, querystatus text, queryresultcode text, address text, memo text, flag INTEGER, paymentstatus text, paymenttype text, paymentresultcode text, ishangup int, rechangestatus text, addtime datetime, updatetime datetime)''' %(Global.GLOBAL_TABLE_PAYMENT_USER))
        # 创建用户欠费信息表
        cursor.execute('''CREATE TABLE IF NOT EXISTS %s(channelcode test, usercode text, count real, startcount real, endcount real, price real, breach text, itemmoney real, month text, addtime datetime, updatetime datetime)''' %Global.GLOBAL_TABLE_USER_ARREARS)

        # 增加商户预存款信息
        for mer in Global.GLOBAL_MERCHANTS:
            cursor.execute('SELECT * FROM %s WHERE merchantkey = ?' %Global.GLOBAL_TABLE_BALANCE, (Global.GLOBAL_MERCHANTS.get(mer),))
            if cursor.fetchone():
                continue
            cursor.execute('INSERT INTO %s(merchantkey, balance, addtime, updatetime) VALUES("%s", %.2f, "%s", "%s")' %(Global.GLOBAL_TABLE_BALANCE, Global.GLOBAL_MERCHANTS.get(mer), 10000, DateUtil.getDate(format='%Y-%m-%d %H:%M:%S'), DateUtil.getDate(format='%Y-%m-%d %H:%M:%S')))

        cursor.execute('SELECT * FROM %s' %(Global.GLOBAL_TABLE_PAYMENT_USER))
        if not cursor.fetchone():
            for user in Global.GLOBAL_ACCOUNT:
                # 设置用户缴费后是否没有欠费信息标识
                flag = 0
                if user.get('flag'):
                    flag = 1

                # 添加用户数据
                userCode = user.get('userCode')
                cursor.execute('INSERT INTO %s(usercode, username, querystatus, queryresultcode, address, memo, flag, paymentstatus, paymenttype, paymentresultcode, ishangup, rechangestatus, addtime, updatetime) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' %Global.GLOBAL_TABLE_PAYMENT_USER, (userCode, user.get('userName'), user.get('queryStatus'), user.get('queryResultCode'), user.get('address'), user.get('memo'), flag, user.get('paymentStatus'), user.get('paymentType'), user.get('paymentResultCode'), user.get('isHangup'), user.get('rechangeStatus'), DateUtil.getDate(format='%Y-%m-%d %H:%M:%S'), DateUtil.getDate(format='%Y-%m-%d %H:%M:%S')))
                conn.commit()

                # 增加用户欠费信息
                userArrears = Global.GLOBAL_ACCOUNT_ARREARS.get(userCode)
                index = 0
                if userArrears:
                    for arrear in userArrears:
                        itemMoney = float(format((arrear.get('count') * arrear.get('price')), '.2f'))
                        cursor.execute('INSERT INTO easylife_user_arrears(channelcode, usercode, count, startcount, endcount, price, breach, itemmoney, month, addtime, updatetime) VALUES(?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?)' %Global.GLOBAL_ACCOUNT_ARREARS, (RandomUtil.random9Str(), userCode, arrear.get('count'), arrear.get('startCount'), (arrear.get('count') + arrear.get('startCount')), arrear.get('price'), str(arrear.get('breach')), itemMoney, DateUtil.getCutDate(month=index), DateUtil.getDate(format='%Y-%m-%d %H:%M:%S'), DateUtil.getDate(format='%Y-%m-%d %H:%M:%S')))
                        conn.commit()
                        index = index + 1
        SQLite.close(conn)
예제 #30
0
    def applyBill(self, args):
        self.db.execute('SELECT * FROM %s WHERE usercode = ?' %Global.GLOBAL_TABLE_PAYMENT_USER, (args.get('userCode'),))
        resultInfo = self.db.fetchone()
        if resultInfo == None:
            return None
        # 查询用户欠费信息
        self.db.execute('SELECT * FROM %s WHERE usercode = ?' %Global.GLOBAL_TABLE_USER_ARREARS, (args.get('userCode'), ))
        userArrears = self.db.fetchall()
        paymentResultInfos = []
        for arrear in userArrears:
            channelCode = arrear['channelcode']
            itemOutSerialNo = ''
            for paymentItem in json.loads(args.get('paymentOrderItemList')):
                if str(channelCode) == str(paymentItem.get('channelCode')):
                    itemOutSerialNo = paymentItem.get('itemOutSerialNo')
            info = {
                'itemOutSerialNo': itemOutSerialNo,
                'agencyCode': args.get('agencyCode'),
                'userCode': args.get('userCode'),
                'charge': arrear['breach'],
                'itemNo': RandomUtil.random20Str(),
                'money': arrear['itemmoney'],
                'month': arrear['month'],
                'count': str(arrear['count']),
                'startCount': str(arrear['startcount']),
                'endCount': str(arrear['endcount']),
                'status': resultInfo['querystatus'],
                'type': resultInfo['paymentType'],
                'memo': resultInfo['memo'],
                'address': resultInfo['address'],
                #'price': resultInfo['price'],
                'username': resultInfo['username']}
            paymentResultInfos.append(info)
        easyLifeOrderNo = RandomUtil.random32Str()
        self.db.execute('SELECT balance FROM %s WHERE merchantkey = ? ORDER BY updatetime desc limit 1' %Global.GLOBAL_TABLE_BALANCE, (Global.GLOBAL_MERCHANTS.get('lencee'),))
        querybalance = self.db.fetchone()
        if not querybalance:
            # 商户预存款未找到
            pass
        balance = querybalance['balance']
        if resultInfo['paymentstatus'] == 'SUCCESS':
            orderStatus = 'SUCCESS'
            resultCode = '0000000'
            # 修改商户预存款
            balance = float(format(balance - float(args.get('paymentAmount')), '.2f'))
            self.db.execute('UPDATE %s SET balance = ?, updatetime = ? WHERE merchantkey = ?' %Global.GLOBAL_TABLE_BALANCE, (balance, DateUtil.getDate(format='%Y-%m-%d %H:%M:%S'), Global.GLOBAL_MERCHANTS.get('lencee')))
            self.conn.commit()
        elif resultInfo['paymentstatus'] == 'FAIL':
            orderStatus = 'FAIL'
            resultCode = resultInfo['paymentresultcode']
        elif resultInfo['paymentstatus'] == 'HANGUP':
            orderStatus = 'PROCESSING'
            resultCode = '0000107'

        # 是否保持挂起状态
        if resultInfo['ishangup']:
            iskeephangup = 1
        else:
            iskeephangup = 0
        self.db.execute('INSERT INTO easylife_payment_order(easylifeorderno, outbizno, status, paymenttype, usercode, resultcode, paymentamount, iskeephangup, addtime, updatetime) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (easyLifeOrderNo, args.get('outBizNo'), orderStatus, resultInfo['paymenttype'], args.get('userCode'), resultCode, float(args.get('paymentAmount')), iskeephangup, DateUtil.getDate(format='%Y-%m-%d %H:%M:%S'), DateUtil.getDate(format='%Y-%m-%d %H:%M:%S')))
        self.conn.commit()

        # 如果用户表flag=1,更新用户查询结果码为:0000121
        if resultInfo['flag'] == 1:
            self.db.execute('UPDATE %s SET queryresultcode = ? WHERE usercode = ?' %Global.GLOBAL_TABLE_PAYMENT_USER, ('0000121', args.get('userCode'),))
            self.conn.commit()
            logger.info(u'更新用户%s查询结果码:%s' %(args.get('userCode'), '0000121'))

        result = {
            'success': 'T',
            'signType': 'MD5',
            'outBizNo': args.get('outBizNo'),
            'orderStatus': orderStatus,
            'orderNo': args.get('orderNo'),
            'easyLifeOrderNo': easyLifeOrderNo,
            'channelId': RandomUtil.random6Str(),
            'balance': balance,
            'resultCode': resultInfo['paymentresultcode'],
            'paymentResultInfos': '%s' %json.dumps(paymentResultInfos, ensure_ascii=False)
        }
        from operator import itemgetter
        import urllib
        sortList = sorted(result.iteritems(), key=lambda d:d[0])
        sign = '&'.join(['%s=%s' %(k,v) for k,v in sortList])
        sign += Global.GLOBAL_MERCHANTS.get('lencee')
        result['sign'] = MD5Util.md5(sign)
        return result