Skip to content

Instantly share code, notes, and snippets.

@PierreSelim
Last active August 26, 2016 15:13
Show Gist options
  • Save PierreSelim/aa684a9c086de6c6a3cb66ae589795a2 to your computer and use it in GitHub Desktop.
Save PierreSelim/aa684a9c086de6c6a3cb66ae589795a2 to your computer and use it in GitHub Desktop.
Python batteries

List of must known useful libraries in python

  • requests (http client for humans)
  • mysqlclient (using mysql)
  • attrdict (dict as object and object as dict)

requests

Probably the most famous http client for python.

Project page: http://docs.python-requests.org/en/master/

Installation

pip install requests

Example

>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}

mysqlclient

The common mysql binding for python.

Project page:

Installation

Python developpement files and mysql connectors (a bit painful under windows)

Ubuntu dependencies:

sudo apt-get install python-dev libmysqlclient-dev

Install from PyPi

pip install mysqclient

Example

import MySQLdb
db=MySQLdb.connect(passwd="moonpie",db="thangs")
c=db.cursor()
max_price=5
c.execute("""SELECT spam, eggs, sausage FROM breakfast
          WHERE price < %s""", (max_price,))
# fetchone(), fetchall(), fetchmany(n)
c.fetchone()  # returns tuple (3L, 2L, 0L)

using db.cursor(MySQLdb.cursors.DictCursor) instead of db.cursor() will get you result as dict() instead of tuple which is awesome. If you want more, read the doc: https://mysqlclient.readthedocs.io/en/latest/

attrdict

Dictionnaries as objects with attributes. Useful for results of API call or SELECT in Database.

GitHub page: https://github.com/bcj/AttrDict

Installation

pip install attrdict

Example

>>> from attrdict import AttrDict
>>> a = AttrDict({'foo': 'bar'})
>>> a.foo
'bar'
>>>> a['foo']
'bar'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment