【问题标题】:Python Scrapy maintain SSH MySQL connection on every process_itemPython Scrapy 在每个 process_item 上维护 SSH MySQL 连接
【发布时间】:2019-01-30 21:32:16
【问题描述】:

我还是 Scrapy 和 Python 的新手。

我能够使用 SSH 凭据连接到我的远程数据库,但是...

希望防止在每个被抓取的项目上发生此错误。

错误:2055:在“127.0.0.1:3306”处丢失与 MySQL 服务器的连接,系统错误:10053 已建立的连接被主机中的软件中止

下面是我的 MySQL 管道对象

import mysql.connector
import sshtunnel

class MySQLStorePipeline(object):

def __init__(self):
    with sshtunnel.SSHTunnelForwarder(
        ('13.***.***.***', 22),
        ssh_username='***',
        ssh_password='***',
        remote_bind_address=('db1.prod.***.***.net.***', 3306),
        local_bind_address=('127.0.0.1', 3306)
    ) as tunnel:

        self.dbcon = mysql.connector.connect(
            host='127.0.0.1', 
            port=3306,
            user='***', 
            database='***', 
            password='***',
            charset='utf8'
        )
        self.cursor = self.dbcon.cursor() 

def process_item(self, item, spider):
    try:
        tables = self.cursor.execute('SHOW TABLES')
        print tables.fetchall()

        self.dbcon.commit()            
    except mysql.connector.Error as err:
        print('Error: {}'.format(err))

    return item

我只是不知道如何在 process_item 函数中维护数据库连接

【问题讨论】:

    标签: python mysql ssh scrapy mysql-connector-python


    【解决方案1】:

    您正在使用with ...,这就是为什么您会出现这种行为SSH tunnel from Python is closing automatically

    【讨论】:

    • 你能为我构建一个代码吗?我对python还是陌生的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 2017-08-20
    相关资源
    最近更新 更多