मैं एक वेब-स्क्रैपिंग प्रोजेक्ट में मोंगोइंजिन का उपयोग कर रहा हूं। मैं उन सभी छवियों का ट्रैक रखना चाहता हूं जिन्हें मैंने सभी स्क्रैप किए गए वेबपृष्ठों पर सामना किया है।मोंगोएन्गिन - "नया आइटम या वृद्धि काउंटर" ऑपरेशन कैसे करें?
ऐसा करने के लिए, मैं छवि src
यूआरएल और छवि का सामना करने की संख्या को स्टोर करता हूं।
class ImagesUrl(Document):
""" Model representing images encountered during web-scraping.
When an image is encountered on a web-page during scraping,
we store its url and the number of times it has been
seen (default counter value is 1).
If the image had been seen before, we do not insert a new document
in collection, but merely increment the corresponding counter value.
"""
# The url of the image. There cannot be any duplicate.
src = URLField(required=True, unique=True)
# counter of the total number of occurences of the image during
# the datamining process
counter = IntField(min_value=0, required=True, default=1)
मैं "को बचाने या वेतन वृद्धि" प्रक्रिया को लागू करने के लिए उचित तरीके के लिए देख रहा हूँ:
MongoEngine मॉडल परिभाषा निम्नलिखित है।
अब तक, मैं इसे से निपटने रहा है कि जिस तरह से है, लेकिन मैं MongoEngine साथ यह कर का एक बेहतर, निर्मित तरीका हो सकता है महसूस हो रहा है:
def save_or_increment(self):
""" If it is the first time the image has been encountered, insert
its src in mongo, along with a counter=1 value.
If not, increment its counter value by 1.
"""
# check if item is already stored
# if not, save a new item
if not ImagesUrl.objects(src=self.src):
ImagesUrl(
src=self.src,
counter=self.counter,
).save()
else:
# if item already stored in Mongo, just increment its counter
ImagesUrl.objects(src=self.src).update_one(inc__counter=1)
वहाँ यह करने का एक बेहतर तरीका है?
आपके समय के लिए बहुत बहुत धन्यवाद।
धन्यवाद, कि पूरी तरह से काम किया! –
वैसे, क्या आप इस व्यवहार के साथ Document.save() फ़ंक्शन को ओवरराइड करने की सलाह देंगे, या इसे एक नई छवियों Url विधि में कार्यान्वित करने के लिए सलाह देंगे? –
मैं सलाह दूंगा कि आप 'सेव' का उपयोग न करें, इसका इरादा स्पष्ट नहीं है - मैं केवल 'update_one' कोड ही करूंगा। – Ross