Python : Dictionary comprehension

Before updating a no sql or mongo doc you need to ensure that you are not adding keys which are not part of initial doc then dictionary comprehension is really helpful.

What it means, is you are able to create a dict (json object) dynamically in single line of code using loops, condition, construction every thing together.

Single line comprehension

items_to_update = {key: value for key, value in payload.items() if key in req_items}

 

multi line interpretation

if key in req_items:

….for key, value in payload.items():

…….. dictionary[key]=value

Detailed example of created update doc dic before inserting in mongo db

try:
    req_items = ["property1","property2"]
    items_to_update = {key: value for key, value in payload.items() if key in req_items}
  
    if items_to_update:
        logger.info("Updating device collection with {}".format(items_to_update))
        self.db.update({"filter": filter}, {"$set": items_to_update}, multi=True)
        logger.info("Successfully updated product details")
except PyMongoError as e:
    logger.critical('Pymongo Exception {}'.format(str(e)))
except Exception as e:
    logger.critical('Exception {}'.format(str(e)))

 

asd

Advertisements

Loopback : How to create embedded document or create object type

Here is your Contact model and if you want embed another model called as Address inside it then you need to put relations as embedsOne.
Please note that if you are using mongodb then embeds document will be part of parent document which mean all child documents will not be part of different collections which are linked, rather they will all be part of single parent doc.

“relations”: {
“address”: {
“type”: “embedsOne”,
“model”: “Address”,
“property”: “address”,
“options”: {
“validate”: true,
“forceId”: false
}

Now Contacts.json would look like this

{
“name”: “Contact”,
“base”: “PersistedModel”,
“idInjection”: true,
“options”: {
“validateUpsert”: true
},
“properties”: {
“id”: {
“type”: “string”,
“id”: true,
“defaultFn”: “uuid”
},
“name”: {
“type”: “string”,
“required”: true
},
“phone”: {
“type”: “string”,
“required”: true
},
“email”: {
“type”: “string”
},
“relationship”: {
“type”: “string”
}
},
“validations”: [],
“relations”: {
“address”: {
“type”: “embedsOne”,
“model”: “Address”,
“property”: “address”,
“options”: {
“validate”: true,
“forceId”: false
}
}
},
“acls”: [],
“methods”: {}
}

Please note that default id creator or sub document is “defaultFn”: “uuid” which will add id.

Python : Converting unicode logs of dict into valid json format

While debugging, programmer goes through logs to grab request payload. The issue is payload is wrapped with u for unicode, ‘ and True and False and None which are python standards however fails to pass json validation.

Hence to use them, we need to convert the unicoded python dict into valid json to do crul call, for the same here is the simple trick :

{u’a’: u’aValue’, u’b’: u’bValue’, u’c’: u’cValue’} is a dictionary which you are calling as unicode json. Now, in your language if you want a regular json from this then just do something like this:

x={u'a': u'aValue', u'b': u'bValue', u'c': u'cValue'}
y=json.dumps(x)
print y

The output will be {“a”: “aValue”, “c”: “cValue”, “b”: “bValue”}

This will remove all u, convert False into false, True into true, None into null and convert ‘ into ”   🙂

Mongodb – can’t login via -u root -p bitnami

Are you trying to login like this?

mongo admin --username root --password YOUR_PASSWORD

where YOUR_PASSWORD is the one you can see in your AWS system log:

Setting Bitnami application password to 'YOUR_PASSWORD'

If this doesn’t work, you can also try resetting MongoDB password:

http://wiki.bitnami.com/Components/mongoDB?highlight=mongo#How_to_reset_the_MongoDB_root_password.3f