예제 #1
0
def test_frame():
    log = Log("UI测试").get_logger()
    driver = webdriver.Ie()
    # driver = webdriver.Edge()
    # driver = webdriver.Firefox()
    # driver = webdriver.Chrome()
    driver.set_window_size(1100, 600)  # 设置窗口大小
    # driver.maximize_window()
    """
    163邮箱登录的例子来用新的switch_to方法写一下,并通过观察,
    我们发现进入这个页面后焦点直接就定位到输入框里了,所以我们可以通过active_element()来定位。
    """
    # 进入163邮箱首页
    driver.get("http://mail.163.com/")
    time.sleep(2)
    # 切换到包含登录框的frame下
    driver.switch_to.frame("x-URS-iframe")  # 根据frame的id切换到frame
    # driver.switch_to.parent_frame() # 可以切换到上一层的frame,对于层层嵌套的frame很有用
    time.sleep(2)

    # 通过定位输当前焦点元素,并再次输入数据
    driver.switch_to.active_element.send_keys("123")
    # driver.find_element_by_css_selector('form>div>div>div>input').send_keys("123")
    log.info(driver.title)  # 打印原页面title

    time.sleep(2)
    driver.quit()
예제 #2
0
class ServerChan(object):
    def __init__(self):
        self.log = Log().get_logger()
        self.host = 'https://sc.ftqq.com/'
        self.sckey = 'SCU36505Te655df39dfe25061e9d9cbfa1a4faf925bfce30131860.send'

    def send(self):
        url = ''.join([self.host, self.sckey])
        # text:消息标题,最长为256,必填。
        # desp:消息内容,最长64Kb,可空,支持MarkDown。
        text = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        params = {'text': text, 'desp': 'good'}
        r = requests.request('post', url=url, params=params)  # get或post皆可
        if r.json()['errno'] == 0:
            self.log.info('发送成功')
        else:
            self.log.info('发送失败:%s' % r.json()['errmsg'])

    def timeing(self):
        scheduler = BlockingScheduler()
        scheduler.add_job(func=self.send,
                          trigger='cron',
                          day_of_week='0-6',
                          second='*/5')
        scheduler.start()
예제 #3
0
class ThreadingStudy(object):
    def __init__(self):
        self.log = Log().get_logger()

    def test(self, t=0):
        print('thread %s is running...' % threading.current_thread().name)
        for i in range(5):
            time.sleep(2)
            self.log.info(t)
        print('thread %s is ended...' % threading.current_thread().name)
예제 #4
0
class Pdf(object):
    def __init__(self):
        self.log = Log().get_logger()
        self.path = r'C:\AProjectCode\Python\python3_interface\study_case\data\开发指南.pdf'
        # self.path = r'C:\AProjectCode\Python\python3_interface\study_case\data\a.pdf'
        self.out_path = r'C:\AProjectCode\Python\python3_interface\study_case\data\aa.txt'

    def read(self):
        with open(self.path, 'rb') as fp:  # 以二进制读模式打开
            praser = PDFParser(fp)  # 用文件对象来创建一个pdf文档分析器
            retstr = StringIO()
            doc = PDFDocument()  # 创建一个PDF文档
            praser.set_document(doc)  # 连接分析器 与文档对象
            doc.set_parser(praser)  # 获取解析内容
            doc.initialize()  # 提供初始化密码,如果没有密码就创建一个空的字符串
            if not doc.is_extractable:  # 检测文档是否提供txt转换
                self.log.info("文档不可以进行txt转换")
            else:
                rsrcmgr = PDFResourceManager()  # 创建PDf 资源管理器 来管理共享资源
                laparams = LAParams()  # 创建一个PDF设备对象
                device = PDFPageAggregator(rsrcmgr, laparams=laparams)
                interpreter = PDFPageInterpreter(rsrcmgr,
                                                 device)  # 创建一个PDF解释器对象
                with open(self.out_path, 'w', encoding='utf-8') as f:
                    # 循环遍历列表,每次处理一个page的内容
                    for page in doc.get_pages():  # doc.get_pages() 获取page列表
                        interpreter.process_page(page)
                        layout = device.get_result()  # 接受该页面的LTPage对象
                        # 这里layout是一个LTPage对象 里面存放着 这个page解析出的各种对象 一般包括LTTextBox, LTFigure, LTImage, LTTextBoxHorizontal 等等 想要获取文本就获得对象的text属性,
                        for x in layout:
                            if hasattr(x, 'get_text'):
                                results = x.get_text()
                                self.log.info(results)
                                f.write(results)

    def read2(self):
        pdfFile = open(
            r'C:\AProjectCode\Python\python3_interface\study_case\data\开发指南.pdf',
            'rb')
        retstr = io.StringIO()
        laparams = LAParams()
        rsrcmgr = PDFResourceManager()
        device = TextConverter(rsrcmgr, retstr, laparams=laparams)
        process_pdf(rsrcmgr,
                    device,
                    pdfFile,
                    pagenos=set(),
                    maxpages=0,
                    password='',
                    check_extractable=True)
        device.close()
        print(retstr.getvalue())
        pdfFile.close()
예제 #5
0
class MyTest(unittest.TestCase,Page):

    @classmethod
    def setUpClass(self):
        self.logger = Log()
        self.logger.info('############################### START ###############################')
        self.driver = browser.select_browser(globalparam.browser)
        # self.driver.implicitly_wait(10)
        Page(self.driver).max_window()

    @classmethod
    def tearDownClass(self):
        self.driver.quit()
        self.logger.info('###############################  End  ###############################')
예제 #6
0
class JVMStart(object):

    def __init__(self):
        self.log = Log("jvm初始化").get_logger()

    """ 
    启动Java虚拟机
    """

    def start_jvm(self, jar_list):
        # 获得默认jvm路径
        jvm_path = jpype.getDefaultJVMPath()
        # self.log.info(jvm_path)

        # 你的java扩展包的路径
        ext_classpath = ''

        # 判断系统类型,Linux系统使用“ :”分隔
        sysstr = platform.system()
        if sysstr == "Windows":
            # java扩展包的路径或class文件所在文件夹路径,注意:class文件路径是它所在的上级文件夹
            ext_classpath = config.sdk_path
            for name in jar_list:
                ext_classpath += ';' + config.sdk_path + '%s' % name
        elif sysstr == "Linux":
            ext_classpath = config.sdk_path + 'sdk'
            for name in jar_list:
                ext_classpath = ':' + config.sdk_path + '%s' % name
        # self.log.info("系统类型:" + sysstr)

        # 判断 JVM 是否已启动
        if not jpype.isJVMStarted():
            # 启动Java虚拟机,并加载jar包
            jpype.startJVM(jvm_path, '-ea', '-Djava.class.path=%s' % ext_classpath)
            jpype.java.lang.System.out.println("startJVM success!")
            if jpype.isJVMStarted():
                return True
            else:
                return False
        else:
            return True

    """ 
    关闭Java虚拟机
    """

    def shutdown_jvm(self):
        if jpype.isJVMStarted():
            self.log.info("关闭jvm")
            jpype.shutdownJVM()
예제 #7
0
class RedisStudy(object):

    def __init__(self):
        self.log = Log().get_logger()

    def study(self):
        # 1、一般连接方式
        r = redis.Redis(host='127.0.0.1', port=6379, db=0)
        r.set('name', 'zhangsan0')  # 添加
        self.log.info(r.get('name'))  # 获取

        # 2、连接池
        pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
        r = redis.Redis(connection_pool=pool)
        r.set('name', 'zhangsan2')  # 添加
        self.log.info(r.get('name'))  # 获取
예제 #8
0
class MyTest(unittest.TestCase):
    """
    The base class is for all testcases.
    """
    def setUp(self):
        self.logger = Log()
        self.logger.info(
            '############################### START ###############################'
        )
        self.dr = basepage(global_parameter.browser)
        self.dr.max_window()

    def tearDown(self):
        # self.dr.quit()
        self.logger.info(
            '###############################  End  ###############################'
        )
예제 #9
0
def test_alert():
    log = Log("UI测试").get_logger()
    driver = webdriver.Firefox()
    driver.set_window_size(960, 540)  # 设置窗口大小
    driver.get('http://sahitest.com/demo/promptTest.htm')

    time.sleep(2)
    driver.find_element_by_name('b1').click()

    # a1 = driver.switch_to.alert  # 通过switch_to.alert切换到alert
    a1 = Alert(driver)  # 直接实例化Alert对象
    time.sleep(2)
    log.info(a1.text)  # 获取alert文本内容,对有信息显示的alert框

    a1.send_keys('send some words to alert!')  # 往prompt型alert中传入字符串
    time.sleep(2)
    a1.accept()  # 等同于点击“确认”或“OK”
    # a1.dismiss() # 等同于点击“取消”或“Cancel”
    log.info(driver.find_element_by_name('t1').get_attribute('value'))

    driver.quit()
예제 #10
0
class JpypeTest(object):
    def __init__(self):
        self.log = Log().get_logger()

    def startJvm(self):
        return JVMStart().start_jvm()

    """class文件调用"""

    def get_object_class(self):
        # 获取java的实体类
        java_class = JClass("JavaClass2")
        # java的实体类使用案例
        java_instance = java_class("哈喽!")  # 实例化对象
        self.log.info(java_instance.getValue())  # 调用JAVA对象的方法

    """直接调用JAVA API"""

    def get_base_java(self):
        # 获取java的基本类型类
        system = JClass("java.lang.System")
        string = JClass("java.lang.String")
        Boolean = JClass("java.lang.Boolean")
        Byte = JClass("java.lang.Byte")
        Short = JClass("java.lang.Short")
        Integer = JClass("java.lang.Integer")
        Long = JClass("java.lang.Long")
        Float = JClass("java.lang.Float")
        Double = JClass("java.lang.Double")

        # java的基本类型类使用案例
        port = string.valueOf(6868)  # int转string类型
        self.log.debug(port)
        self.log.debug(type(port))

    """调用JAVA第三方扩展包"""

    def get_object_jar(self):
        # 获取java的实体类
        java_class = JClass("com.jar.test.JavaClass")

        # java的实体类使用案例
        java_instance = java_class("oldvalue")  # 实例化对象
        self.log.info(java_instance.getValue())  # 调用JAVA对象的方法
        java_instance.setName("胜")
        self.log.info(java_instance.name)
        self.log.info(java_instance.getName())

    def shutdownJVM(self):
        JVMStart().shutdown_jvm()
예제 #11
0
class PdfJar(object):
    def __init__(self):
        self.log = Log().get_logger()
        self.path = r'C:\AProjectCode\Python\python3_interface\study_case\data\开发指南.pdf'
        self.out_path = r'C:\AProjectCode\Python\python3_interface\study_case\data\开发指南.txt'

    def startJvm(self):
        return JVMStart().start_jvm(['pdfbox-app-2.0.12.jar'])

    def get_java_objecj(self):
        self.file = JClass("java.io.File")
        self.FileOutputStream = JClass("java.io.FileOutputStream")
        self.OutputStreamWriter = JClass("java.io.OutputStreamWriter")
        self.Writer = JClass("java.io.Writer")
        self.PDDocument = JClass("org.apache.pdfbox.pdmodel.PDDocument")
        self.PDFTextStripper = JClass("org.apache.pdfbox.text.PDFTextStripper")

    def get_txt(self):
        try:
            self.get_java_objecj()
            input = self.file(self.path)  # 转换文件为File类型
            document = self.PDDocument.load(input)  # 加载pdf文件
            outputStream = self.FileOutputStream(self.out_path)
            output = self.OutputStreamWriter(outputStream, 'UTF-8')  # 文件输出流
            stripper = self.PDFTextStripper()  #  PDFTextStripper来提取文本
            stripper.setSortByPosition(False)  # 设置是否排序
            stripper.setStartPage(1)  # 设置起始页
            stripper.setEndPage(100000)  # 设置结束页
            stripper.writeText(document,
                               output)  # 调用PDFTextStripper的writeText提取并输出文本
            self.log.info(stripper.getText(document))  # 直接获取text

            output.close()  # 关闭输出流
            document.close()
        except Exception as e:
            self.log.error('出现异常:%s' % e)

    def shutdownJVM(self):
        JVMStart().shutdown_jvm()
예제 #12
0
def test_window():
    log = Log("UI测试").get_logger()
    driver = webdriver.Firefox()
    driver.set_window_size(960, 540)  # 设置窗口大小
    driver.get('http://sahitest.com/demo/index.htm')

    time.sleep(2)

    current_window = driver.current_window_handle  # 获取当前窗口的handle name
    time.sleep(5)
    driver.find_element_by_link_text(
        'Window Open Test With Title').click()  # 新窗口打开另一个网页
    # driver.find_element_by_link_text('Window Open Test').click()  # 新窗口打开另一个网页

    time.sleep(2)
    all_windows = driver.window_handles  # 获取所有窗口handle name
    # 切换window,如果window不是当前window,则切换到该window
    for window in all_windows:
        if window != current_window:
            driver.switch_to.window(window)  # 只能通过window的handle name来切换窗口
    """
    如果打开多个浏览器句柄和标签页的对应关系:
    标签页顺序(按照打开顺序):1,2,3,4,5
    对应的句柄   :0,4,3,2,1
    """
    # driver.switch_to.window(driver.window_handles[2])

    log.info(driver.title)  # 打印当前页面title

    driver.close()
    time.sleep(5)
    driver.switch_to.window(
        current_window)  # 关闭新窗口之后,driver并不会自动跳转回原窗口,而是需要你switch回来
    log.info(driver.title)  # 打印原页面title

    driver.quit()
예제 #13
0
def test_webdriver():
    log = Log("UI测试").get_logger()

    driver = webdriver.Ie()
    # driver = webdriver.Firefox()  # 获取浏览器驱动对象
    driver.set_window_size(960, 540)  # 设置窗口大小

    driver.get('https://www.baidu.com/')  # 打开一个网页
    # driver.find_element_by_id('kw').clear() # 清除文本
    """HTMl的属性定位,属性要唯一才能定位到"""
    # driver.find_element_by_id('kw').send_keys('王春玲') # 根据html属性id定位元素,模拟按键输入
    # driver.find_element_by_name('wd').send_keys('王春玲') # 根据html属性name定位元素,模拟按键输入
    # driver.find_element_by_class_name('s_ipt').send_keys('王春玲') # 根据html属性id定位元素,模拟按键输入
    # driver.find_element_by_tag_name('input').send_keys('王春玲') # 根据标签input定位,这里定位不到,因为页面有多个input
    # driver.find_element_by_link_text('贴吧').click() # 根据标签对之间的文本信息定位,如:<a>贴吧</a>
    # driver.find_element_by_partial_link_text('一个很长').click() # 根据标签对之间的部分文本信息定位,如:<a>一个很长很长的文本</a>
    """XPath定位"""
    # driver.find_element_by_xpath('/html/body/div/div/div[4]/div/div/from/span/input').send_keys('王春玲') # ,绝对路径定位
    # driver.find_element_by_xpath('//input[@id="kw"]').send_keys('王春玲') # XPath定位,根据元素属性id,还可以其他属性,//表示当前页面某目录
    # driver.find_element_by_xpath('//*[@id="kw"]').send_keys('王春玲') # XPath定位,根据元素属性,不指定标签名,用*替代
    # driver.find_element_by_xpath("//form[@id='form']/span/input").send_keys('王春玲') # XPath定位,上级和属性组合,
    # driver.find_element_by_xpath('//input[@id="kw" and @class="s_ipt"]').send_keys('王春玲') # 多个属性组合
    """CSS定位,属性要唯一才能定位到"""
    # driver.find_element_by_css_selector(".s_ipt").send_keys('王春玲') # css的class属性,注意:.代表class类型的
    # driver.find_element_by_css_selector("#kw").send_keys('王春玲') # css的id属性,注意:#代表id类型的
    # driver.find_element_by_css_selector("input").send_keys('王春玲') # 标签名定位,这里定位不到,不唯一
    driver.find_element_by_css_selector("span>input").send_keys('王春玲')  # 父子关系

    """
    显式等待和隐式等待:
    显式等待的等待时间是固定的,固定了10s就必须等待10s,隐式等待的等待时间是个范围,例如最大10s,那么如果在3s的
    时候程序达到预期的结果,那么就不在继续后面的7秒,直接进入下一步操作,而如果超出10s还没有相应,
    程序就会报出相应的错误。 
    """

    """
    implicitly_wait()隐式等待,用来设置超时,一般把implicitly_wait()方法调用在加载测试地址后,等待所测试的应用程序加载。
    如果 WebDriver没有在 DOM中找到元素,将继续等待,超出设定时间后则抛出找不到元素的异常。
    即当查找元素或元素并没有立即出现的时候,隐式等待将等待一段时间再查找 DOM,默认的时间是0
    一旦设置了隐式等待,则它存在整个 WebDriver 对象实例的声明周期中,隐式的等到会让一个正常响应的应用的测试变慢,
    它将会在寻找每个元素的时候都进行等待,这样会增加整个测试执行的时间。
    """
    # driver.implicitly_wait(30)

    # driver.find_element_by_id('kw').submit() # 提交输入框的内容,功能与click类似
    # driver.find_element_by_id('su').click() # 点击元素
    driver.find_element_by_xpath('//*[@id="su"]').click()  # 点击元素
    # size = driver.find_element_by_id('kw').size # 获取元素的大小
    # text = driver.find_element_by_id('cp').text # 获取元素的文本
    # attribute = driver.find_element_by_id('kw').get_attribute() # 获取元素的属性值
    # print(size)

    # driver.get_screenshot_as_file(Config.project_path + r'\test_data\a.png') # 截屏

    # time.sleep(3) #睡眠3秒
    # driver.back() # 返回上一个网页
    # time.sleep(3)
    # driver.refresh() # 刷新当前页面
    # driver.forward() # 前进

    # driver.maximize_window() # 设置窗口最大化
    # driver.minimize_window() # 设置窗口最小化

    time.sleep(1)
    log.info(driver.title)  # 获取标题

    driver.quit()   # 退出浏览器
예제 #14
0
class basePage(object):

    def __init__(self,driver):
        self.driver = driver
        self.timeout = 10
        self.log = Log()

    def find_element_xpath(self,xpath):
        try:
            element = WebDriverWait(self.driver, self.timeout, 0.5).until(EC.presence_of_element_located((By.XPATH,xpath)))
            self.log.info(xpath+",xpath定位成功")
            return element
        except TimeoutException:
            self.log.error("请重新定位,"+"原始定位是:"+xpath)
            self.save_screen_picture()
            return False

    def find_element_id(self,id):
        try:
            element = WebDriverWait(self.driver, self.timeout, 0.5).until(EC.presence_of_element_located((By.ID,id)))
            self.log.info(id+",id定位成功")
            return element
        except TimeoutException:
            self.log.error("请重新定位,"+"原始定位是:"+id)
            self.save_screen_picture()
            return False

    def find_element_class(self,CLASS):
        try:
            element = WebDriverWait(self.driver, self.timeout, 0.5).until(EC.presence_of_element_located((By.CLASS_NAME,CLASS)))
            self.log.info(CLASS+",class定位成功")
            return element
        except TimeoutException:
            self.log.error("请重新定位,"+"原始定位是:"+CLASS)
            self.save_screen_picture()
            return False

    def find_element_css(self,css):
        try:
            element = WebDriverWait(self.driver, self.timeout, 0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR,css)))
            self.log.info(css+",css定位成功")
            return element
        except TimeoutException:
            self.log.error("请重新定位,"+"原始定位是:"+css)
            self.save_screen_picture()
            return False

    def find_elements_xpath(self,xpath):
        try:
            element = WebDriverWait(self.driver, self.timeout, 0.5).until(EC.presence_of_all_elements_located((By.XPATH,xpath)))
            self.log.info(",xpath定位列表成功")
            return element
        except TimeoutException:
            self.log.error("请重新定位,"+"原始定位是:"+xpath)
            self.save_screen_picture()
            return False

    def find_elements_css(self,css):
        try:
            element = WebDriverWait(self.driver, self.timeout, 0.5).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,css)))
            self.log.info(",css定位列表成功")
            return element
        except TimeoutException:
            self.log.error("请重新定位,"+"原始定位是:"+css)
            self.save_screen_picture()
            return False

    def quit(self):
        self.driver.quit()
        self.log.info('退出浏览器')

    def switch_frame(self, frame):
        try:
            self.log.info('切换frame')
            return self.driver.switch_to_frame(frame)
        except Exception:
            self.log.error("切换farme失败,"+frame+"定位不到")
            return False

    def switch_to_default(self):
        try:
            self.log.info('退出frame')
            return self.driver.switch_to_default_content()
        except Exception:
            self.log.error('切换默认失败')
            return False

    def switch_to_fatheriframe(self):
        try:
            self.log.info('切换到上一级frame')
            return self.driver.switch_to.parent_frame()
        except Exception:
            self.log.error('切换上一级farme失败')
            return False

    def comfirm(self,type):
        self.log.info("寻找弹窗")
        try:
            if type in 'yes':
                self.driver.switch_to_alert().accept()
            elif type in 'no':
                self.driver.switch_to_alert().dismiss()
            else:
                self.log.error("选择类型错误")
                raise Exception
        except Exception:
            self.log.error("没有找到弹窗")
            self.save_screen_picture()
            return False

    def save_screen_picture(self):  # 获取存放图片的文件夹路径
        picture_path = pictureDir + '\\'+ NOW() + '.png'
        try:
            self.driver.get_screenshot_as_file(picture_path)
        except Exception :
            self.log.error("截图失败")
            return False

    def switch_currenthandles(self):
        all_handles = self. driver.window_handles
        handler = self.driver.current_window_handle
        self.log.info("开始切换窗口")
        for i in all_handles:
            if i != handler:
                self.driver.switch_to.window(i)
                self.log.error("切换成功")


    def actionmouse(self,element):
        try:
            ActionChains(self.driver).move_to_element(element).perform()
            self.log.info('移动鼠标成功')
        except Exception:
            self.log.error("移动失败")
            self.save_screen_picture()
            return False

    def rollto(self, x):
        try:
            self.driver.execute_script('var q=document.documentElement.scrollTop=%s' %x)
            self.log.info('向下滚动了'+str(x))
        except Exception:
            self.log.error('滚动失败')
            return False

    #css定位loading页
    def wait_element_disappear_true(self, element, waittime=1,maxTime=30):
        timeTotal = 0
        try:
            while self.driver.find_element_by_css_selector(
                element).is_displayed() is True:
                time.sleep(waittime)
                timeTotal = waittime + timeTotal
                self.log.info('等待中: '+ element )
                if timeTotal > maxTime:
                    self.log.info("等待总时长" + timeTotal)
                    break
        except Exception:
            self.log.error("等待异常")

    # 执行js
    def execute(self, js, *args):
        try:
            self.driver.execute_script(js, *args)
            self.log.info('执行成功')
        except Exception:
            self.log.error('执行失败')
예제 #15
0
class MongoDB(object):
    def __init__(self):
        self.log = Log().get_logger()
        """
        1、连接MongoDB
            连接MongoDB我们需要使用PyMongo库里面的MongoClient,一般来说传入MongoDB的IP及端口即可,第一个参数为地址host,
            第二个参数为端口port,端口如果不传默认是27017。
        """
        self.client = pymongo.MongoClient(host='localhost', port=27017)
        # client = pymongo.MongoClient('mongodb://localhost:27017/')  # 可以达到同样的连接效果。
        """
        2、指定数据库
            MongoDB分为一个个数据库,需要指定要操作哪个数据库,在这里我以test数据库为例进行说明
            注意: 在 MongoDB 中,如果数据库不存在,数据库只有在内容插入后才会创建! 就是说,数据库创建后要创建集合(数据表)
                并插入一个文档(记录),数据库才会真正创建。集合创建同理。
        """
        self.db = self.client.testdb
        # self.db = self.client['testdb']  # 两种方式是等价的。
        """
        2.2、读取 MongoDB 中的所有数据库,并判断指定的数据库是否存在
        """
        dblist = self.client.list_database_names()
        if "testdb" in dblist:
            self.log.info("数据库已存在!")
        else:
            self.log.info("数据库不存在!")
        """
        3、指定集合
            每个数据库又包含了许多集合Collection,也就类似与关系型数据库中的表,下一步需要指定要操作的集合,
        在这里我们指定一个集合名称为students,学生集合。还是和指定数据库类似,指定集合也有两种方式。
        """
        self.collection = self.db.students
        # self.collection = self.db['students']

        collist = self.db.list_collection_names()
        if "students" in collist:  # 判断 sites 集合是否存在
            self.log.info("集合已存在!")
        else:
            self.log.info("集合不存在!")

    def db_insert(self):
        """
        4、插入数据,
            对于students这个Collection,我们新建一条学生数据,以字典的形式表示,
            直接调用collection的insert()方法即可插入数据
        """
        student = {
            "name": "Google",
            "alexa": "1",
            "url": "https://www.google.com"
        }
        result = self.collection.insert_one(student)
        # 在MongoDB中,每条数据都有一个_id属性来唯一标识,如果没有显式指明_id,MongoDB会自动产生一个ObjectId类型的_id属性。
        self.log.info(result.inserted_id)

        students = [
            {
                "name": "Taobao",
                "alexa": "100",
                "url": "https://www.taobao.com"
            },
            {
                "name": "QQ",
                "alexa": "101",
                "url": "https://www.qq.com"
            },
            {
                "name": "Facebook",
                "alexa": "10",
                "url": "https://www.facebook.com"
            },
        ]
        results = self.collection.insert_many(students)  # 集合中插入多条数据
        # 输出插入的所有文档对应的 _id 值
        self.log.info(results.inserted_ids)

        students = [{
            "_id": 1,
            "name": "知乎",
            "alexa": "103",
            "url": "https://www.zhihu.com"
        }, {
            "_id": 2,
            "name": "Github",
            "alexa": "109",
            "url": "https://www.github.com"
        }]
        results = self.collection.insert_many(students)  # 自己指定 id,插入
        # 输出插入的所有文档对应的 _id 值
        self.log.info(results.inserted_ids)

    def db_find(self):
        # results = self.collection.find_one()  # 查询集合中的第一条数据。
        # self.log.info(results)
        #
        # for x in self.collection.find():  # 查询集合中的所有数据
        #     self.log.info(x)

        # find() 方法来查询指定字段的数据,将要返回的字段对应值设置为 1。
        # 除了 _id 你不能在一个对象中同时指定 0 和 1,如果你设置了一个字段为 0,则其他都为 1,反之亦然。
        # self.collection.find({}, {"name": 0, "alexa": 1}) 会抛异常
        value_list = self.collection.find({}, {
            "_id": 0,
            "name": 1,
            "alexa": 1
        })
        for x in value_list:
            self.log.info(x)

        self.log.info('-' * 20)

        # 指定条件查询
        myquery = {"name": "Facebook"}
        value_list = self.collection.find(myquery)
        for x in value_list:
            self.log.info(x)

        self.log.info('-' * 20)

        # 高级查询,第一个字母 ASCII 值大于 "H" 的数据
        myquery = {"name": {"$gt": "H"}}
        value_list = self.collection.find(myquery)
        for x in value_list:
            self.log.info(x)

        self.log.info('-' * 20)

        # 使用正则表达式查询,第一个字母为 "F" 的数据
        myquery = {"name": {"$regex": "^F"}}
        value_list = self.collection.find(myquery)
        for x in value_list:
            self.log.info(x)

        self.log.info('-' * 20)

        # 返回指定条数记录,设置指定条数的记录可以使用 limit() 方法,该方法只接受一个数字参数
        value_list = self.collection.find().limit(2)
        for x in value_list:
            self.log.info(x)

    def db_update(self):
        value_list = self.collection.find()  # 查询集合中的所有数据
        for x in value_list:
            self.log.info(x)

        # # 将 alexa 字段的值为XXX 的改为 XXX
        # myquery = {"alexa": "103"}
        # newvalues = {"$set": {"alexa": "111"}}
        # result = self.collection.update_one(myquery, newvalues) # 只能修匹配到的第一条记录
        # self.log.info('修改数据结果:%s' % result.modified_count)

        # 将 alexa 字段的值为10000 的改为 111
        myquery = {"alexa": "111"}
        newvalues = {"$set": {"alexa": "112"}}
        result = self.collection.update_many(myquery, newvalues)  # 修改所有匹配到的记录
        self.log.info('修改数据结果:%s' % result.modified_count)

        self.log.info('-' * 20)

        value_list = self.collection.find()  # 查询集合中的所有数据
        for x in value_list:
            self.log.info(x)

    def db_sort(self):
        # value_list = self.collection.find().sort("alexa")  # 对字段 alexa 按升序排序
        value_list = self.collection.find().sort("alexa",
                                                 -1)  # 对字段 alexa 按降序排序
        for x in value_list:
            self.log.info(x)

    def db_delete(self):
        # myquery = {"name": "Taobao"}
        # self.collection.delete_one(myquery)# 删除 name 字段值为 "Taobao" 的第一个匹配文档

        myquery = {"name": {"$regex": "^G"}}
        result = self.collection.delete_many(myquery)  # 删除所有 name 字段中以 G 开头的文档
        self.log.info('删除结果:%s' % result.deleted_count)

        value_list = self.collection.find()
        for x in value_list:
            self.log.info(x)
예제 #16
0
class RedisStudy(object):
    def __init__(self):
        self.log = Log().get_logger()

    def study(self):
        # 1、一般连接方式
        r = redis.Redis(host='127.0.0.1', port=6379, db=0, password=12345)
        # r.set('name', 'zhangsan0')  # 添加
        self.log.info(r.get('mykey1'))  # 获取

        # 2、连接池
        pool = redis.ConnectionPool(host='127.0.0.1',
                                    port=6379,
                                    db=0,
                                    password=12345)
        r = redis.Redis(connection_pool=pool)
        # r.set('name2', 'zhangsan2')  # 添加
        # r.setex('name2', 'zhangsan11',15)  #设置过期时间(秒)
        self.log.info(r.get('name2'))  # 获取

        # r.mset(name3='zhangsan', name4='lisi')    # 批量设置值
        self.log.info(r.mget("name3", "name4"))
        self.log.info(r.mget(["name3", "name4"]))

        self.log.info(r.getset("name2", "wangwu"))  #  设置新值,打印原值
        self.log.info(r.get("name2"))  # 输出新值
        self.log.info(r.getrange("name2", 0, 3))  # #根据字节获取子序列
예제 #17
0
class MySQLStudy(object):
    def __init__(self):
        self.log = Log().get_logger()
        # 打开数据库连接
        self.conn = pymysql.connect(
            host='192.168.1.9',
            port=3307,
            user='******',
            password='******',
            database='artest',  # 数据库不存在话会抛异常
            charset='utf8')
        # self.cursor = self.conn.cursor() # 游标默认获取的数据是元祖类型
        self.cursor = self.conn.cursor(
            cursor=pymysql.cursors.DictCursor)  # 游标设置为字典类型

    def db_create(self):
        data = self.cursor.fetchone()
        self.log.info('Database version:%s' % data)
        # sql = 'CREATE DATABASE IF NOT EXISTS teacherdb DEFAULT CHARACTER SET UTF8'
        # self.cursor.execute(sql)

        sql = 'CREATE TABLE IF NOT EXISTS teacher (id INT auto_increment PRIMARY KEY ,' \
              'name VARCHAR(10) NOT NULL UNIQUE,age TINYINT NOT NULL)ENGINE=innodb DEFAULT CHARSET=utf8;'
        self.cursor.execute(sql)  # 执行SQL语句
        self.cursor.close()  # 关闭光标对象
        self.conn.close()

    def db_insert(self):
        # 执行SQL,并返回受影响行数,执行多次
        effect_row = self.cursor.executemany(
            "insert into teacher(name,age)values(%s,%s)", [("小米", 100),
                                                           ("小红", 101),
                                                           ("小华", 102)])
        self.log.info('影响行数:%s' % effect_row)
        self.conn.commit()  # 提交,不然无法保存新建或者修改的数据
        self.cursor.close()
        self.conn.close()
        # 获取自增id
        new_id = self.cursor.lastrowid
        self.log.info('自增id:%s' % new_id)

    def db_find(self):
        sql = "select * from teacher;"
        effect_row = self.cursor.execute(sql)
        # fetch数据时按照顺序进行,可以使用cursor.scroll(num, mode)来移动游标位置,如:
        # self.cursor.scroll(1, mode='relative')  # 相对当前位置移动
        # self.cursor.scroll(2, mode='absolute')  # 相对绝对位置移动
        data1 = self.cursor.fetchone()  # 按照顺序进行
        # data2 = self.cursor.fetchmany(2)
        data2 = self.cursor.fetchall()
        self.log.info(data1)
        self.log.info(data2)
        # self.log.info('影响行数:%s' % effect_row)
        self.cursor.close()  # 关闭光标对象
        self.conn.close()

    def db_find2(self):
        name = "小米2"
        age = "100"

        # 1、字符串拼接查询语句
        sql = "select name,age from teacher where name='%s' and age='%s' " % (
            name, age)  # %s的引号要加
        # 执行参数化查询
        self.cursor.execute(sql)
        data1 = self.cursor.fetchone()  # 按照顺序进行
        self.log.info(data1)

        # 2、pymysql提供的参数化查询语句,注意与字符串方式的区别
        self.cursor.execute(
            "select name,age from teacher where name like  '%%%s%%'" % name)
        data2 = self.cursor.fetchone()  # 按照顺序进行
        self.log.info(data2)

        self.cursor.close()
        self.conn.close()

    def db_update(self):
        sql = "update teacher set age = 100 where name = '小米'"
        self.cursor.execute(sql)
        # effect_row = self.cursor.execute("update teacher set age = %s where name = %s", ('110', '小米'))

        sql2 = "update teacher set age = 111 ,name = '小马' where id = 13"
        self.cursor.execute(sql2)

        self.conn.commit()  # 提交,不然无法保存新建或者修改的数据
        self.db_find()
        # self.cursor.close()
        # self.conn.close()

    # 存在就更新,不存在就插入
    def db_update2(self):
        # 1、使用replace语法,表中必须有唯一索引
        sql = "replace into teacher(name,age)values('小米2',100)"  # REPLACE时,表中必须有唯一索引
        self.cursor.execute(sql)

        # 2、判断存不存在的那个字段要设置成unique索引,这里前后name值要一样,前面数据是插入,后面是更新
        sql2 = "insert into teacher(name,age)values('小马2',110) on duplicate key update name= '小马2',age=100"
        self.cursor.execute(sql2)

        self.conn.commit()  # 提交,不然无法保存新建或者修改的数据
        self.db_find()
        # self.cursor.close()
        # self.conn.close()

    def db_delete(self):
        sql = "delete from teacher where name = '小米'"
        self.cursor.execute(sql)

        self.conn.commit()  # 提交,不然无法保存新建或者修改的数据
        self.db_find()