zoukankan      html  css  js  c++  java
  • 数据存储 twisted

    数据存储 twisted

    adbapi.ConnectionPool方法可以创建一个数据库连接池对象,其中包括多个连接对象,每个连接对象在独立的线程中工作。adbapi只是提供了异步访问数据库的编程框架,在其内部依然使mysql这样的库访问数据库。
    dbpool.runInteraction(insert_db,item)以异步方式调用insert_db函数,dbpool会选择连接池中的一个连接对象在独立线程中调用insert_db,其中参数item会被传给insert_db的第二个参数,传给insert_db的第一个参数是一个Transaction对象,其接口与Cursor对象类似,可以调用execute方法执行SQL语句,insert_db执行后,连接对象会自动调用commit方法

     1 import pymysql
     2 from twisted.enterprise import adbapi
     3 from pymysql import cursors
     4  
     5  
     6 class JianshuTwistedPipeline(object):
     7  
     8     def __init__(self):
     9         dbparmas = {
    10             'host': '192.168.0.134',
    11             'user': 'root',
    12             'password': '123456',
    13             'database': 'jianshu',
    14             'charset': 'utf8',
    15             'cursorclass': cursors.DictCursor
    16         # 在默认情况下cursor方法返回的是BaseCursor类型对象,BaseCursor类型对象在执行查询后每条记录的结果以列表(list)表示。如果要返回字典(dict)表示的记录,就要设置cursorclass参数为cursors.DictCursor类。
    17         }
    18         # 连接ConnectionPool(使用pymysql或者MySQLdb连接)
    19         self.dbpool = adbapi.ConnectionPool('pymysql', **dbparmas)
    20         self._sql = None
    21  
    22     @property
    23     def sql(self):
    24         if not self._sql:
    25             self._sql = '''
    26               insert into article(id,title,content,author,avatar,publish_time,article_id,origin_url) values(null,%s,%s,%s,%s,%s,%s,%s)
    27               '''
    28             return self._sql
    29         return self._sql
    30  
    31     def process_item(self, item, spider):
    32         # 使用twisted将mysql插入变成异步执行
    33         defer = self.dbpool.runInteraction(self.insert_item, item)
    34         # 添加异常处理
    35         defer.addErrback(self.handle_error, item, spider)
    36  
    37     def insert_item(self, cursor, item):
    38         cursor.execute(self.sql, (
    39         item['title'], item['content'], item['author'], item['avatar'], item['publish_time'], item['article_id'],
    40         item['origin_url']))
    41  
    42     def handle_error(self, error, item, spider):
    43         print(error)
    数据存储 twisted
  • 相关阅读:
    《c程序设计语言》读书笔记--大写转小写
    《c程序设计语言》读书笔记--字符串比较
    《c程序设计语言》读书笔记--反转字符串
    spring接收json字符串的两种方式
    logback的使用
    初识Vim
    Chrome控制台
    构造有层次的大纲
    让chrome浏览器快的不要不要的
    排序算法Java版
  • 原文地址:https://www.cnblogs.com/guozepingboke/p/10794731.html
Copyright © 2011-2022 走看看