diff --git a/src/humulus/couch.py b/src/humulus/couch.py index e5212e0..aebbdcd 100644 --- a/src/humulus/couch.py +++ b/src/humulus/couch.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import time +from datetime import datetime import uuid import click @@ -90,9 +90,22 @@ def put_doc(doc): # Use a UUID for name doc['_id'] = str(uuid.uuid4()) + # Add a created timestamp + # Timestamps are written to couchdb in ISO-8601 format + doc['created'] = datetime.utcnow().isoformat() + return db.create_document(doc, throw_on_exists=True) +def update_doc(doc): + """Update a doc. + + Adds an 'updated' field representing the current time the doc was updated. + """ + doc['updated'] = datetime.utcnow().isoformat() + doc.save() + + def get_doc(id): """Gets a doc from CouchDB and returns it.""" return get_db()[id] diff --git a/src/humulus/recipes.py b/src/humulus/recipes.py index 74bdd61..46f79db 100644 --- a/src/humulus/recipes.py +++ b/src/humulus/recipes.py @@ -22,7 +22,7 @@ from wtforms import (Form, StringField, DecimalField, TextAreaField, FieldList, FormField, SelectField) from wtforms.validators import DataRequired, Optional -from humulus.couch import get_doc_or_404, put_doc +from humulus.couch import get_doc_or_404, put_doc, update_doc bp = Blueprint('recipes', __name__, url_prefix='/recipes') @@ -222,7 +222,7 @@ def update(id): # Copy values from submitted form to the existing recipe and save for key, value in form.doc.items(): recipe[key] = value - recipe.save() + update_doc(recipe) flash('Updated recipe: {}'.format(form.name.data), 'success') return redirect(url_for('recipes.info', id=id)) diff --git a/tests/test_couch.py b/tests/test_couch.py index 10e9a8e..2a1ff55 100644 --- a/tests/test_couch.py +++ b/tests/test_couch.py @@ -14,7 +14,7 @@ import uuid -from humulus.couch import get_doc, put_doc +from humulus.couch import get_doc, put_doc, update_doc def test_put_doc(app): @@ -22,6 +22,7 @@ def test_put_doc(app): data = {'foo': 'bar'} response = put_doc(data) assert '_id' in response + assert 'created' in response response = put_doc({'name': 'test'}) assert response['_id'] == 'test' @@ -33,6 +34,20 @@ def test_put_doc(app): assert response['_id'] == 'test-2' +def test_update_doc(app): + with app.app_context(): + doc = get_doc('awesome-lager') + rev = doc['_rev'] + doc['test'] = 'update' + update_doc(doc) + + updated_doc = get_doc('awesome-lager') + assert doc['_id'] == updated_doc['_id'] + assert rev < updated_doc['_rev'] + assert updated_doc['test'] == 'update' + assert 'updated' in updated_doc + + def test_build_couch_command(runner, monkeypatch): class Recorder(object): called = False