Django-phitbit

An alternative integration of the Fitbit API for Django, with a whole bunch of extra features.

Contents:

Django-phitbit

https://badge.fury.io/py/django-phitbit.png https://travis-ci.org/phalt/django-phitbit.png?branch=master https://pypip.in/d/django-phitbit/badge.png

An alternative integration of the Fitbit API for Django, with a whole bunch of extra features.

Features

  • Fitbit Authentication Views.
  • Store consumer keys in the database.
  • Full Fitbit API access through the Django user model:
>>> usr = User.objects.get(pk=1)
>>> act = usr.phitbit.api.activities()
>>> act['goals']
{u'activeMinutes': 60, u'distance': 6.44, u'caloriesOut': 2000, u'steps': 10000}
  • Wrappers around the Fitbit API for even quicker access to common resources:
>>> usr.phitbit.goals()
{u'activeMinutes': 60, u'distance': 6.44, u'caloriesOut': 2000, u'steps': 10000}
# So much faster than the code above.
  • Store and retrieve collected resources in your Django app:
>>> goal_data = usr.phitbit.goals()
>>> usr.phitbit.store('goals', goal_data)

>>> usr.phitbit.retrieve('goals')
{'data': {u'activeMinutes': 60, u'distance': 6.44, u'caloriesOut': 2000, u'steps': 10000},
 'modified_date': datetime.datetime(2013, 10, 17, 12, 21, 25, 457581)}

TODO

  • Public facing API for stored Phitbit data.
  • Python 3.* compatibility

Installation

Requirements

  • Django 1.5
  • Python 2.7

Installation

  1. At the command line:

    $ easy_install django-phitbit
    
  • OR, if you have pip (the Python package installer) installed:

    $ [sudo] pip install django-phitbit
    
  1. Include the app in your Django settings:

    INSTALLED_APPS = [
    #...,
    # Don't forget the underscore!
    "django_phitbit",
    ]
    
  2. Add Django-phitbit URLS to your URLconf:

    url(r'^fitbit/', include('django_phitbit.urls')),
    
  3. Finally, sync the new database tables with syncdb:

    $ python manage.py syncdb
    

This will setup Django-phitbit read for use.

See the Getting Started page for using Django-phitbit in your project.

Phitbit Defaults

  • Phitbit has a few adjustable settings for redirects and error messages, their defaults are shown below.

  • In order to customise these, add them to your settings.py file as shown below:

    PHITBIT_SUCCESS_REDIRECT = '/'
    PHITBIT_SUCCESS_ERROR = '/505.html/'
    PHITBIT_AUTH_MESSAGE = 'You do not have Fitbit authentication'
    

Upgrading

  • When / if you need to upgrade the Django-phitbit model (check the History page for info), use South to migrate:

    $ python manage.py migrate django_phitbit
    

We’ll make sure this is absolutely clear when it is necessary. For clean installations always use syncdb.

Getting Started

Django-phitbit is designed for simplicity.

For installation see the Installation guide before continuing.

Setup a Fitbit App

  1. First things first - create a Fitbit application at dev.fitbit.com .

  2. From that application, obtain your CONSUMER_SECRET and CONSUMER_KEY tokens.

  3. Create a new PhitbitConsumer object using these keys. This can be done through the Django shell by typing:

    $ python manage.py shell
    
  4. Then create the object:

    >>> from django_phitbit import PhitbitConsumer
    >>> phc = PhitbitConsumer(name='my_app')
    >>> phc.CONSUMER_KEY = 'PASTE_YOUR_KEY_HERE'
    >>> phc.CONSUMER_SECRET = 'PASTE_YOUR_SECRET_HERE'
    >>> phc.save()
    
  • Alternatively, start your Django project with:

    $ python manage.py runserver
    
  • and, in a browser navigate to:

    http://localhost:8000/admin
    
  • Login as an Administrator, click on Phitbit Consumer and then Add New.

  • Enter the CONSUMER_KEY, CONSUMER_SECRET and the app name and then click save.

Authenticating users

Now our Users can start authenticating their accounts with Fitbit!

  1. Based on your URLConf settings, visit:

    http://localhost:8000/fitbit/login/
    
  • This will redirect you to Fitbit.com where you will authorise the app with your user account.

  • NOTE: You must be logged into a valid Django User in order to view these pages.

  • Afterwards, they will be redirected to the ‘/’ path in your URLConf. If you wish to change this, add the following setting in your settings.py:

    PHITBIT_SUCCESS_REDIRECT = '/'
    
  • At this point, a new PhitbitUser object is created, saved and linked to the user.

Errors

  • If an errors occurs, you will be redirected to the default error page:

    PHITBIT_SUCCESS_ERROR = '/505.html/'
    
  • Check your terminal output for more information on errors.

Using Django-phitbit

Following the instructions above, you should now have a Django User object with an authenticated Fitbit account and full access to the Fitbit API.

See the API reference page for full information on a list of the methods.

Below are a few quick examples.

  • Call the API and get steps data for today, then store it in our Django project:

    >>> steps_data = u.phitbit.steps()
    >>> u.phitbit.store('steps', steps_data)
    
  • Retrieve stored steps data and display the total steps count:

    >>> stored_data = u.phitbit.retrieve('steps')
    >>> print stored_data['value']
    2345
    

Decorators

If you want to add views to your Django project that can only be accessed by users who have authenticated Fitbit apps, Django-phitbit comes with a handy decorator:

from django_phitbit.decorators import phitbit_authenticated

@phitbit_authenticated
def my_view(request):
    ...

By adding @phitbit_authenticated a User requires a USER_KEY and USER_SECRET in their linked PhitbitUser object.

It’s probably best to pair this with the @login_required decorator too.

This can help ensure views that use the Fitbit API are not accessed by unauthorised users.

API reference

All Django-phitbit APIs, wrappers, and examples.

PhitbitUserModel

For the examples below, the letter u is used to denote a Django User object.

All functionality for Django-phitbit can be done through the Django User object.

  • store(key, data)

    Store data.

    Creates or updates a PhitbitData object.

    The key must be unique, and assigning new data to an existing key will overwrite the old data.

    Any data type can be stored, we recommend keeping single values for ease of use.

    Returns the newly updated / created object.

    >>> g = u.phitbit.goals()
    >>> u.phitbit.store('goals', g)
    <PhitbitData: goals for user Paul>
    
  • retrieve(key)

    Retrieves stored data.

    If one doesn’t exist, raises a DoesNotExist error.

    >>> u.phitbit.retrieve('goals')
    <PhitbitData: goals for user Paul>
    

Fitbit API wrappers

These wrappers are convience methods for more commonly requested Fitbit resources. All return dictionaries.

The full Python-fitbit API is available through the api object in the PhitbitUser model:

>>> u.phitbit.api
<fitbit.api.Fitbit object at 0x101d07dd0>
  • goals()

    A wrapper around the Python-fitbit function fitbit.activities()[‘goals’]

    >>> u.phitbit.goals()
    {u'activeMinutes': 60, u'distance': 6.44, u'caloriesOut': 2000, u'steps': 10000}
    
  • summary()

    A wrapper around the Python-fibit function fitbit.activities()[‘summary’]

    Returns a summary of the user’s current day

    >>> u.phitbit.summary()
    ...
    
  • devices()

    A wrapper around the Python-fibit function fitbit.get_devices()

    Returns information on the user’s devices.

    >>> u.phitbit.devices()
    ...
    
  • user_profile(user_id=None)

    A wrapper around the Python-fitbit function fitbit.user_profile_get(user_id=None)

    If a user_id is not supplied it returns the current user’s information.

    >>> u.phitbit.user_profile()
    ...
    
  • steps(period=‘1d’, start=None, end=None)

    A wrapper around the Python-fitbit time_series function

    Returns a list of dictionaries for each day

    Period must be one of the following:

    ‘1d’, ‘7d’, ‘30d’, ‘1w’, ‘1m’, ‘3m’, ‘6m’, ‘1y’, ‘max’

    and by default is ‘1d’

    # Get steps for today
    >>> u.phitbit.steps()
    [{u'value': u'3965', u'dateTime': u'2013-10-17'}]
    
    # Change the period to get data from today and back
    >>> u.phitbit.steps(period='7d')
    [{u'value': u'2001', u'dateTime': u'2013-10-11'}, ... , {u'value': u'9635', u'dateTime': u'2013-10-17'}]
    
    # Specify a date range
    >>> u.phitbit.steps(period='7d', start='2013-10-09')
    [{u'value': u'4567', u'dateTime': u'2013-10-09'}, ... , {u'value': u'10635', u'dateTime': u'2013-10-15'}]
    
  • distance(period=‘1d’, start=None, end=None)

    A wrapper around Python-fitbit time_series function

    Requirements are identical to steps() above

    >>> u.phitbit.distance()
    ...
    
  • food_calories_in(period=‘1d’, start=None, end=None)

    A wrapper around Python-fitbit time_series function

    Requirements are identical to steps() above

    >>> u.phitbit.food_calories_in()
    ...
    
  • minutes_asleep(period=‘1d’, start=None, end=None)

    A wrapper around Python-fitbit time_series function

    Requirements are identical to steps() above

    >>> u.phitbit.minutes_asleep()
    ...
    
  • minutes_awake(period=‘1d’, start=None, end=None)

    A wrapper around Python-fitbit time_series function

    Requirements are identical to steps() above

    >>> u.phitbit.minutes_awake()
    ...
    
  • sleep_efficiency(period=‘1d’, start=None, end=None)

    A wrapper around Python-fitbit time_series function

    Requirements are identical to steps() above

    >>> u.phitbit.sleep_efficiency()
    ...
    

Project info:

Contributing

Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.

You can contribute in many ways:

Types of Contributions

Report Bugs

Report bugs at https://github.com/phalt/django-phitbit/issues.

If you are reporting a bug, please include:

  • Your operating system name and version.
  • Any details about your local setup that might be helpful in troubleshooting.
  • Detailed steps to reproduce the bug.
Fix Bugs

Look through the GitHub issues for bugs. Anything tagged with “bug” is open to whoever wants to implement it.

Implement Features

Look through the GitHub issues for features. Anything tagged with “feature” is open to whoever wants to implement it.

Write Documentation

Django-phitbit could always use more documentation, whether as part of the official Django-phitbit docs, in docstrings, or even on the web in blog posts, articles, and such.

Submit Feedback

The best way to send feedback is to file an issue at https://github.com/phalt/django-phitbit/issues.

If you are proposing a feature:

  • Explain in detail how it would work.
  • Keep the scope as narrow as possible, to make it easier to implement.
  • Remember that this is a volunteer-driven project, and that contributions are welcome :)

Get Started!

Ready to contribute? Here’s how to set up django-phitbit for local development.

  1. Fork the django-phitbit repo on GitHub.

  2. Clone your fork locally:

    $ git clone git@github.com:your_name_here/django-phitbit.git
    
  3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:

    $ mkvirtualenv django-phitbit
    $ cd django-phitbit/
    $ python setup.py develop
    
  4. Create a branch for local development:

    $ git checkout -b name-of-your-bugfix-or-feature
    
Now you can make your changes locally.

5. When you’re done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:

  $ flake8 django-phitbit tests
        $ python setup.py test
  $ tox

To get flake8 and tox, just pip install them into your virtualenv.
  1. Commit your changes and push your branch to GitHub:

    $ git add .
    $ git commit -m "Your detailed description of your changes."
    $ git push origin name-of-your-bugfix-or-feature
    
  2. Submit a pull request through the GitHub website.

Pull Request Guidelines

Before you submit a pull request, check that it meets these guidelines:

  1. The pull request should include tests.
  2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst.
  3. The pull request should work for Python 2.6, 2.7, and 3.3, and for PyPy. Check https://travis-ci.org/phalt/django-phitbit/pull_requests and make sure that the tests pass for all supported Python versions.

Tips

To run a subset of tests:

$ python -m unittest tests.test_django-phitbit

Credits

Development Lead

Contributors

None yet. Why not be the first?

Thanks

History

0.1.2 (2013-10-22)

  • Fixed bugs in decorators
  • Removed unused imports
  • Flake8 cleanup

0.1.1 (2013-10-21)

  • Inevitable bug fixes

0.1.0 (2013-10-21)

  • Initial public release.
  • All basic functionality implementation.
  • Decorators functionality.
  • Tests for 0.1.0
  • Documentation write up.

Showcase

Websites using Django-phitbit

Add your own! See Contributing

Indices and tables