Esempio n. 1
0
async def handle_404(request, response):
    user = request.match_info.get("userKey") or 'x'
    product = request.match_info.get("productKey") or 'x'

    error_log(user, product, "404")

    raise web.HTTPNotFound()
Esempio n. 2
0
 def saveData(self):
   try:
     res = self.model.save()
   except Exception, e:
     log.error_log(u"%s" % e)
     log.error_log(traceback.format_exc().decode(define.CODEC))
     QMessageBox.information(self, u"数据保存错误", u"%s" % e)
     return
Esempio n. 3
0
def run_testcases():
    if len(sys.argv) == 1:
        warning_log("No test cases for run.") 
    elif len(sys.argv) == 2:
        pass_log("Running python main.py {0}".format(sys.argv[1]))
        os.system("python {0}".format(sys.argv[1]))
        pass_log("Run end")
        
    else:
        error_log("You need use it as $python main.py test.py")
Esempio n. 4
0
def onclick_submit():

    if username.get().strip() == "" or password.get().strip() == "":
        messagebox.showwarning("Warning", "Cannot accept empty fields")
        return

    try:
        conn = sqlite3.connect('db/amas.db')
        # Create cursor
        c = conn.cursor()

        c.execute("SELECT * FROM users")
        records = c.fetchall()

        username_exists = False
        for record in records:
            print(record)
            if username.get().strip() == record[0].strip():
                username_exists = True

        if username_exists == False:

            # Insert Into Table
            c.execute("INSERT INTO users VALUES(:username, :password)", {
                'username': username.get(),
                'password': password.get(),
            })

            messagebox.showinfo("Success", username.get() + " was added!")

            # Commit Changes
            conn.commit()
            # Close Connection
            conn.close()

            # Clear The Text Boxes
            username.delete(0, END)
            password.delete(0, END)
        else:
            messagebox.showwarning(
                "Warning",
                username.get() + " already exist, try another username!")

    except IOError:
        raise RuntimeError
        messagebox.showerror(
            "Error",
            "An error occured while saving user" + str(sys.exc_info()[0]))

        log.error_log("Error adding new user")
Esempio n. 5
0
def load_schedule():
    try:
        conn = sqlite3.connect('db/amas.db')
        # Create cursor
        c = conn.cursor()

        c.execute("SELECT * FROM pregnantwomen")
        records = c.fetchall()  

        for record in records: 
            LMP_date == record[3].strip()

            if datetime.date.today() < LMP + datetime.timedelta(weeks=40):
                nextappointment = nextappointment_calculator(LMP_date, 28)
                if nextappointment == datetime.date.today.timedelta(1):
                    
                    # Save SMS to database
                    c.execute("""CREATE TABLE IF NOT EXISTS sms 
                                (
                                    sms text NOT NULL,
                                    phonenumber text NOT NULL,
                                    datesaved text NOT NULL,
                                    datesent text,                                    
                                    sent text NOT NULL
                                )
                            """)
                    
                    phonenumber = record[2].strip()

                    sms = "Hi {name}, \n\nThis is a friendly reminder for your ANC appointment at our clinic tomorrow {date} by 10am. \n\nThanks"
                    sms = sms.format(name = record[0].strip(), date = nextappointment)
                    
                    # Insert Into Table
                    c.execute("INSERT INTO sms VALUES(:sms, :datesaved, :datesent, :sent)",
                                {                        
                                    'sms' : sms,
                                    'phonenumber' : phonenumber,
                                    'datesaved' : datetime.date.today(),
                                    'sent' : '0'                        
                                }                
                            )

        # Commit Changes
        conn.commit()
        # Close Connection
        conn.close()
        log.error_log("Schedule loaded!")

    except IOError as e:
        raise RuntimeError
        
        log.error_log("Schedule not loaded! " + str(e))
        
    except AttributeError as e:
        raise RuntimeError
        log.error_log("Schedule not loaded! " + str(e))

    except Exception as e:
        log.error_log("Schedule not loaded! " + str(e))
Esempio n. 6
0
 def saveHeader(self):
   try:
     res = self.model.checkHeaderData()
     if res is None:
       if self.__parent.updateHeaderInfo(self.headerInfo().clone()):
         self.model.saveHeaderData()
         self.setEnableSaveAndDiscard(False)
         self.emit(SIGNAL("headerSaved"))
         self.__dirty = False
     else:
       QMessageBox.information(self, u"表头错误", res)
   except Exception, e:
     log.error_log(u"%s" % e)
     log.error_log(traceback.format_exc().decode(define.CODEC))
     self.headerDataError(u"保存文件错误", u"%s" % e)
Esempio n. 7
0
    def run(self):
        # while True:
        global max_thread_count
        if max_thread_count < threading.activeCount():
            max_thread_count = threading.activeCount()

        # print("Active Threads:{} Current Client Thread:{} max_thread_count:{}\n".format(
        #     threading.activeCount(), threading.currentThread(), max_thread_count))
        """ iso-8859-1 decoding to decode image(binary files without any issues) """
        msg = self.client_socket.recv(4096).decode("iso-8859-1")
        """
            If msg is None... For now sendd 400
        # """
        # print("****************************  Request msg: Start  ********************")
        # print(msg)
        # print("*****************************   Request msg: end   ********************\n")

        try:
            self.extract_msg(msg)
            self.extract_headers()
        except:
            self.client_socket.close()
            request_line = None
            log.error_log(status_code=500, size=len("Server Error"), request_line=request_line,
                          client_ip=self.ip, user_agent=self.req_headers_general['User-Agent'], logDir=logDir)
            return

        if self.res_headers['Status'] == 400:
            self.process_query()
            self.client_socket.close()
            return
        # print("****************************  Request Headers: Start  ********************")
        # print(self.headers)
        # print("************************   Request Headers: end   ********************\n")

        request_line = self.req_headers_general['method'] + " " + \
            self.req_headers_general['uri'] + " " + \
            self.req_headers_general['protocol']
        try:
            self.process_query()
            self.client_socket.close()
            log.access_log(status_code=self.res_headers["Status"], size=self.res_headers["Content-Length"], request_line=request_line,
                           client_ip=self.ip, user_agent=self.req_headers_general['User-Agent'], logDir=logDir)
        except:
            self.client_socket.close()
            log.error_log(status_code=500, size=len("Server Error"), request_line=request_line,
                          client_ip=self.ip, user_agent=self.req_headers_general['User-Agent'], logDir=logDir)
            return
Esempio n. 8
0
def send_sms():
    try:
        conn = sqlite3.connect('db/amas.db')
        # Create cursor
        c = conn.cursor()

        c.execute("SELECT *, oid FROM sms WHERE sent = 0")
        records = c.fetchall()
        
        for record in records: 
            #send SMS module
            status = bulksmsnigeria_module(record[1], 'AMAS', record[0])

            if status == 'success':
                c.execute("""UPDATE sms SET
                    datesent = :_datesent,
                    sent = :_sent

                    WHERE oid = :_oid   
                    """,
                    {
                        'datesent' : datetime.date.today(),
                        'sent' : '1',
                        '_oid': oid
                    }                
                )
            else:
                log.error_log("Couldn't sent with response {0}".format(status))
            
        # Commit Changes
        conn.commit()
        # Close Connection
        conn.close()
        log.error_log("SMS Sent!")

    except IOError as e:
        raise RuntimeError
        
        log.error_log("SMS not sent! " + str(e))
        
    except AttributeError as e:
        raise RuntimeError
        log.error_log("SMS not sent! " + str(e))

    except Exception as e:
        log.error_log("SMS not sent! " + str(e))
Esempio n. 9
0
    def __init_user_info(self):
        #从文件读取
        data = easy_read.read_from_utf8(self.login_record_file_path)
        if data is None:
            last_pos = -1
            last_md5 = 0
        else:
            #local_file文件格式:第一行记录文件md5值,第二行记录上次答题最后答题用户的位置
            lines = data.split('\n')
            last_md5 = lines[0]
            if len(lines) == 2:
                last_pos = int(lines[1])
            else:
                last_pos = -1

        #计算当前user_info文件的md5值
        new_md5 = self.calc_md5(self.user_info_file_path)
        self.md5 = new_md5

        #新旧user_info不同,为了保证将所有用户都答题,讲user_info中的用户全部重新答
        if last_md5 != new_md5:
            self.pos = -1
            log.success_log('new', '')
            log.error_log('', 'new')
        else:
            self.pos = last_pos

        data = easy_read.read_from_utf8(self.user_info_file_path)
        lines = data.split('\n')
        for line in lines:

            #跳过空行
            if len(line) == 0:
                continue

            username, password = line.split(' ')
            self.user_info.append([username, password])
Esempio n. 10
0
    def login(self, username, password, driver):
        #登录三次失败后,放弃本次登录
        err_login_cnt = 0

        driver.get('http://xxjs.dtdjzx.gov.cn/')
        sleep(2)

        # 关闭提示框
        cancel_tip = driver.find_elements_by_xpath(
            "//body/div[@id='myxiaoxi']/div/div/div[@class='modal-header']/button"
        )
        if cancel_tip[0]:
            cancel_tip[0].click()
            sleep(2)

        #点击左侧竞赛答题
        driver.find_element_by_id('lbuts').click()
        sleep(2)

        #选择党员身份
        shenfen = driver.find_element_by_id('shenfen')
        shenfen.find_element_by_xpath("//option[@value='0']").click()
        btn_confirm = driver.find_element_by_id('bts')
        btn_confirm.click()

        while err_login_cnt < 3:
            #填入用户名密码验证码
            driver.find_element_by_id('username').send_keys(username)
            sleep(1)
            driver.find_element_by_id('password').send_keys(password)
            sleep(1)
            val_code = self.recognize.recognize(driver)
            driver.find_element_by_id("validateCode").send_keys(val_code)
            sleep(1)

            #点击登录
            driver.find_element_by_class_name('js-submit').click()
            sleep(3)

            #若登录失败,增加失败计数,从新开始登录
            if ('https://sso.dtdjzx.gov.cn/sso/login?error' ==
                    driver.current_url):
                err_login_cnt += 1
                continue

            #关闭提示框

            cancel_tip = driver.find_elements_by_xpath(
                "//body/div[@id='myxiaoxi']/div/div/div[@class='modal-header']/button"
            )
            if cancel_tip[0]:
                cancel_tip[0].click()
                sleep(2)

            #登录成功后获取答题次数
            opportunity = driver.find_element_by_class_name('l_jihui')
            #剩余答题次数为0,不进行后续操作
            if '0' == opportunity.text[2]:
                driver.quit()
                return None

            driver.find_element_by_id("lbuts").click()
            sleep(3)
            log.success_log('username', username)

            return driver

        #登录错误次数超过三次,可认为登录错误归因于用户名密码错误
        driver.quit()
        log.error_log(username, 'error username/password!')
        return None
Esempio n. 11
0
    fp.close()

    log.info_log(("[begin crawl dir url %d]" % index) + req.url)
    try:

        while (1):
            if req.retry_times == 0:
                req.error = 1
                break

            try:
                res = urllib.urlopen(req.url).read()
            except Exception, e:
                req.retry_times -= 1
                time.sleep(1)
                log.error_log("try again!" + req.url)
                continue

            if res:
                parser.dir_parse(res, result_list)
                break
            else:
                req.retry_times -= 1
                time.sleep(1)
                log.error_log("try again!" + req.url)

        if req.error == 0:
            #make dir result
            item_list = []
            while (len(result_list) > 0):
                crawl_req = result_list.pop()
Esempio n. 12
0
	fp.close()

	log.info_log(("[begin crawl dir url %d]" % index)+ req.url)
	try:

		while (1):
			if req.retry_times ==0:
				req.error=1
				break
	
			try:
				res=urllib.urlopen(req.url).read()
			except Exception,e:
				req.retry_times -=1
				time.sleep(1)
				log.error_log("try again!"+req.url)
				continue

			if res:
				parser.dir_parse(res,result_list)
				break
			else:
				req.retry_times -=1
				time.sleep(1)
				log.error_log("try again!"+req.url)

		if req.error==0:
			#make dir result
			item_list =[]
			while( len(result_list)>0):
				crawl_req = result_list.pop()
Esempio n. 13
0
from logging import getLogger

from account import Account

import parameter

def _idle(seconds=settings.IDLE_INTERVAL):
    time.sleep(seconds)

running = False

PARA = parameter.get()

log.run_log()  #设置log
log.error_log()  #提取runlog中的error信息
log.performance_log_roach()  #设置小强需要的log
RLOG = getLogger('runlog')

USERLIST = Account().parse(PARA.userrule, PARA.psdrule)

def get_time(user_len):
    settings.BEFORE_READY *= user_len

    settings.BEFORE_LISTARENA *= user_len

    settings.BEFORE_SUBRESULT *= user_len

    settings.USER_RANDOM_SLEEP_TIME *= user_len

if __name__ == "__main__":
Esempio n. 14
0
def onclick_edit():
    next_appointment = services.nextappointment_calculator(
        calendar_LMP.selection_get(), spinbox_cycle_length.get())

    if entry_firstname.get().strip() == "" or entry_lastname.get().strip(
    ) == "" or entry_phonenumber.get().strip() == "":
        messagebox.showwarning("Warning", "Cannot accept empty fields")
        return

    if calendar_LMP.selection_get() == datetime.date.today():
        messagebox.showwarning("Warning", "You can't select today's date")
        return

    next_appointment = services.nextappointment_calculator(
        calendar_LMP.selection_get(), spinbox_cycle_length.get())

    try:
        # Create a database or connect to one
        conn = sqlite3.connect('db/amas.db')
        # Create cursor
        c = conn.cursor()

        # record_id = services.pregnant_woman_ID # record ID from previous windows

        c.execute(
            """UPDATE pregnantwomen SET
                    firstname = :first,
                    lastname = :last,
                    phonenumber = :phone,
                    LMP = :LM,
                    cyclelength = :cycle

                    WHERE oid = :oid_ID   
                    """, {
                'first': entry_firstname.get(),
                'last': entry_lastname.get(),
                'phone': entry_phonenumber.get(),
                'LM': calendar_LMP.selection_get(),
                'cycle': spinbox_cycle_length.get(),
                'oid_ID': record_id
            })

        # Commit Changes
        conn.commit()
        # Close Connection
        conn.close()

        messagebox.showinfo("Success",
                            entry_firstname.get() + " " + " was edited")
        # import view_pregnant_women
        root.destroy()

    except IOError as e:
        raise RuntimeError
        messagebox.showerror("Error", "An error occured while updating " +
                             entry_firstname.get() + " " +
                             str(e))  #str(sys.exc_info()[0]))

        log.error_log("Error adding new pregnant woman")

    except AttributeError as e:
        raise RuntimeError
        messagebox.showerror("Error", "An error occured while saving user" +
                             str(e))  #str(sys.exc_info()[0]))

        log.error_log("Error adding new pregnant woman")

    except Exception as e:

        messagebox.showerror("Error", "An error occured while saving user" +
                             str(e))  #str(sys.exc_info()[0]))

        log.error_log("Error adding new pregnant woman")
Esempio n. 15
0
def onclick_submit():
    next_appointment = services.nextappointment_calculator(
        calendar_LMP.selection_get(), spinbox_cycle_length.get())

    if entry_firstname.get().strip() == "" or entry_lastname.get().strip(
    ) == "" or entry_phonenumber.get().strip() == "":
        messagebox.showwarning("Warning", "Cannot accept empty fields")
        return

    if calendar_LMP.selection_get() == datetime.date.today():
        messagebox.showwarning("Warning", "You can't select today's date")
        return

    next_appointment = services.nextappointment_calculator(
        calendar_LMP.selection_get(), spinbox_cycle_length.get())

    uniqueID = services.generate_uniqueID(entry_firstname.get(),
                                          entry_lastname.get())

    try:
        conn = sqlite3.connect('db/amas.db')
        # Create cursor
        c = conn.cursor()

        c.execute("""CREATE TABLE IF NOT EXISTS pregnantwomen 
                    (
                        firstname text NOT NULL,
                        lastname text NOT NULL,
                        phonenumber text NOT NULL,
                        LMP text NOT NULL,
                        cyclelength integer,
                        uniqueID text NOT NULL,
                        registrationdate text NOT NULL,
                        nextappointment text
                    )
                """)

        c.execute("SELECT * FROM pregnantwomen")
        records = c.fetchall()

        for record in records:
            if uniqueID == record[5].strip():
                uniqueID = services.generate_uniqueID(entry_firstname.get(),
                                                      entry_lastname.get())

        # Insert Into Table
        c.execute(
            "INSERT INTO pregnantwomen VALUES(:firstname, :lastname, :phonenumber, :LMP, :cyclelength, :uniqueID, :registrationdate, :nextappointment)",
            {
                'firstname': entry_firstname.get(),
                'lastname': entry_lastname.get(),
                'phonenumber': entry_phonenumber.get(),
                'LMP': calendar_LMP.selection_get(),
                'cyclelength': spinbox_cycle_length.get(),
                'uniqueID': uniqueID,
                'registrationdate': datetime.date.today(),
                'nextappointment': next_appointment
            })

        # Commit Changes
        conn.commit()
        # Close Connection
        conn.close()

        messagebox.showinfo("Success", "New pregnant woman added")

        # Clear The Text Boxes
        entry_firstname.delete(0, END)
        entry_lastname.delete(0, END)
        entry_phonenumber.delete(0, END)

    except IOError as e:
        raise RuntimeError
        messagebox.showerror("Error", "An error occured while saving user" +
                             str(e))  #str(sys.exc_info()[0]))

        log.error_log("Error adding new pregnant woman")

    except AttributeError as e:
        raise RuntimeError
        messagebox.showerror("Error", "An error occured while saving user" +
                             str(e))  #str(sys.exc_info()[0]))

        log.error_log("Error adding new pregnant woman")

    except Exception as e:

        messagebox.showerror("Error", "An error occured while saving user" +
                             str(e))  #str(sys.exc_info()[0]))

        log.error_log("Error adding new pregnant woman")
Esempio n. 16
0
import http.cookiejar
import log

__name__ = 'test'

if __name__ == "__main__":
    user_list, last_pos = auto_login.get_user_info_from_txt()

    print(last_pos)

    for pos in range(last_pos + 1, len(user_list)):
        user = user_list[pos]
        driver = auto_login.login_with_chrome(user[0], user[1])
        auto_login.record_pos_2_local(pos)
        if None == driver:
            log.error_log(user[0], ' login error!')
            continue
        elif 'finish' == driver:
            log.success_log(user[0], '  has finish the quiz!')
            continue

        score = do_quiz.do_practice(driver)
        log.success_log(user[0], score)

        driver.quit()

        sleep(1)

    print('all user has finish the quiz')

if __name__ == 'file_test':