Introducing Records: just write SQL (from the author of python's requests)

hpdsrdrvjq 8年前發布 | 32K 次閱讀 SQL Python

來自: https://github.com/kennethreitz/records

Records: SQL for Humans?

Records is a very simple, but powerful, library for making raw SQL queries to Postgres databases.

This common task can be surprisingly difficult with the standard tools available. This library strives to make this workflow as simple as possible, while providing an elegant interface to work with your query results.

We know how to write SQL, so let's send some to our database:

import records

db = records.Database('postgres://...') rows = db.query('select * from active_users') # or db.query_file('sqls/active-users.sql')</pre>

? The Basics

Rows are represented as standard Python dictionaries: {'column-name': 'value'} .

Grab one row at a time:

>>> rows.next()
{'username': 'hansolo', 'name': 'Henry Ford', 'active': True, 'timezone': datetime.datetime(2016, 2, 6, 22, 28, 23, 894202), 'user_email': 'hansolo@gmail.com'}

Or iterate over them:

for row in rows:
    spam_user(name=row['name'], email=row['user_email'])

Or store them all for later reference:

>>> rows.all()
[{'username': ...}, {'username': ...}, {'username': ...}, ...]

? Features

  • HSTORE support, if available.
  • Iterated rows are cached for future reference.
  • $DATABASE_URL environment variable support.
  • Convenience Database.get_table_names method.
  • Safe parameterization : Database.query('life=%s', params=('42',))
  • Queries can be passed as strings or filenames, parameters supported.
  • Query results are iterators of standard Python dictionaries: {'column-name': 'value'}

Records is proudly powered by Psycopg2 and Tablib .

? Data Export Functionality

Records also features full Tablib integration, and allows you to export your results to CSV, XLS, JSON, HTML Tables, or YAML with a single line of code. Excellent for sharing data with friends, or generating reports.

>>> print rows.dataset
username|active|name      |user_email       |timezone
--------|------|----------|-----------------|--------------------------
hansolo |True  |Henry Ford|hansolo@gmail.com|2016-02-06 22:28:23.894202
...
  • CSV
  • </ul>

    >>> print rows.dataset.csv
    username,active,name,user_email,timezone
    hansolo,True,Henry Ford,hansolo@gmail.com,2016-02-06 22:28:23.894202
    ...
    • YAML
    • </ul>

      >>> print rows.dataset.yaml

      • {active: true, name: Henry Ford, timezone: '2016-02-06 22:28:23.894202', user_email: hansolo@gmail.com, username: hansolo} ...</pre>

        • JSON

        >>> print rows.dataset.json
        [{"username": "hansolo", "active": true, "name": "Henry Ford", "user_email": "hansolo@gmail.com", "timezone": "2016-02-06 22:28:23.894202"}, ...]

        • Excel (xls, xlsx)

        with open('report.xls', 'wb') as f:
          f.write(rows.dataset.xls)

        You get the point. Of course, all other features of Tablib are also available, so you can sort results, add/remove columns/rows, remove duplicates, tranpose the table, add separators, slice data by column, and more.

        See the Tablib Documentation for more details.

        ? Installation

        Of course, the recommended installation method is pip:

        $ pip install records
        :sparkles::cake::sparkles:

        ? Thank You

        Thanks for checking this library out! I hope you find it useful.

        Of course, there's always room for improvement. Feel free toopen an issue so we can make Records better, stronger, faster.

        </article>

 本文由用戶 hpdsrdrvjq 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!