2017-12-03 263 views
0

我想访问变量self.cursor以利用活动的postgreSQL连接,但我无法弄清楚如何访问scrapy的管道类实例。scrapy管道类的访问实例

class ScrapenewsPipeline(object): 

    def open_spider(self, spider): 
     self.connection = psycopg2.connect(
     host= os.environ['HOST_NAME'], 
     user=os.environ['USERNAME'], 
     database=os.environ['DATABASE_NAME'], 
     password=os.environ['PASSWORD']) 
     self.cursor = self.connection.cursor() 
     self.connection.set_session(autocommit=True) 


    def close_spider(self, spider): 
     self.cursor.close() 
     self.connection.close() 


    def process_item(self, item, spider): 
     print ("Some Magic Happens Here") 


    def checkUrlExist(self, item): 
     print("I want to call this function from my spider to access the 
    self.cursor variable") 

请注意,我知道我可以用yield item得到process_item访问,但该功能是做其他的东西,我想通过self.cursorcheckUrlExist连接的访问​​,并能够从调用类的实例我蜘蛛随意! 谢谢。

+0

'objectName.cursor'? – RottenCandy

+0

objectName在我不知道的时候,管道类会在蜘蛛自动启动时调用,我想将一个实例挂接到该类的实例上! :) – atb00ker

+0

也许你应该考虑'getattr' https://stackoverflow.com/questions/4075190/what-is-getattr-exactly-and-how-do-i-use-it#4076099 – RottenCandy

回答

1

你可以在这里做spider.variable_name来访问你所有的蜘蛛类变量。

class MySpider(scrapy.Spider): 

     name = "myspider" 

     any_variable = "any_value" 

这里你管线

class MyPipeline(object): 

    def process_item(self, item, spider): 

     spider.any_variable 

我建议你创建就像我宣布我的例子any_variable你的蜘蛛类的连接,那将是在使用self.any_variable您的蜘蛛在你的管道进入,它将可以通过spider.any_variable

+0

我有60只蜘蛛,在这种情况下,他们都有自己的PostgreSQL连接,我只有有限的内存,因为它不会对我有用。 – atb00ker