Python - Essential Utilities

Here are a couple of absolutely essential Python utilities...

PyLint

http://www.pylint.org/

PyLint checks your Python code for errors, following PEP8 guidelines and suggestions.

PyLint is simple to use...

>>> pip install pylint
>>> pylint hello_monty.py
W: 4, 0: Found indentation with tabs instead of spaces (mixed)  
C: 8, 0: Final newline missing (missing-final-newline)  
W: 5, 7: Catching too general exception Exception (broad-except)  
C: 5, 0 Invalid variable name "e" (invalid-name)  
W: 1, 0: Unused import sys (unused import)  

That is all there is to it. Fix the errors as identified by the PyLint output.

Foolish consistency is the hobgoblin of little minds.

Pymongo

PyMongo is a Python distribution containing the required tools for working with MongoDB, and it is the recommended way to work with MongoDB from Python.

This documentation attempts to explain everything you need to know to use PyMongo.

Example 1:

mongo_fun.py

import pymongo

connection = pymongo.MongoClient("mongodb://localhost")

db = connection.test  
users = db.users  
doc = {"name":"Craig Derington", "dob":"01/17/1970", "favcolor":"blue"}  
print(doc)  
print("about to insert this document...")

try:  
    users.insert_one(doc)
except Exception as e:  
    print("insert failed: ", e)

print(doc)  
print("inserting again...")  

Example 2:

score_results.py

# import pymongo
import pymongo  
from pymongo import MongoClient

# connect to the database
connection = MongoClient('localhost', 27017)

# test the database connection
db = connection.test

# assign default database and query
scores = db.scores.find()

for score in scores:  
    if score['score'] >= 95:
        print(score)

Example 3:

This time from the shell:

>>> import datetime
>>> post = {"author": "Craig Derington",
...         "text": "My First Bottle Blog Post!",
...         "tags": ["mongodb", "python", "pymongo", "web frameworks", "bottle"],
...         "date": datetime.datetime.utcnow()}
...
>>> posts = db.posts
>>> post_id = posts.insert_one(post).inserted_id
>>> post_id
ObjectId('55ab6F...')  
>>> posts.find_one()
{u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo', u'web frameworks', u'bottle']}
>>> for post in posts.find({"author": "Craig Derington"}):
...   post
{...data...}

Craig Derington

Veteran full stack web dev focused on deploying high-performance, responsive, modern web applications using Python, NodeJS, Django, Flask, MongoDB and MySQL.

comments powered by Disqus