Last active
August 16, 2020 17:01
-
-
Save mgmarino/6007545 to your computer and use it in GitHub Desktop.
Save a data document in a database with couchdb/python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Save a document with couchdb in python | |
""" | |
import couchdb | |
import datetime | |
import time | |
import json | |
import random | |
import pytz | |
server = couchdb.Server("http://127.0.0.1:5984") | |
# Set credentials if necessary | |
server.resource.credentials = ("username", "password") | |
# create db if necessary | |
if "nedm/hg_laser" not in server: | |
server.create("nedm/hg_laser") | |
db = server["nedm/hg_laser"] | |
# create skeleton doc | |
adoc = { | |
"type" : "data", | |
"created_by" : "mgmarino", | |
"value" : {} | |
} | |
# loop ten times and insert 10 new documents | |
while 1: | |
# calls to save will automatically update the document | |
if "_id" in adoc: del adoc["_id"] | |
adoc["timestamp"] = datetime.datetime.utcnow().replace(tzinfo=pytz.utc).strftime('%a, %d %b %Y %H:%M:%S GMT') | |
val = random.random() | |
adoc["value"]["sensor1"] = val | |
if (val < 0.5) and "sensor2" in adoc["value"]: | |
del adoc["value"]["sensor2"] | |
else: | |
adoc["value"]["sensor2"] = 2*val | |
db.save(adoc) | |
print "Saved: ", json.dumps(adoc) | |
time.sleep(1.5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment