cloudant / python-cloudant

A Python library for Cloudant and CouchDB
Apache License 2.0
163 stars 55 forks source link

Document save #375

Closed chosun41 closed 6 years ago

chosun41 commented 6 years ago

Python - 3.6.4

Not sure if this is an actual bug. But it seems one needs to save the local cache multiple times instead of one time before saving information to a document. Original code only had doc.save() at end.

New code:

    end =  datetime.datetime.utcnow()
    doc = db[kwargs['inbt']['_id']]
    doc['api_result'] = kwargs['results']
    doc['end_time_utc'] =  time.mktime(end.timetuple())
    duration = (end-kwargs['inbt']['start']).total_seconds()
    doc['duration'] = round((duration)/60,2)
    doc.save()
    if 'et_results' in kwargs.keys():
        doc['et_results'] = kwargs['et_results']
        doc.save()
    if 'forecast' in kwargs.keys():
        doc['forecast'] = kwargs['forecast']
        doc.save()
    if 'encoded' in kwargs.keys():
        doc.put_attachment(attachment = "encode.bin",data = kwargs['encoded'], content_type = 'application/octet-stream')
    doc.save()
    return doc
emlaver commented 6 years ago

@chosun41 I'm currently not able to reproduce your issue. What happens if you try to save the doc once then doc.fetch() from the remote database and print the doc? Are the added/modified fields missing?

I modified your code above and tested it in Python 3.6.4. I used an example database animaldb that's very small (11 docs). Code:

import time
from datetime import datetime
import os
from cloudant import Cloudant
from cloudant.document import Document

def main():
    CLOUDANT_USERNAME = os.getenv('CLOUDANT_USERNAME')
    CLOUDANT_PASSWORD = os.getenv('CLOUDANT_PASSWORD')
    CLOUDANT_URL = os.getenv('CLOUDANT_URL')
    db_name = 'animaldb'

    end = datetime.utcnow()
    client = Cloudant(CLOUDANT_USERNAME, CLOUDANT_PASSWORD, url=CLOUDANT_URL, connect=True)
    db = client[db_name]
    doc = db['lemur']
    # Adding new fields to doc
    doc['end_time_utc'] = time.mktime(end.timetuple())
    doc['duration'] = round(100 / 60, 2)
    doc.save()

    # try and fetch the doc from the remote db
    doc = Document(db, 'lemur')
    doc.fetch()
    print(doc['end_time_utc'])
    print(doc['duration'])
    return doc

if __name__ == "__main__":
    doc = main()
    print(doc)
chosun41 commented 6 years ago

I originally only had the one doc.save() after the doc.put_attachment. In that case, only the attachment was saved.

emlaver commented 6 years ago

@chosun41 have you changed your environment since using the original code? Updated python version or other Python packages?

smithsz commented 6 years ago

Stale ticket. Please reopen if you require further assistance.