2017-12-03 32 views
0

アクティブなpostgreSQL接続を使用するために変数self.cursorにアクセスしたいのですが、私はパイプラインクラスのスクラップのインスタンスにアクセスする方法を見つけることができません。アクセスのインスタンスは、パイプラインクラス

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へのアクセスを得ることができますが、その機能は他のものをやっていると私はcheckUrlExistself.cursorを経由して接続のアクセスをしたいと私のクラスのインスタンスを呼び出すことができる実現、注意してくださいクモの意志で! ありがとうございます。

+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 

私はあなたがself.any_variableを使用して、あなたのクモで、あなたのパイプラインでアクセスできるようになります私は私の例でany_variableを宣言しただけのようなあなたのスパイダーのクラスでの接続を作成することをお勧めspider.any_variable

+0

私は60のスパイダーを持っていますこのケースでは、すべて自分自身のpostgreSQL接続を持っているので、私には限られたRAMしかないので、これは私には役に立たないでしょう。 – atb00ker

関連する問題