Find or create single document. Return (doc, created_now).
197683
def get_or_create(cls, spec, defaults=None):
        ''''''
        docs = list(cls.find(spec).limit(2))
        assert len(docs) < 2, 'multiple docs returned'
        if docs:
            return docs[0], False
        else:
            kwargs = defaults or {}
            kwargs.update(spec)
            doc = cls(**kwargs)
            doc.save()
            return doc, True
729889
def create(self, request):
        
        document = self.collection(request.json)
        document.created_at = datetime.utcnow()
        document.updated_at = document.created_at

        created = document.insert()
        return Response(
            response=serialize(created),
            status=(
                201 if not all(
                    key in created for key in [
                        'error_code', 'error_type', 'error_message'
                    ]
                ) else 400
            )
        )
357685
def create(self):
        

        # Ensure that an existing document will not be "updated"
        doc = dict(self)
        if doc.get('_rev') is not None:
            doc.__delitem__('_rev')

        headers = {'Content-Type': 'application/json'}
        resp = self.r_session.post(
            self._database.database_url,
            headers=headers,
            data=json.dumps(doc, cls=self.encoder)
        )
        resp.raise_for_status()
        data = response_to_json_dict(resp)
        super(Document, self).__setitem__('_id', data['id'])
        super(Document, self).__setitem__('_rev', data['rev'])
924068
def get_instance(self, payload):
        
        return DocumentInstance(self._version, payload, service_sid=self._solution['service_sid'], )
4685
def one(cls, filter=None, **kwargs):
        """"""
        from mongoframes.queries import Condition, Group, to_refs

        # Flatten the projection
        kwargs['projection'], references, subs = \
                cls._flatten_projection(
                    kwargs.get('projection', cls._default_projection)
                    )

        # Find the document
        if isinstance(filter, (Condition, Group)):
            filter = filter.to_dict()

        document = cls.get_collection().find_one(to_refs(filter), **kwargs)

        # Make sure we found a document
        if not document:
            return

        # Dereference the document (if required)
        if references:
            cls._dereference([document], references)

        # Add sub-frames to the document (if required)
        if subs:
            cls._apply_sub_frames([document], subs)

        return cls(document)
555667
def find(model, rid):
    

    validate_rid(model, rid)

    rid_field = model.rid_field
    model = goldman.sess.store.find(model.RTYPE, rid_field, rid)

    if not model:
        abort(exceptions.DocumentNotFound)

    return model
33831
def fetchDocument(self, key, rawResults = False, rev = None) :
        """"""
        url = "%s/%s/%s" % (self.documentsURL, self.name, key)
        if rev is not None :
            r = self.connection.session.get(url, params = {'rev' : rev})
        else :
            r = self.connection.session.get(url)

        if r.status_code < 400 :
            if rawResults :
                return r.json()
            return self.documentClass(self, r.json())
        elif r.status_code == 404 :
            raise DocumentNotFoundError("Unable to find document with _key: %s" % key, r.json())
        else :
            raise DocumentNotFoundError("Unable to find document with _key: %s, response: %s" % (key, r.json()), r.json())
833310
def fetch_object(self, doc_id):
        """"""
        try:
            return self.object_class.objects.get(pk=doc_id)
        except self.object_class.DoesNotExist:
            raise ReferenceNotFoundError
1180391
def _document_by_attribute(self, kind, condition=None):
        
        doc = self.document
        if doc:
            for attr in doc.attributes:
                if isinstance(attr, kind):
                    if not condition or condition(attr):
                        return doc
                    return None
1154777
def get(self, master_id):
        
        collection_name = self.request.headers.get("collection")
        self.client = BaseAsyncMotorDocument("%s_revisions" % collection_name)

        limit = self.get_query_argument("limit", 2)
        add_current_revision = self.get_arg_value_as_type("addCurrent",
                                                          "false")
        show_history = self.get_arg_value_as_type("showHistory", "false")

        objects_processed = []

        if isinstance(limit, unicode):
            limit = int(limit)

        objects = yield self.client.find({"master_id": master_id,
                                          "processed": False},
                                         orderby="toa",
                                         order_by_direction=1,
                                         page=0,
                                         limit=20)

        # If this is a document that should have a revision and doesn't we
        # orchestratioin creation of the first one
        if len(objects) == 0:

            new_revision = yield self.__lazy_migration(master_id)
            if not new_revision:
                return

        if show_history:
            objects_processed = yield self.client.find({"master_id": master_id,
                                                        "processed": True},
                                                       orderby="toa",
                                                       order_by_direction=-1,
                                                       page=0,
                                                       limit=limit)

        elif add_current_revision:
            objects_processed = yield self.client.find({"master_id": master_id,
                                                        "processed": True},
                                                       orderby="toa",
                                                       order_by_direction=-1,
                                                       page=0,
                                                       limit=1)

        if len(objects_processed) > 0:
            objects_processed = objects_processed[::-1]
            objects_processed[-1]["current"] = True
            objects = objects_processed + objects

        self.write({
            "count": len(objects),
            "results": objects
        })
1155025
def get_document(self, doc_id):
        ''''''
        conn = self.agency._database.get_connection()
        return conn.get_document(doc_id)
1153893
def find_one(self, cls, id):
        """"""
        try:
            db_result = self.get_class_table(cls).lookup(id)
        except ItemNotFound:
            # according to docs, this shouldn't be required, but it IS
            db_result = None

        if not db_result:
            return None

        obj = cls.from_data(db_result['value'])
        return obj
51370
def _generate_doc(ret):
    '''
    
    '''

    # Create a copy of the object that we will return.
    retc = ret.copy()

    # Set the ID of the document to be the JID.
    retc["_id"] = ret["jid"]

    # Add a timestamp field to the document
    retc["timestamp"] = time.time()

    return retc
117250
def add_document(self, document):
        '''
        
        '''

        documents_url = urljoin(self.base_url, self.DOCUMENTS_PAGE)
        data = {"corpus": self.url}
        files = {"blob": document}
        result = self.session.post(documents_url, data=data, files=files)
        if result.status_code == 201:
            return Document(session=self.session, **result.json())
        else:
            raise RuntimeError("Document creation failed with status "
                               "{}. The response was: '{}'".format(result.status_code,
                                result.text))
929243
def createDocument(self, initDict = None) :
        """"""
        if initDict is not None :
            return self.createDocument_(initDict)
        else :
            if self._validation["on_load"] :
                self._validation["on_load"] = False
                return self.createDocument_(self.defaultDocument)
                self._validation["on_load"] = True
            else :
                return self.createDocument_(self.defaultDocument)
646607
def get(self, id):
        
        data = self.fetch('documents/%s.json' % id).get("document")
        data['_connection'] = self._connection
        return Document(data)
498833
def get_last_doc(self):
        
        #search everything, sort by descending timestamp, return 1 row
        try:
            result = self.solr.search('*:*', sort='_ts desc', rows=1)
        except ValueError:
            return None

        for r in result:
            r['_id'] = r.pop(self.unique_key)
            return r