Exemplo n.º 1
0
class DataBase:
    _conn = None
    _cursor = None

    def __init__(self, conf, database):
        self.log = Log()
        self.host = conf['host']
        self.user = conf['user']
        self.passwd = conf['passwd']
        self.database = database

        # 连接数据库
    def connectDatabase(self):
        try:
            self._conn = pymysql.connect(self.host, self.user, self.passwd)
            self._conn.select_db(self.database)
            self._cursor = self._conn.cursor()
            self.log.info("Connect DB successfully!")
        except ConnectionError as ex:
            self.log.error(str(ex))

    # 执行sql语句   ---查询
    def execute(self, sql):
        self.connectDatabase()
        self._cursor.execute(sql)
        data = self._cursor.fetchall()
        return data

    # def executeSQL(self, sql, params):
    #     self.connectDB()
    #     # executing sql
    #     self.cursor.execute(sql, params)
    #     # executing by committing to DB
    #     self.db.commit()
    #     return self.cursor

    # def get_all(self, cursor):
    #     #     value = cursor.fetchall()
    #     #     return value
    #     #
    #     # def get_one(self, cursor):
    #     #     value = cursor.fetchone()
    #     #     return value

    # 关闭数据库
    def close(self):
        if self._conn and self._cursor:
            self._cursor.close()
            self._conn.close()
            print("Database closed!")
Exemplo n.º 2
0
class YamlRead(object):

    def __init__(self, path: str):
        self.path = path
        self.log = Log().get_logger()
        if not os.path.exists(self.path):
            self.log.error(f"指定文件路径不存在:{self.path}")
        self.yml = None
        with open(path, 'r', encoding='utf-8') as f:
            try:
                self.yml = yaml.safe_load(f.read())
            except Exception as e:
                print(e)

    def get_cases(self):
        try:
            cases = self.yml['testcase']
            return cases
        except KeyError:
            self.log.error(f"从文件: {self.path} 获取testcase失败")
Exemplo n.º 3
0
class DataBaseOperate(object):
    def __init__(self):
        self.__log = Log("DataBaseOperate", 'DEBUG').logger
        self.__db_pool = None

    def creat_db_pool(self, mysql):
        user = mysql.get('MYSQL_USER')
        password = mysql.get('MYSQL_PASSWD')
        port = int(mysql.get('MYSQL_PORT'))
        host = mysql.get('MYSQL_HOST')
        self.__log.debug('创建数据库连接池:%s' % host)
        self.__db_pool = PooledDB(creator=pymysql,
                                  mincached=3,
                                  maxcached=5,
                                  maxshared=0,
                                  maxconnections=20,
                                  blocking=True,
                                  maxusage=None,
                                  setsession=None,
                                  host=host,
                                  port=port,
                                  user=user,
                                  db=None,
                                  passwd=password)
        self.__log.debug('创建数据库连接池完成!')

    def query_data(self, sql):
        con = self.__db_pool.connection()
        cursor = con.cursor(cursor=pymysql.cursors.DictCursor)
        try:
            self.__log.error(sql)
            cursor.execute(sql)
            results = cursor.fetchall()
            self.__log.debug(results)
            for result in results:
                for fields in result:
                    if isinstance(result[fields], datetime.datetime):
                        result[fields] = str(
                            result[fields].strftime('%Y-%m-%d %H:%M:%S'))
                    elif isinstance(result[fields], datetime.date):
                        result[fields] = str(
                            result[fields].strftime('%Y-%m-%d'))
                    elif isinstance(result[fields], decimal.Decimal):
                        result[fields] = float(result[fields])
            return results
        except Exception as e:
            self.__log.error('执行sql异常:\n%s' % e)
            self.__log.error(sql)
        finally:
            cursor.close()
            con.close()

    def close_db_pool(self):
        self.__db_pool.close()
Exemplo n.º 4
0
class Config_Http():
    def __init__(self):
        global shcme, baseUrl, ip, username, password, port, dataname
        shcme = local_Read_Config.get_HTTP("schme")
        baseUrl = local_Read_Config.get_HTTP("baseUrl")
        ip = local_Read_Config.get_DATA("ip")
        username = local_Read_Config.get_DATA("username")
        password = local_Read_Config.get_DATA("password")
        port = local_Read_Config.get_DATA("port")
        dataname = local_Read_Config.get_DATA("dataname")
        self.logger = Log().logger
        self.header = {}
        self.param = {}
        self.data = {}
        self.url = None
        self.file = {}

    #获取请求路径
    def get_Path(self, url):
        self.url = shcme + baseUrl + url
        print(self.url)

    #设置请求头
    def get_Heardes(self, headers):

        self.header = headers

    def get_cookies(self, cookies):
        self.cookies = cookies

    #设置请求体
    #1,get请求传参 paerams 2,post请求传参 data
    def get_parm(self, param):
        self.params = param

    def get_data(self, data):
        self.data = data

    def get_file(self, filename):
        porDir = readConfig.porDir
        testFilePath = os.path.join(porDir, "testFile")
        if not os.path.exists(testFilePath):
            os.mkdir(testFilePath)
        if filename != "":
            filPath = testFilePath + filename
            self.file = {"file", open(filPath, "rb")}
        if filename == "" or filename is None:
            self.state = 1

    def get_datebase(self):
        mysql_conn = pymysql.Connect(
            host=ip,
            port=int(port),
            user=username,
            password=password,
            db=dataname,
        )
        print(mysql_conn)
        return mysql_conn

    #设置get请求

    def set_get(self):
        try:
            response = requests.get(self.url,
                                    params=self.params,
                                    headers=self.header,
                                    cookies=self.cookies)
            return response
        except TimeoutError:
            self.logger.error("Time out")
            return None
        #post请求
    def set_post(self):
        try:
            response = requests.post(url=self.url,
                                     headers=self.header,
                                     data=self.data)
            return response
        except TimeoutError:
            self.logger.error("Time out")
            return None

    def set_Post_With_File(self):
        try:
            response = requests.post(self.url,
                                     headers=self.header,
                                     data=self.data,
                                     file=self.file)
            return response
        except TimeoutError:
            self.logger.error("Time out")
            return None

    def set_Post_with_json(self):
        try:
            response = requests.post(self.url,
                                     headers=self.header,
                                     data=self.data)
            return response
        except TimeoutError:
            self.logger.error("Time out")
Exemplo n.º 5
0
        if timer is not None:
            timer.tick(dt)
        elif state == WAITING_FOR_PHOTO:
            if not pygame.mixer.music.get_busy():
                soundDone()

        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if event.key == K_e:
                    language = 'en'
                    startGame()
                elif event.key == K_h:
                    language = 'he'
                    startGame()
                elif event.key == K_a:
                    language = 'ar'
                    startGame()
                elif event.key == K_q:
                    isGameRunning = False
                    Log.info('QUIT')

        pygame.display.flip()
        clock.tick(60)

    pygame.quit()
    cv2.destroyAllWindows()
except:
    excType, excValue, excTraceback = sys.exc_info()
    lines = traceback.format_exception(excType, excValue, excTraceback)
    Log.error('\n'.join(lines))
Exemplo n.º 6
0
                LOG.debug("create mappings response: " + str(res))
                if "acknowledged" in res:
                    if res["acknowledged"]:
                        LOG.info("[Mapping] create " + index + "/" + doc_type +
                                 " success")
                    else:
                        LOG.info("[Mapping] create " + index + "/" + doc_type +
                                 " failed")
                    return res["acknowledged"]
                else:
                    raise Exception(res)
            else:
                LOG.info("[Index] create index=" + index + " success")
                return True
        else:
            LOG.error("create " + index + "/" + doc_type + " Failed")
            return False


def writer_data():
    es = create_client()
    result = CONN.select(SQL, 10)
    for row in result:
        ip = {}
        ip.setdefault("ip_addr", row[0])
        ip.setdefault("port", row[1])
        ip.setdefault("city", row[2])
        ip.setdefault("country", row[3])
        id = hashlib.md5(row[0] + "-" + str(row[1])).hexdigest()
        source = json.dumps(ip, lambda o: o.__dict__)
        LOG.debug(id + " : " + source)