pax_global_header 0000666 0000000 0000000 00000000064 12464570011 0014512 g ustar 00root root 0000000 0000000 52 comment=b5188b1f336438a4986ad7d6f2a0446440c7c239
python-fitbit-0.1.3/ 0000775 0000000 0000000 00000000000 12464570011 0014313 5 ustar 00root root 0000000 0000000 python-fitbit-0.1.3/.gitignore 0000664 0000000 0000000 00000000140 12464570011 0016276 0 ustar 00root root 0000000 0000000 *.pyc
*.DS_Store
.coverage
.tox
*~
docs/_build
*.egg-info
*.egg
dist
build
env
# Editors
.idea
python-fitbit-0.1.3/.travis.yml 0000664 0000000 0000000 00000000320 12464570011 0016417 0 ustar 00root root 0000000 0000000 language: python
python: 3.3
env:
- TOX_ENV=pypy
- TOX_ENV=py33
- TOX_ENV=py32
- TOX_ENV=py27
- TOX_ENV=py26
install:
- pip install coveralls tox
script: tox -e $TOX_ENV
after_success: coveralls
python-fitbit-0.1.3/AUTHORS 0000664 0000000 0000000 00000000422 12464570011 0015361 0 ustar 00root root 0000000 0000000 Issac Kelly (Kelly Creative Tech)
Percy Perez (ORCAS)
Rebecca Lovewell (Caktus Consulting Group)
Dan Poirier (Caktus Consulting Group)
Brad Pitcher (ORCAS)
Silvio Tomatis
Steven Skoczen
Eric Xu
Josh Gachnang
Lorenzo Mancini
David Grandinetti
Chris Streeter
Mario Sangiorgio
python-fitbit-0.1.3/CHANGELOG.rst 0000664 0000000 0000000 00000002421 12464570011 0016333 0 ustar 00root root 0000000 0000000 0.1.3 (2015-02-04)
==================
* Support Intraday Time Series API
* Use connection pooling to avoid a TCP and SSL handshake for every API call
0.1.2 (2014-09-19)
==================
* Quick fix for response objects without a status code
0.1.1 (2014-09-18)
==================
* Fix the broken foods log date endpoint
* Integrate with travis-ci.org, coveralls.io, and requires.io
* Add HTTPTooManyRequests exception with retry_after_secs information
* Enable adding parameters to authorize token URL
0.1.0 (2014-04-15)
==================
* Officially test/support Python 3.2+ and PyPy in addition to Python 2.x
* Clean up OAuth workflow, change the API slightly to match oauthlib terminology
* Fix some minor bugs
0.0.5 (2014-03-30)
==================
* Switch from python-oauth2 to the better supported oauthlib
* Add get_bodyweight and get_bodyfat methods
0.0.3 (2014-02-05)
==================
* Add get_badges method
* Include error messages in the exception
* Add API for alarms
* Add API for log activity
* Correctly pass headers on requests
* Way more test coverage
* Publish to PyPI
0.0.2 (2012-10-02)
==================
* Add docs, including Readthedocs support
* Add tests
* Use official oauth2 version from pypi
0.0.1 (2012-02-25)
==================
* Initial release
python-fitbit-0.1.3/LICENSE 0000664 0000000 0000000 00000001102 12464570011 0015312 0 ustar 00root root 0000000 0000000 Copyright 2012-2015 ORCAS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
python-fitbit-0.1.3/MANIFEST.in 0000664 0000000 0000000 00000000071 12464570011 0016047 0 ustar 00root root 0000000 0000000 include LICENSE AUTHORS README.rst requirements/* docs/*
python-fitbit-0.1.3/README.rst 0000664 0000000 0000000 00000003115 12464570011 0016002 0 ustar 00root root 0000000 0000000 python-fitbit
=============
.. image:: https://travis-ci.org/orcasgit/python-fitbit.svg?branch=master
:target: https://travis-ci.org/orcasgit/python-fitbit
:alt: Build Status
.. image:: https://coveralls.io/repos/orcasgit/python-fitbit/badge.png?branch=master
:target: https://coveralls.io/r/orcasgit/python-fitbit?branch=master
:alt: Coverage Status
.. image:: https://requires.io/github/orcasgit/python-fitbit/requirements.png?branch=master
:target: https://requires.io/github/orcasgit/python-fitbit/requirements/?branch=master
:alt: Requirements Status
Fitbit API Python Client Implementation
For documentation: `http://python-fitbit.readthedocs.org/ `_
Requirements
============
* Python 2.6+
* `python-dateutil`_ (always)
* `requests-oauthlib`_ (always)
* `Sphinx`_ (to create the documention)
* `tox`_ (for running the tests)
* `coverage`_ (to create test coverage reports)
.. _python-dateutil: https://pypi.python.org/pypi/python-dateutil/2.4.0
.. _requests-oauthlib: https://pypi.python.org/pypi/requests-oauthlib
.. _Sphinx: https://pypi.python.org/pypi/Sphinx
.. _tox: https://pypi.python.org/pypi/tox
.. _coverage: https://pypi.python.org/pypi/coverage/
To use the library, you need to install the run time requirements:
sudo pip install -r requirements/base.txt
To modify and test the library, you need to install the developer requirements:
sudo pip install -r requirements/dev.txt
To run the library on a continuous integration server, you need to install the test requirements:
sudo pip install -r requirements/test.txt
python-fitbit-0.1.3/TODO 0000664 0000000 0000000 00000000147 12464570011 0015005 0 ustar 00root root 0000000 0000000 TODO
* Public calls only based on consumer_key, (should work, untested)
* Change Units
* Docs
* Tests
python-fitbit-0.1.3/docs/ 0000775 0000000 0000000 00000000000 12464570011 0015243 5 ustar 00root root 0000000 0000000 python-fitbit-0.1.3/docs/Makefile 0000664 0000000 0000000 00000012730 12464570011 0016706 0 ustar 00root root 0000000 0000000 # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make ' where is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Python-Fitbit.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Python-Fitbit.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/Python-Fitbit"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Python-Fitbit"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
python-fitbit-0.1.3/docs/conf.py 0000664 0000000 0000000 00000017332 12464570011 0016550 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# Python-Fitbit documentation build configuration file, created by
# sphinx-quickstart on Wed Mar 14 18:51:57 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Python-Fitbit'
copyright = u'Copyright 2012-2015 ORCAS'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1.3'
# The full version, including alpha/beta/rc tags.
release = '0.1.3'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Python-Fitbitdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Python-Fitbit.tex', u'Python-Fitbit Documentation',
u'Issac Kelly, Percy Perez, Brad Pitcher', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'python-fitbit', u'Python-Fitbit Documentation',
[u'Issac Kelly, Percy Perez, Brad Pitcher'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Python-Fitbit', u'Python-Fitbit Documentation',
u'Issac Kelly, Percy Perez, Brad Pitcher', 'Python-Fitbit', 'Fitbit API Python Client Implementation',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
python-fitbit-0.1.3/docs/index.rst 0000664 0000000 0000000 00000002613 12464570011 0017106 0 ustar 00root root 0000000 0000000 .. Python-Fitbit documentation master file, created by
sphinx-quickstart on Wed Mar 14 18:51:57 2012.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Overview
========
This is a complete python implementation of the Fitbit API.
It uses oAuth for authentication, it supports both us and si
measurements
Quickstart
==========
Here is some example usage::
import fitbit
unauth_client = fitbit.Fitbit('', '')
# certain methods do not require user keys
unauth_client.activities()
# You'll have to gather the user keys on your own, or try ./fitbit/gather_keys_cli.py for development
authd_client = fitbit.Fitbit('', '', resource_owner_key='', resource_owner_secret='')
authd_client.sleep()
Fitbit API
==========
Some assumptions you should note. Anywhere it says user_id=None,
it assumes the current user_id from the credentials given, and passes
a ``-`` through the API. Anywhere it says date=None, it should accept
either ``None`` or a ``date`` or ``datetime`` object
(anything with proper strftime will do), or a string formatted
as ``%Y-%m-%d``.
.. autoclass:: fitbit.Fitbit
:private-members:
:members:
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
python-fitbit-0.1.3/docs/make.bat 0000664 0000000 0000000 00000011766 12464570011 0016663 0 ustar 00root root 0000000 0000000 @ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set I18NSPHINXOPTS=%SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^` where ^ is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Python-Fitbit.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Python-Fitbit.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
:end
python-fitbit-0.1.3/fitbit/ 0000775 0000000 0000000 00000000000 12464570011 0015574 5 ustar 00root root 0000000 0000000 python-fitbit-0.1.3/fitbit/__init__.py 0000664 0000000 0000000 00000000657 12464570011 0017715 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
"""
Fitbit API Library
------------------
:copyright: 2012-2015 ORCAS.
:license: BSD, see LICENSE for more details.
"""
from .api import Fitbit, FitbitOauthClient
# Meta.
__title__ = 'fitbit'
__author__ = 'Issac Kelly and ORCAS'
__author_email__ = 'bpitcher@orcasinc.com'
__copyright__ = 'Copyright 2012-2015 ORCAS'
__license__ = 'Apache 2.0'
__version__ = '0.1.3'
# Module namespace.
all_tests = []
python-fitbit-0.1.3/fitbit/api.py 0000664 0000000 0000000 00000101527 12464570011 0016725 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
import requests
import json
import datetime
try:
from urllib.parse import urlencode
except ImportError:
# Python 2.x
from urllib import urlencode
from requests_oauthlib import OAuth1, OAuth1Session
from fitbit.exceptions import (BadResponse, DeleteError, HTTPBadRequest,
HTTPUnauthorized, HTTPForbidden,
HTTPServerError, HTTPConflict, HTTPNotFound,
HTTPTooManyRequests)
from fitbit.utils import curry
class FitbitOauthClient(object):
API_ENDPOINT = "https://api.fitbit.com"
AUTHORIZE_ENDPOINT = "https://www.fitbit.com"
API_VERSION = 1
request_token_url = "%s/oauth/request_token" % API_ENDPOINT
access_token_url = "%s/oauth/access_token" % API_ENDPOINT
authorization_url = "%s/oauth/authorize" % AUTHORIZE_ENDPOINT
def __init__(self, client_key, client_secret, resource_owner_key=None,
resource_owner_secret=None, user_id=None, callback_uri=None,
*args, **kwargs):
"""
Create a FitbitOauthClient object. Specify the first 5 parameters if
you have them to access user data. Specify just the first 2 parameters
to access anonymous data and start the set up for user authorization.
Set callback_uri to a URL and when the user has granted us access at
the fitbit site, fitbit will redirect them to the URL you passed. This
is how we get back the magic verifier string from fitbit if we're a web
app. If we don't pass it, then fitbit will just display the verifier
string for the user to copy and we'll have to ask them to paste it for
us and read it that way.
"""
self.session = requests.Session()
self.client_key = client_key
self.client_secret = client_secret
self.resource_owner_key = resource_owner_key
self.resource_owner_secret = resource_owner_secret
if user_id:
self.user_id = user_id
params = {'client_secret': client_secret}
if callback_uri:
params['callback_uri'] = callback_uri
if self.resource_owner_key and self.resource_owner_secret:
params['resource_owner_key'] = self.resource_owner_key
params['resource_owner_secret'] = self.resource_owner_secret
self.oauth = OAuth1Session(client_key, **params)
def _request(self, method, url, **kwargs):
"""
A simple wrapper around requests.
"""
return self.session.request(method, url, **kwargs)
def make_request(self, url, data={}, method=None, **kwargs):
"""
Builds and makes the OAuth Request, catches errors
https://wiki.fitbit.com/display/API/API+Response+Format+And+Errors
"""
if not method:
method = 'POST' if data else 'GET'
auth = OAuth1(
self.client_key, self.client_secret, self.resource_owner_key,
self.resource_owner_secret, signature_type='auth_header')
response = self._request(method, url, data=data, auth=auth, **kwargs)
if response.status_code == 401:
raise HTTPUnauthorized(response)
elif response.status_code == 403:
raise HTTPForbidden(response)
elif response.status_code == 404:
raise HTTPNotFound(response)
elif response.status_code == 409:
raise HTTPConflict(response)
elif response.status_code == 429:
exc = HTTPTooManyRequests(response)
exc.retry_after_secs = int(response.headers['Retry-After'])
raise exc
elif response.status_code >= 500:
raise HTTPServerError(response)
elif response.status_code >= 400:
raise HTTPBadRequest(response)
return response
def fetch_request_token(self):
"""
Step 1 of getting authorized to access a user's data at fitbit: this
makes a signed request to fitbit to get a token to use in step 3.
Returns that token.}
"""
token = self.oauth.fetch_request_token(self.request_token_url)
self.resource_owner_key = token.get('oauth_token')
self.resource_owner_secret = token.get('oauth_token_secret')
return token
def authorize_token_url(self, **kwargs):
"""Step 2: Return the URL the user needs to go to in order to grant us
authorization to look at their data. Then redirect the user to that
URL, open their browser to it, or tell them to copy the URL into their
browser. Allow the client to request the mobile display by passing
the display='touch' argument.
"""
return self.oauth.authorization_url(self.authorization_url, **kwargs)
def fetch_access_token(self, verifier, token=None):
"""Step 3: Given the verifier from fitbit, and optionally a token from
step 1 (not necessary if using the same FitbitOAuthClient object) calls
fitbit again and returns an access token object. Extract the needed
information from that and save it to use in future API calls.
"""
if token:
self.resource_owner_key = token.get('oauth_token')
self.resource_owner_secret = token.get('oauth_token_secret')
self.oauth = OAuth1Session(
self.client_key,
client_secret=self.client_secret,
resource_owner_key=self.resource_owner_key,
resource_owner_secret=self.resource_owner_secret,
verifier=verifier)
response = self.oauth.fetch_access_token(self.access_token_url)
self.user_id = response.get('encoded_user_id')
self.resource_owner_key = response.get('oauth_token')
self.resource_owner_secret = response.get('oauth_token_secret')
return response
class Fitbit(object):
US = 'en_US'
METRIC = 'en_UK'
API_ENDPOINT = "https://api.fitbit.com"
API_VERSION = 1
WEEK_DAYS = ['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY']
_resource_list = [
'body',
'activities',
'foods/log',
'water',
'sleep',
'heart',
'bp',
'glucose',
]
_qualifiers = [
'recent',
'favorite',
'frequent',
]
def __init__(self, client_key, client_secret, system=US, **kwargs):
self.client = FitbitOauthClient(client_key, client_secret, **kwargs)
self.SYSTEM = system
# All of these use the same patterns, define the method for accessing
# creating and deleting records once, and use curry to make individual
# Methods for each
for resource in self._resource_list:
setattr(self, resource.replace('/', '_'),
curry(self._COLLECTION_RESOURCE, resource))
if resource not in ['body', 'glucose']:
# Body and Glucose entries are not currently able to be deleted
setattr(self, 'delete_%s' % resource, curry(
self._DELETE_COLLECTION_RESOURCE, resource))
for qualifier in self._qualifiers:
setattr(self, '%s_activities' % qualifier, curry(self.activity_stats, qualifier=qualifier))
setattr(self, '%s_foods' % qualifier, curry(self._food_stats,
qualifier=qualifier))
def make_request(self, *args, **kwargs):
##@ This should handle data level errors, improper requests, and bad
# serialization
headers = kwargs.get('headers', {})
headers.update({'Accept-Language': self.SYSTEM})
kwargs['headers'] = headers
method = kwargs.get('method', 'POST' if 'data' in kwargs else 'GET')
response = self.client.make_request(*args, **kwargs)
if response.status_code == 202:
return True
if method == 'DELETE':
if response.status_code == 204:
return True
else:
raise DeleteError(response)
try:
rep = json.loads(response.content.decode('utf8'))
except ValueError:
raise BadResponse
return rep
def user_profile_get(self, user_id=None):
"""
Get a user profile. You can get other user's profile information
by passing user_id, or you can get the current user's by not passing
a user_id
.. note:
This is not the same format that the GET comes back in, GET requests
are wrapped in {'user': }
https://wiki.fitbit.com/display/API/API-Get-User-Info
"""
if user_id is None:
user_id = "-"
url = "%s/%s/user/%s/profile.json" % (self.API_ENDPOINT,
self.API_VERSION, user_id)
return self.make_request(url)
def user_profile_update(self, data):
"""
Set a user profile. You can set your user profile information by
passing a dictionary of attributes that will be updated.
.. note:
This is not the same format that the GET comes back in, GET requests
are wrapped in {'user': }
https://wiki.fitbit.com/display/API/API-Update-User-Info
"""
url = "%s/%s/user/-/profile.json" % (self.API_ENDPOINT,
self.API_VERSION)
return self.make_request(url, data)
def _COLLECTION_RESOURCE(self, resource, date=None, user_id=None,
data=None):
"""
Retrieving and logging of each type of collection data.
Arguments:
resource, defined automatically via curry
[date] defaults to today
[user_id] defaults to current logged in user
[data] optional, include for creating a record, exclude for access
This implements the following methods::
body(date=None, user_id=None, data=None)
activities(date=None, user_id=None, data=None)
foods_log(date=None, user_id=None, data=None)
water(date=None, user_id=None, data=None)
sleep(date=None, user_id=None, data=None)
heart(date=None, user_id=None, data=None)
bp(date=None, user_id=None, data=None)
* https://wiki.fitbit.com/display/API/Fitbit+Resource+Access+API
"""
if not date:
date = datetime.date.today()
if not user_id:
user_id = '-'
if not isinstance(date, str):
date = date.strftime('%Y-%m-%d')
if not data:
url = "%s/%s/user/%s/%s/date/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
user_id,
resource,
date,
)
else:
data['date'] = date
url = "%s/%s/user/%s/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
user_id,
resource,
)
return self.make_request(url, data)
def _DELETE_COLLECTION_RESOURCE(self, resource, log_id):
"""
deleting each type of collection data
Arguments:
resource, defined automatically via curry
log_id, required, log entry to delete
This builds the following methods::
delete_body(log_id)
delete_activities(log_id)
delete_foods(log_id)
delete_water(log_id)
delete_sleep(log_id)
delete_heart(log_id)
delete_bp(log_id)
"""
url = "%s/%s/user/-/%s/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
resource,
log_id,
)
response = self.make_request(url, method='DELETE')
return response
def time_series(self, resource, user_id=None, base_date='today',
period=None, end_date=None):
"""
The time series is a LOT of methods, (documented at url below) so they
don't get their own method. They all follow the same patterns, and
return similar formats.
Taking liberty, this assumes a base_date of today, the current user,
and a 1d period.
https://wiki.fitbit.com/display/API/API-Get-Time-Series
"""
if not user_id:
user_id = '-'
if period and end_date:
raise TypeError("Either end_date or period can be specified, not both")
if end_date:
if not isinstance(end_date, str):
end = end_date.strftime('%Y-%m-%d')
else:
end = end_date
else:
if not period in ['1d', '7d', '30d', '1w', '1m', '3m', '6m', '1y', 'max']:
raise ValueError("Period must be one of '1d', '7d', '30d', '1w', '1m', '3m', '6m', '1y', 'max'")
end = period
if not isinstance(base_date, str):
base_date = base_date.strftime('%Y-%m-%d')
url = "%s/%s/user/%s/%s/date/%s/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
user_id,
resource,
base_date,
end
)
return self.make_request(url)
def intraday_time_series(self, resource, base_date='today', detail_level='1min', start_time=None, end_time=None):
"""
The intraday time series extends the functionality of the regular time series, but returning data at a
more granular level for a single day, defaulting to 1 minute intervals. To access this feature, one must
send an email to api@fitbit.com and request to have access to the Partner API
(see https://wiki.fitbit.com/display/API/Fitbit+Partner+API). For details on the resources available, see:
https://wiki.fitbit.com/display/API/API-Get-Intraday-Time-Series
"""
if start_time and not end_time:
raise TypeError("You must provide an end time when you provide a start time")
if end_time and not start_time:
raise TypeError("You must provide a start time when you provide an end time")
if not isinstance(base_date, str):
base_date = base_date.strftime('%Y-%m-%d')
if not detail_level in ['1min', '15min']:
raise ValueError("Period must be either '1min' or '15min'")
url = "%s/%s/user/-/%s/date/%s/1d/%s" % (
self.API_ENDPOINT,
self.API_VERSION,
resource,
base_date,
detail_level
)
if start_time:
time_init = start_time
if not isinstance(time_init, str):
time_init = start_time.strftime('%H:%M')
url = url + ('/time/%s' % (time_init))
if end_time:
time_fin = end_time
if not isinstance(time_fin, str):
time_fin = time_fin.strftime('%H:%M')
url = url + ('/%s' % (time_fin))
url = url + '.json'
return self.make_request(url)
def activity_stats(self, user_id=None, qualifier=''):
"""
* https://wiki.fitbit.com/display/API/API-Get-Activity-Stats
* https://wiki.fitbit.com/display/API/API-Get-Favorite-Activities
* https://wiki.fitbit.com/display/API/API-Get-Recent-Activities
* https://wiki.fitbit.com/display/API/API-Get-Frequent-Activities
This implements the following methods::
recent_activities(user_id=None, qualifier='')
favorite_activities(user_id=None, qualifier='')
frequent_activities(user_id=None, qualifier='')
"""
if not user_id:
user_id = '-'
if qualifier:
if qualifier in self._qualifiers:
qualifier = '/%s' % qualifier
else:
raise ValueError("Qualifier must be one of %s"
% ', '.join(self._qualifiers))
else:
qualifier = ''
url = "%s/%s/user/%s/activities%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
user_id,
qualifier,
)
return self.make_request(url)
def _food_stats(self, user_id=None, qualifier=''):
"""
This builds the convenience methods on initialization::
recent_foods(user_id=None, qualifier='')
favorite_foods(user_id=None, qualifier='')
frequent_foods(user_id=None, qualifier='')
* https://wiki.fitbit.com/display/API/API-Get-Recent-Foods
* https://wiki.fitbit.com/display/API/API-Get-Frequent-Foods
* https://wiki.fitbit.com/display/API/API-Get-Favorite-Foods
"""
if not user_id:
user_id = '-'
url = "%s/%s/user/%s/foods/log/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
user_id,
qualifier,
)
return self.make_request(url)
def add_favorite_activity(self, activity_id):
"""
https://wiki.fitbit.com/display/API/API-Add-Favorite-Activity
"""
url = "%s/%s/user/-/activities/favorite/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
activity_id,
)
return self.make_request(url, method='POST')
def log_activity(self, data):
"""
https://wiki.fitbit.com/display/API/API-Log-Activity
"""
url = "%s/%s/user/-/activities.json" % (
self.API_ENDPOINT,
self.API_VERSION)
return self.make_request(url, data = data)
def delete_favorite_activity(self, activity_id):
"""
https://wiki.fitbit.com/display/API/API-Delete-Favorite-Activity
"""
url = "%s/%s/user/-/activities/favorite/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
activity_id,
)
return self.make_request(url, method='DELETE')
def add_favorite_food(self, food_id):
"""
https://wiki.fitbit.com/display/API/API-Add-Favorite-Food
"""
url = "%s/%s/user/-/foods/log/favorite/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
food_id,
)
return self.make_request(url, method='POST')
def delete_favorite_food(self, food_id):
"""
https://wiki.fitbit.com/display/API/API-Delete-Favorite-Food
"""
url = "%s/%s/user/-/foods/log/favorite/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
food_id,
)
return self.make_request(url, method='DELETE')
def create_food(self, data):
"""
https://wiki.fitbit.com/display/API/API-Create-Food
"""
url = "%s/%s/user/-/foods.json" % (
self.API_ENDPOINT,
self.API_VERSION,
)
return self.make_request(url, data=data)
def get_meals(self):
"""
https://wiki.fitbit.com/display/API/API-Get-Meals
"""
url = "%s/%s/user/-/meals.json" % (
self.API_ENDPOINT,
self.API_VERSION,
)
return self.make_request(url)
def get_devices(self):
"""
https://wiki.fitbit.com/display/API/API-Get-Devices
"""
url = "%s/%s/user/-/devices.json" % (
self.API_ENDPOINT,
self.API_VERSION,
)
return self.make_request(url)
def get_alarms(self, device_id):
"""
https://wiki.fitbit.com/display/API/API-Devices-Get-Alarms
"""
url = "%s/%s/user/-/devices/tracker/%s/alarms.json" % (
self.API_ENDPOINT,
self.API_VERSION,
device_id
)
return self.make_request(url)
def add_alarm(self, device_id, alarm_time, week_days, recurring=False, enabled=True, label=None,
snooze_length=None, snooze_count=None, vibe='DEFAULT'):
"""
https://wiki.fitbit.com/display/API/API-Devices-Add-Alarm
alarm_time should be a timezone aware datetime object.
"""
url = "%s/%s/user/-/devices/tracker/%s/alarms.json" % (
self.API_ENDPOINT,
self.API_VERSION,
device_id
)
alarm_time = alarm_time.strftime("%H:%M%z")
# Check week_days list
if not isinstance(week_days, list):
raise ValueError("Week days needs to be a list")
for day in week_days:
if day not in self.WEEK_DAYS:
raise ValueError("Incorrect week day %s. see WEEK_DAY_LIST." % day)
data = {
'time': alarm_time,
'weekDays': week_days,
'recurring': recurring,
'enabled': enabled,
'vibe': vibe
}
if label:
data['label'] = label
if snooze_length:
data['snoozeLength'] = snooze_length
if snooze_count:
data['snoozeCount'] = snooze_count
return self.make_request(url, data=data, method="POST")
# return
def update_alarm(self, device_id, alarm_id, alarm_time, week_days, recurring=False, enabled=True, label=None,
snooze_length=None, snooze_count=None, vibe='DEFAULT'):
"""
https://wiki.fitbit.com/display/API/API-Devices-Update-Alarm
alarm_time should be a timezone aware datetime object.
"""
# TODO Refactor with create_alarm. Tons of overlap.
# Check week_days list
if not isinstance(week_days, list):
raise ValueError("Week days needs to be a list")
for day in week_days:
if day not in self.WEEK_DAYS:
raise ValueError("Incorrect week day %s. see WEEK_DAY_LIST." % day)
url = "%s/%s/user/-/devices/tracker/%s/alarms/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
device_id,
alarm_id
)
alarm_time = alarm_time.strftime("%H:%M%z")
data = {
'time': alarm_time,
'weekDays': week_days,
'recurring': recurring,
'enabled': enabled,
'vibe': vibe
}
if label:
data['label'] = label
if snooze_length:
data['snoozeLength'] = snooze_length
if snooze_count:
data['snoozeCount'] = snooze_count
return self.make_request(url, data=data, method="POST")
# return
def delete_alarm(self, device_id, alarm_id):
"""
https://wiki.fitbit.com/display/API/API-Devices-Delete-Alarm
"""
url = "%s/%s/user/-/devices/tracker/%s/alarms/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
device_id,
alarm_id
)
return self.make_request(url, method="DELETE")
def get_sleep(self, date):
"""
https://wiki.fitbit.com/display/API/API-Get-Sleep
date should be a datetime.date object.
"""
url = "%s/%s/user/-/sleep/date/%s-%s-%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
date.year,
date.month,
date.day
)
return self.make_request(url)
def log_sleep(self, start_time, duration):
"""
https://wiki.fitbit.com/display/API/API-Log-Sleep
start time should be a datetime object. We will be using the year, month, day, hour, and minute.
"""
data = {
'startTime': start_time.strftime("%H:%M"),
'duration': duration,
'date': start_time.strftime("%Y-%m-%d"),
}
url = "%s/%s/user/-/sleep.json" % (
self.API_ENDPOINT,
self.API_VERSION,
)
return self.make_request(url, data=data, method="POST")
def activities_list(self):
"""
https://wiki.fitbit.com/display/API/API-Browse-Activities
"""
url = "%s/%s/activities.json" % (
self.API_ENDPOINT,
self.API_VERSION,
)
return self.make_request(url)
def activity_detail(self, activity_id):
"""
https://wiki.fitbit.com/display/API/API-Get-Activity
"""
url = "%s/%s/activities/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
activity_id
)
return self.make_request(url)
def search_foods(self, query):
"""
https://wiki.fitbit.com/display/API/API-Search-Foods
"""
url = "%s/%s/foods/search.json?%s" % (
self.API_ENDPOINT,
self.API_VERSION,
urlencode({'query': query})
)
return self.make_request(url)
def food_detail(self, food_id):
"""
https://wiki.fitbit.com/display/API/API-Get-Food
"""
url = "%s/%s/foods/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
food_id
)
return self.make_request(url)
def food_units(self):
"""
https://wiki.fitbit.com/display/API/API-Get-Food-Units
"""
url = "%s/%s/foods/units.json" % (
self.API_ENDPOINT,
self.API_VERSION
)
return self.make_request(url)
def get_bodyweight(self, base_date=None, user_id=None, period=None, end_date=None):
"""
https://wiki.fitbit.com/display/API/API-Get-Body-Weight
base_date should be a datetime.date object (defaults to today),
period can be '1d', '7d', '30d', '1w', '1m', '3m', '6m', '1y', 'max' or None
end_date should be a datetime.date object, or None.
You can specify period or end_date, or neither, but not both.
"""
if not base_date:
base_date = datetime.date.today()
if not user_id:
user_id = '-'
if period and end_date:
raise TypeError("Either end_date or period can be specified, not both")
if not isinstance(base_date, str):
base_date_string = base_date.strftime('%Y-%m-%d')
else:
base_date_string = base_date
if period:
if not period in ['1d', '7d', '30d', '1w', '1m', '3m', '6m', '1y', 'max']:
raise ValueError("Period must be one of '1d', '7d', '30d', '1w', '1m', '3m', '6m', '1y', 'max'")
url = "%s/%s/user/%s/body/log/weight/date/%s/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
user_id,
base_date_string,
period
)
elif end_date:
if not isinstance(end_date, str):
end_string = end_date.strftime('%Y-%m-%d')
else:
end_string = end_date
url = "%s/%s/user/%s/body/log/weight/date/%s/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
user_id,
base_date_string,
end_string
)
else:
url = "%s/%s/user/%s/body/log/weight/date/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
user_id,
base_date_string,
)
return self.make_request(url)
def get_bodyfat(self, base_date=None, user_id=None, period=None, end_date=None):
"""
https://wiki.fitbit.com/display/API/API-Get-Body-fat
base_date should be a datetime.date object (defaults to today),
period can be '1d', '7d', '30d', '1w', '1m', '3m', '6m', '1y', 'max' or None
end_date should be a datetime.date object, or None.
You can specify period or end_date, or neither, but not both.
"""
if not base_date:
base_date = datetime.date.today()
if not user_id:
user_id = '-'
if period and end_date:
raise TypeError("Either end_date or period can be specified, not both")
if not isinstance(base_date, str):
base_date_string = base_date.strftime('%Y-%m-%d')
else:
base_date_string = base_date
if period:
if not period in ['1d', '7d', '30d', '1w', '1m', '3m', '6m', '1y', 'max']:
raise ValueError("Period must be one of '1d', '7d', '30d', '1w', '1m', '3m', '6m', '1y', 'max'")
url = "%s/%s/user/%s/body/log/fat/date/%s/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
user_id,
base_date_string,
period
)
elif end_date:
if not isinstance(end_date, str):
end_string = end_date.strftime('%Y-%m-%d')
else:
end_string = end_date
url = "%s/%s/user/%s/body/log/fat/date/%s/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
user_id,
base_date_string,
end_string
)
else:
url = "%s/%s/user/%s/body/log/fat/date/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
user_id,
base_date_string,
)
return self.make_request(url)
def get_friends(self, user_id=None):
"""
https://wiki.fitbit.com/display/API/API-Get-Friends
"""
if not user_id:
user_id = '-'
url = "%s/%s/user/%s/friends.json" % (
self.API_ENDPOINT,
self.API_VERSION,
user_id
)
return self.make_request(url)
def get_friends_leaderboard(self, period):
"""
https://wiki.fitbit.com/display/API/API-Get-Friends-Leaderboard
"""
if not period in ['7d', '30d']:
raise ValueError("Period must be one of '7d', '30d'")
url = "%s/%s/user/-/friends/leaders/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
period
)
return self.make_request(url)
def invite_friend(self, data):
"""
https://wiki.fitbit.com/display/API/API-Create-Invite
"""
url = "%s/%s/user/-/friends/invitations.json" % (
self.API_ENDPOINT,
self.API_VERSION,
)
return self.make_request(url, data=data)
def invite_friend_by_email(self, email):
"""
Convenience Method for
https://wiki.fitbit.com/display/API/API-Create-Invite
"""
return self.invite_friend({'invitedUserEmail': email})
def invite_friend_by_userid(self, user_id):
"""
Convenience Method for
https://wiki.fitbit.com/display/API/API-Create-Invite
"""
return self.invite_friend({'invitedUserId': user_id})
def respond_to_invite(self, other_user_id, accept=True):
"""
https://wiki.fitbit.com/display/API/API-Accept-Invite
"""
url = "%s/%s/user/-/friends/invitations/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
other_user_id,
)
accept = 'true' if accept else 'false'
return self.make_request(url, data={'accept': accept})
def accept_invite(self, other_user_id):
"""
Convenience method for respond_to_invite
"""
return self.respond_to_invite(other_user_id)
def reject_invite(self, other_user_id):
"""
Convenience method for respond_to_invite
"""
return self.respond_to_invite(other_user_id, accept=False)
def get_badges(self, user_id=None):
"""
https://wiki.fitbit.com/display/API/API-Get-Badges
"""
if not user_id:
user_id = '-'
url = "%s/%s/user/%s/badges.json" % (
self.API_ENDPOINT,
self.API_VERSION,
user_id
)
return self.make_request(url)
def subscription(self, subscription_id, subscriber_id, collection=None,
method='POST'):
"""
https://wiki.fitbit.com/display/API/Fitbit+Subscriptions+API
"""
if not collection:
url = "%s/%s/user/-/apiSubscriptions/%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
subscription_id
)
else:
url = "%s/%s/user/-/%s/apiSubscriptions/%s-%s.json" % (
self.API_ENDPOINT,
self.API_VERSION,
collection,
subscription_id,
collection
)
return self.make_request(
url,
method=method,
headers={"X-Fitbit-Subscriber-id": subscriber_id}
)
def list_subscriptions(self, collection=''):
"""
https://wiki.fitbit.com/display/API/Fitbit+Subscriptions+API
"""
if collection:
collection = '/%s' % collection
url = "%s/%s/user/-%s/apiSubscriptions.json" % (
self.API_ENDPOINT,
self.API_VERSION,
collection,
)
return self.make_request(url)
@classmethod
def from_oauth_keys(self, client_key, client_secret, user_key=None,
user_secret=None, user_id=None, system=US):
client = FitbitOauthClient(client_key, client_secret, user_key,
user_secret, user_id)
return self(client, system)
python-fitbit-0.1.3/fitbit/exceptions.py 0000664 0000000 0000000 00000002552 12464570011 0020333 0 ustar 00root root 0000000 0000000 import json
class BadResponse(Exception):
"""
Currently used if the response can't be json encoded, despite a .json extension
"""
pass
class DeleteError(Exception):
"""
Used when a delete request did not return a 204
"""
pass
class HTTPException(Exception):
def __init__(self, response, *args, **kwargs):
try:
errors = json.loads(response.content.decode('utf8'))['errors']
message = '\n'.join([error['message'] for error in errors])
except Exception:
if hasattr(response, 'status_code') and response.status_code == 401:
message = response.content.decode('utf8')
else:
message = response
super(HTTPException, self).__init__(message, *args, **kwargs)
class HTTPBadRequest(HTTPException):
"""Generic >= 400 error
"""
pass
class HTTPUnauthorized(HTTPException):
"""401
"""
pass
class HTTPForbidden(HTTPException):
"""403
"""
pass
class HTTPNotFound(HTTPException):
"""404
"""
pass
class HTTPConflict(HTTPException):
"""409 - returned when creating conflicting resources
"""
pass
class HTTPTooManyRequests(HTTPException):
"""429 - returned when exceeding rate limits
"""
pass
class HTTPServerError(HTTPException):
"""Generic >= 500 error
"""
pass
python-fitbit-0.1.3/fitbit/utils.py 0000664 0000000 0000000 00000003436 12464570011 0017314 0 ustar 00root root 0000000 0000000 """
Curry was copied from Django's implementation.
License is reproduced here.
Copyright (c) Django Software Foundation and individual contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Django nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
def curry(_curried_func, *args, **kwargs):
def _curried(*moreargs, **morekwargs):
return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))
return _curried
python-fitbit-0.1.3/fitbit_tests/ 0000775 0000000 0000000 00000000000 12464570011 0017016 5 ustar 00root root 0000000 0000000 python-fitbit-0.1.3/fitbit_tests/__init__.py 0000664 0000000 0000000 00000001461 12464570011 0021131 0 ustar 00root root 0000000 0000000 import unittest
from .test_exceptions import ExceptionTest
from .test_auth import AuthTest
from .test_api import APITest, CollectionResourceTest, DeleteCollectionResourceTest, MiscTest
def all_tests(consumer_key="", consumer_secret="", user_key=None, user_secret=None):
kwargs = {
"consumer_key": consumer_key,
"consumer_secret": consumer_secret,
"user_key": user_key,
"user_secret": user_secret,
}
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(ExceptionTest))
suite.addTest(unittest.makeSuite(AuthTest))
suite.addTest(unittest.makeSuite(APITest))
suite.addTest(unittest.makeSuite(CollectionResourceTest))
suite.addTest(unittest.makeSuite(DeleteCollectionResourceTest))
suite.addTest(unittest.makeSuite(MiscTest))
return suite
python-fitbit-0.1.3/fitbit_tests/test_api.py 0000664 0000000 0000000 00000060706 12464570011 0021211 0 ustar 00root root 0000000 0000000 from unittest import TestCase
import datetime
import mock
from fitbit import Fitbit
from fitbit.exceptions import DeleteError
URLBASE = "%s/%s/user" % (Fitbit.API_ENDPOINT, Fitbit.API_VERSION)
class TestBase(TestCase):
def setUp(self):
self.fb = Fitbit('x', 'y')
def common_api_test(self, funcname, args, kwargs, expected_args, expected_kwargs):
# Create a fitbit object, call the named function on it with the given
# arguments and verify that make_request is called with the expected args and kwargs
with mock.patch.object(self.fb, 'make_request') as make_request:
retval = getattr(self.fb, funcname)(*args, **kwargs)
args, kwargs = make_request.call_args
self.assertEqual(expected_args, args)
self.assertEqual(expected_kwargs, kwargs)
def verify_raises(self, funcname, args, kwargs, exc):
self.assertRaises(exc, getattr(self.fb, funcname), *args, **kwargs)
class APITest(TestBase):
"""Tests for python-fitbit API, not directly involved in getting authenticated"""
def test_make_request(self):
# If make_request returns a response with status 200,
# we get back the json decoded value that was in the response.content
ARGS = (1, 2)
KWARGS = { 'a': 3, 'b': 4, 'headers': {'Accept-Language': self.fb.SYSTEM}}
mock_response = mock.Mock()
mock_response.status_code = 200
mock_response.content = b"1"
with mock.patch.object(self.fb.client, 'make_request') as client_make_request:
client_make_request.return_value = mock_response
retval = self.fb.make_request(*ARGS, **KWARGS)
self.assertEqual(1, client_make_request.call_count)
self.assertEqual(1, retval)
args, kwargs = client_make_request.call_args
self.assertEqual(ARGS, args)
self.assertEqual(KWARGS, kwargs)
def test_make_request_202(self):
# If make_request returns a response with status 202,
# we get back True
mock_response = mock.Mock()
mock_response.status_code = 202
mock_response.content = "1"
ARGS = (1, 2)
KWARGS = { 'a': 3, 'b': 4, 'Accept-Language': self.fb.SYSTEM}
with mock.patch.object(self.fb.client, 'make_request') as client_make_request:
client_make_request.return_value = mock_response
retval = self.fb.make_request(*ARGS, **KWARGS)
self.assertEqual(True, retval)
def test_make_request_delete_204(self):
# If make_request returns a response with status 204,
# and the method is DELETE, we get back True
mock_response = mock.Mock()
mock_response.status_code = 204
mock_response.content = "1"
ARGS = (1, 2)
KWARGS = { 'a': 3, 'b': 4, 'method': 'DELETE', 'Accept-Language': self.fb.SYSTEM}
with mock.patch.object(self.fb.client, 'make_request') as client_make_request:
client_make_request.return_value = mock_response
retval = self.fb.make_request(*ARGS, **KWARGS)
self.assertEqual(True, retval)
def test_make_request_delete_not_204(self):
# If make_request returns a response with status not 204,
# and the method is DELETE, DeleteError is raised
mock_response = mock.Mock()
mock_response.status_code = 205
mock_response.content = "1"
ARGS = (1, 2)
KWARGS = { 'a': 3, 'b': 4, 'method': 'DELETE', 'Accept-Language': self.fb.SYSTEM}
with mock.patch.object(self.fb.client, 'make_request') as client_make_request:
client_make_request.return_value = mock_response
self.assertRaises(DeleteError, self.fb.make_request, *ARGS, **KWARGS)
def test_user_profile_get(self):
user_id = "FOO"
url = URLBASE + "/%s/profile.json" % user_id
self.common_api_test('user_profile_get', (user_id,), {}, (url,), {})
def test_user_profile_update(self):
data = "BAR"
url = URLBASE + "/-/profile.json"
self.common_api_test('user_profile_update', (data,), {}, (url, data), {})
class CollectionResourceTest(TestBase):
"""Tests for _COLLECTION_RESOURCE"""
def test_all_args(self):
# If we pass all the optional args, the right things happen
resource = "RESOURCE"
date = datetime.date(1962, 1, 13)
user_id = "bilbo"
data = { 'a': 1, 'b': 2}
expected_data = data.copy()
expected_data['date'] = date.strftime("%Y-%m-%d")
url = URLBASE + "/%s/%s.json" % (user_id, resource)
self.common_api_test('_COLLECTION_RESOURCE', (resource, date, user_id, data), {}, (url, expected_data), {})
def test_date_string(self):
# date can be a "yyyy-mm-dd" string
resource = "RESOURCE"
date = "1962-1-13"
user_id = "bilbo"
data = { 'a': 1, 'b': 2}
expected_data = data.copy()
expected_data['date'] = date
url = URLBASE + "/%s/%s.json" % (user_id, resource)
self.common_api_test('_COLLECTION_RESOURCE',(resource, date, user_id, data), {}, (url, expected_data), {} )
def test_no_date(self):
# If we omit the date, it uses today
resource = "RESOURCE"
user_id = "bilbo"
data = { 'a': 1, 'b': 2}
expected_data = data.copy()
expected_data['date'] = datetime.date.today().strftime("%Y-%m-%d") # expect today
url = URLBASE + "/%s/%s.json" % (user_id, resource)
self.common_api_test('_COLLECTION_RESOURCE', (resource, None, user_id, data), {}, (url, expected_data), {})
def test_no_userid(self):
# If we omit the user_id, it uses "-"
resource = "RESOURCE"
date = datetime.date(1962, 1, 13)
user_id = None
data = { 'a': 1, 'b': 2}
expected_data = data.copy()
expected_data['date'] = date.strftime("%Y-%m-%d")
expected_user_id = "-"
url = URLBASE + "/%s/%s.json" % (expected_user_id, resource)
self.common_api_test('_COLLECTION_RESOURCE', (resource, date, user_id, data), {}, (url,expected_data), {})
def test_no_data(self):
# If we omit the data arg, it does the right thing
resource = "RESOURCE"
date = datetime.date(1962, 1, 13)
user_id = "bilbo"
data = None
url = URLBASE + "/%s/%s/date/%s.json" % (user_id, resource, date)
self.common_api_test('_COLLECTION_RESOURCE', (resource,date,user_id,data), {}, (url,data), {})
def test_body(self):
# Test the first method defined in __init__ to see if it calls
# _COLLECTION_RESOURCE okay - if it does, they should all since
# they're all built the same way
# We need to mock _COLLECTION_RESOURCE before we create the Fitbit object,
# since the __init__ is going to set up references to it
with mock.patch('fitbit.api.Fitbit._COLLECTION_RESOURCE') as coll_resource:
coll_resource.return_value = 999
fb = Fitbit('x', 'y')
retval = fb.body(date=1, user_id=2, data=3)
args, kwargs = coll_resource.call_args
self.assertEqual(('body',), args)
self.assertEqual({'date': 1, 'user_id': 2, 'data': 3}, kwargs)
self.assertEqual(999, retval)
class DeleteCollectionResourceTest(TestBase):
"""Tests for _DELETE_COLLECTION_RESOURCE"""
def test_impl(self):
# _DELETE_COLLECTION_RESOURCE calls make_request with the right args
resource = "RESOURCE"
log_id = "Foo"
url = URLBASE + "/-/%s/%s.json" % (resource,log_id)
self.common_api_test('_DELETE_COLLECTION_RESOURCE', (resource, log_id), {},
(url,), {"method": "DELETE"})
def test_cant_delete_body(self):
self.assertFalse(hasattr(self.fb, 'delete_body'))
def test_delete_water(self):
log_id = "OmarKhayyam"
# We need to mock _DELETE_COLLECTION_RESOURCE before we create the Fitbit object,
# since the __init__ is going to set up references to it
with mock.patch('fitbit.api.Fitbit._DELETE_COLLECTION_RESOURCE') as delete_resource:
delete_resource.return_value = 999
fb = Fitbit('x', 'y')
retval = fb.delete_water(log_id=log_id)
args, kwargs = delete_resource.call_args
self.assertEqual(('water',), args)
self.assertEqual({'log_id': log_id}, kwargs)
self.assertEqual(999, retval)
class MiscTest(TestBase):
def test_activities(self):
user_id = "Qui-Gon Jinn"
self.common_api_test('activities', (), {}, (URLBASE + "/%s/activities/date/%s.json" % (user_id, datetime.date.today().strftime('%Y-%m-%d'),),), {})
self.common_api_test('activities', (), {}, (URLBASE + "/-/activities/date/%s.json" % datetime.date.today().strftime('%Y-%m-%d'),), {})
def test_recent_activities(self):
user_id = "LukeSkywalker"
with mock.patch('fitbit.api.Fitbit.activity_stats') as act_stats:
fb = Fitbit('x', 'y')
retval = fb.recent_activities(user_id=user_id)
args, kwargs = act_stats.call_args
self.assertEqual((), args)
self.assertEqual({'user_id': user_id, 'qualifier': 'recent'}, kwargs)
def test_activity_stats(self):
user_id = "O B 1 Kenobi"
qualifier = "frequent"
url = URLBASE + "/%s/activities/%s.json" % (user_id, qualifier)
self.common_api_test('activity_stats', (), dict(user_id=user_id, qualifier=qualifier), (url,), {})
def test_activity_stats_no_qualifier(self):
user_id = "O B 1 Kenobi"
qualifier = None
self.common_api_test('activity_stats', (), dict(user_id=user_id, qualifier=qualifier), (URLBASE + "/%s/activities.json" % user_id,), {})
def test_timeseries(self):
resource = 'FOO'
user_id = 'BAR'
base_date = '1992-05-12'
period = '1d'
end_date = '1998-12-31'
# Not allowed to specify both period and end date
self.assertRaises(
TypeError,
self.fb.time_series,
resource,
user_id,
base_date,
period,
end_date)
# Period must be valid
self.assertRaises(
ValueError,
self.fb.time_series,
resource,
user_id,
base_date,
period="xyz",
end_date=None)
def test_timeseries(fb, resource, user_id, base_date, period, end_date, expected_url):
with mock.patch.object(fb, 'make_request') as make_request:
retval = fb.time_series(resource, user_id, base_date, period, end_date)
args, kwargs = make_request.call_args
self.assertEqual((expected_url,), args)
# User_id defaults = "-"
test_timeseries(self.fb, resource, user_id=None, base_date=base_date, period=period, end_date=None,
expected_url=URLBASE + "/-/FOO/date/1992-05-12/1d.json")
# end_date can be a date object
test_timeseries(self.fb, resource, user_id=user_id, base_date=base_date, period=None, end_date=datetime.date(1998, 12, 31),
expected_url=URLBASE + "/BAR/FOO/date/1992-05-12/1998-12-31.json")
# base_date can be a date object
test_timeseries(self.fb, resource, user_id=user_id, base_date=datetime.date(1992,5,12), period=None, end_date=end_date,
expected_url=URLBASE + "/BAR/FOO/date/1992-05-12/1998-12-31.json")
def test_intraday_timeseries(self):
resource = 'FOO'
base_date = '1918-05-11'
# detail_level must be valid
self.assertRaises(
ValueError,
self.fb.intraday_time_series,
resource,
base_date,
detail_level="xyz",
start_time=None,
end_time=None)
# provide end_time if start_time provided
self.assertRaises(
TypeError,
self.fb.intraday_time_series,
resource,
base_date,
detail_level="1min",
start_time='12:55',
end_time=None)
# provide start_time if end_time provided
self.assertRaises(
TypeError,
self.fb.intraday_time_series,
resource,
base_date,
detail_level="1min",
start_time=None,
end_time='12:55')
def test_intraday_timeseries(fb, resource, base_date, detail_level, start_time, end_time, expected_url):
with mock.patch.object(fb, 'make_request') as make_request:
retval = fb.intraday_time_series(resource, base_date, detail_level, start_time, end_time)
args, kwargs = make_request.call_args
self.assertEqual((expected_url,), args)
# Default
test_intraday_timeseries(self.fb, resource, base_date=base_date,
detail_level='1min', start_time=None, end_time=None,
expected_url=URLBASE + "/-/FOO/date/1918-05-11/1d/1min.json")
# start_date can be a date object
test_intraday_timeseries(self.fb, resource, base_date=datetime.date(1918, 5, 11),
detail_level='1min', start_time=None, end_time=None,
expected_url=URLBASE + "/-/FOO/date/1918-05-11/1d/1min.json")
# start_time can be a datetime object
test_intraday_timeseries(self.fb, resource, base_date=base_date,
detail_level='1min', start_time=datetime.time(3,56), end_time='15:07',
expected_url=URLBASE + "/-/FOO/date/1918-05-11/1d/1min/time/03:56/15:07.json")
# end_time can be a datetime object
test_intraday_timeseries(self.fb, resource, base_date=base_date,
detail_level='1min', start_time='3:56', end_time=datetime.time(15,7),
expected_url=URLBASE + "/-/FOO/date/1918-05-11/1d/1min/time/3:56/15:07.json")
def test_foods(self):
today = datetime.date.today().strftime('%Y-%m-%d')
self.common_api_test('recent_foods', ("USER_ID",), {}, (URLBASE+"/USER_ID/foods/log/recent.json",), {})
self.common_api_test('favorite_foods', ("USER_ID",), {}, (URLBASE+"/USER_ID/foods/log/favorite.json",), {})
self.common_api_test('frequent_foods', ("USER_ID",), {}, (URLBASE+"/USER_ID/foods/log/frequent.json",), {})
self.common_api_test('foods_log', (today, "USER_ID",), {}, ("%s/USER_ID/foods/log/date/%s.json" % (URLBASE, today), None), {})
self.common_api_test('recent_foods', (), {}, (URLBASE+"/-/foods/log/recent.json",), {})
self.common_api_test('favorite_foods', (), {}, (URLBASE+"/-/foods/log/favorite.json",), {})
self.common_api_test('frequent_foods', (), {}, (URLBASE+"/-/foods/log/frequent.json",), {})
self.common_api_test('foods_log', (today,), {}, ("%s/-/foods/log/date/%s.json" % (URLBASE, today), None), {})
url = URLBASE + "/-/foods/log/favorite/food_id.json"
self.common_api_test('add_favorite_food', ('food_id',), {}, (url,), {'method': 'POST'})
self.common_api_test('delete_favorite_food', ('food_id',), {}, (url,), {'method': 'DELETE'})
url = URLBASE + "/-/foods.json"
self.common_api_test('create_food', (), {'data': 'FOO'}, (url,), {'data': 'FOO'})
url = URLBASE + "/-/meals.json"
self.common_api_test('get_meals', (), {}, (url,), {})
url = "%s/%s/foods/search.json?query=FOOBAR" % (Fitbit.API_ENDPOINT, Fitbit.API_VERSION)
self.common_api_test('search_foods', ("FOOBAR",), {}, (url,), {})
url = "%s/%s/foods/FOOBAR.json" % (Fitbit.API_ENDPOINT, Fitbit.API_VERSION)
self.common_api_test('food_detail', ("FOOBAR",), {}, (url,), {})
url = "%s/%s/foods/units.json" % (Fitbit.API_ENDPOINT, Fitbit.API_VERSION)
self.common_api_test('food_units', (), {}, (url,), {})
def test_devices(self):
url = URLBASE + "/-/devices.json"
self.common_api_test('get_devices', (), {}, (url,), {})
def test_badges(self):
url = URLBASE + "/-/badges.json"
self.common_api_test('get_badges', (), {}, (url,), {})
def test_activities(self):
url = "%s/%s/activities.json" % (Fitbit.API_ENDPOINT, Fitbit.API_VERSION)
self.common_api_test('activities_list', (), {}, (url,), {})
url = "%s/%s/user/-/activities.json" % (Fitbit.API_ENDPOINT, Fitbit.API_VERSION)
self.common_api_test('log_activity', (), {'data' : 'FOO'}, (url,), {'data' : 'FOO'} )
url = "%s/%s/activities/FOOBAR.json" % (Fitbit.API_ENDPOINT, Fitbit.API_VERSION)
self.common_api_test('activity_detail', ("FOOBAR",), {}, (url,), {})
def test_bodyweight(self):
def test_get_bodyweight(fb, base_date=None, user_id=None, period=None, end_date=None, expected_url=None):
with mock.patch.object(fb, 'make_request') as make_request:
fb.get_bodyweight(base_date, user_id=user_id, period=period, end_date=end_date)
args, kwargs = make_request.call_args
self.assertEqual((expected_url,), args)
user_id = 'BAR'
# No end_date or period
test_get_bodyweight(self.fb, base_date=datetime.date(1992, 5, 12), user_id=None, period=None, end_date=None,
expected_url=URLBASE + "/-/body/log/weight/date/1992-05-12.json")
# With end_date
test_get_bodyweight(self.fb, base_date=datetime.date(1992, 5, 12), user_id=user_id, period=None, end_date=datetime.date(1998, 12, 31),
expected_url=URLBASE + "/BAR/body/log/weight/date/1992-05-12/1998-12-31.json")
# With period
test_get_bodyweight(self.fb, base_date=datetime.date(1992, 5, 12), user_id=user_id, period="1d", end_date=None,
expected_url=URLBASE + "/BAR/body/log/weight/date/1992-05-12/1d.json")
# Date defaults to today
test_get_bodyweight(self.fb, base_date=None, user_id=None, period=None, end_date=None,
expected_url=URLBASE + "/-/body/log/weight/date/%s.json" % datetime.date.today().strftime('%Y-%m-%d'))
def test_bodyfat(self):
def test_get_bodyfat(fb, base_date=None, user_id=None, period=None, end_date=None, expected_url=None):
with mock.patch.object(fb, 'make_request') as make_request:
fb.get_bodyfat(base_date, user_id=user_id, period=period, end_date=end_date)
args, kwargs = make_request.call_args
self.assertEqual((expected_url,), args)
user_id = 'BAR'
# No end_date or period
test_get_bodyfat(self.fb, base_date=datetime.date(1992, 5, 12), user_id=None, period=None, end_date=None,
expected_url=URLBASE + "/-/body/log/fat/date/1992-05-12.json")
# With end_date
test_get_bodyfat(self.fb, base_date=datetime.date(1992, 5, 12), user_id=user_id, period=None, end_date=datetime.date(1998, 12, 31),
expected_url=URLBASE + "/BAR/body/log/fat/date/1992-05-12/1998-12-31.json")
# With period
test_get_bodyfat(self.fb, base_date=datetime.date(1992, 5, 12), user_id=user_id, period="1d", end_date=None,
expected_url=URLBASE + "/BAR/body/log/fat/date/1992-05-12/1d.json")
# Date defaults to today
test_get_bodyfat(self.fb, base_date=None, user_id=None, period=None, end_date=None,
expected_url=URLBASE + "/-/body/log/fat/date/%s.json" % datetime.date.today().strftime('%Y-%m-%d'))
def test_friends(self):
url = URLBASE + "/-/friends.json"
self.common_api_test('get_friends', (), {}, (url,), {})
url = URLBASE + "/FOOBAR/friends.json"
self.common_api_test('get_friends', ("FOOBAR",), {}, (url,), {})
url = URLBASE + "/-/friends/leaders/7d.json"
self.common_api_test('get_friends_leaderboard', ("7d",), {}, (url,), {})
url = URLBASE + "/-/friends/leaders/30d.json"
self.common_api_test('get_friends_leaderboard', ("30d",), {}, (url,), {})
self.verify_raises('get_friends_leaderboard', ("xd",), {}, ValueError)
def test_invitations(self):
url = URLBASE + "/-/friends/invitations.json"
self.common_api_test('invite_friend', ("FOO",), {}, (url,), {'data': "FOO"})
self.common_api_test('invite_friend_by_email', ("foo@bar",), {}, (url,), {'data':{'invitedUserEmail': "foo@bar"}})
self.common_api_test('invite_friend_by_userid', ("foo@bar",), {}, (url,), {'data':{'invitedUserId': "foo@bar"}})
url = URLBASE + "/-/friends/invitations/FOO.json"
self.common_api_test('respond_to_invite', ("FOO", True), {}, (url,), {'data':{'accept': "true"}})
self.common_api_test('respond_to_invite', ("FOO", False), {}, (url,), {'data':{'accept': "false"}})
self.common_api_test('respond_to_invite', ("FOO", ), {}, (url,), {'data':{'accept': "true"}})
self.common_api_test('accept_invite', ("FOO",), {}, (url,), {'data':{'accept': "true"}})
self.common_api_test('reject_invite', ("FOO", ), {}, (url,), {'data':{'accept': "false"}})
def test_subscriptions(self):
url = URLBASE + "/-/apiSubscriptions.json"
self.common_api_test('list_subscriptions', (), {}, (url,), {})
url = URLBASE + "/-/FOO/apiSubscriptions.json"
self.common_api_test('list_subscriptions', ("FOO",), {}, (url,), {})
url = URLBASE + "/-/apiSubscriptions/SUBSCRIPTION_ID.json"
self.common_api_test('subscription', ("SUBSCRIPTION_ID", "SUBSCRIBER_ID"), {},
(url,), {'method': 'POST', 'headers': {'X-Fitbit-Subscriber-id': "SUBSCRIBER_ID"}})
self.common_api_test('subscription', ("SUBSCRIPTION_ID", "SUBSCRIBER_ID"), {'method': 'THROW'},
(url,), {'method': 'THROW', 'headers': {'X-Fitbit-Subscriber-id': "SUBSCRIBER_ID"}})
url = URLBASE + "/-/COLLECTION/apiSubscriptions/SUBSCRIPTION_ID-COLLECTION.json"
self.common_api_test('subscription', ("SUBSCRIPTION_ID", "SUBSCRIBER_ID"), {'method': 'THROW', 'collection': "COLLECTION"},
(url,), {'method': 'THROW', 'headers': {'X-Fitbit-Subscriber-id': "SUBSCRIBER_ID"}})
def test_alarms(self):
url = "%s/-/devices/tracker/%s/alarms.json" % (URLBASE, 'FOO')
self.common_api_test('get_alarms', (), {'device_id': 'FOO'}, (url,), {})
url = "%s/-/devices/tracker/%s/alarms/%s.json" % (URLBASE, 'FOO', 'BAR')
self.common_api_test('delete_alarm', (), {'device_id': 'FOO', 'alarm_id': 'BAR'}, (url,), {'method': 'DELETE'})
url = "%s/-/devices/tracker/%s/alarms.json" % (URLBASE, 'FOO')
self.common_api_test('add_alarm',
(),
{'device_id': 'FOO',
'alarm_time': datetime.datetime(year=2013, month=11, day=13, hour=8, minute=16),
'week_days': ['MONDAY']
},
(url,),
{'data':
{'enabled': True,
'recurring': False,
'time': datetime.datetime(year=2013, month=11, day=13, hour=8, minute=16).strftime("%H:%M%z"),
'vibe': 'DEFAULT',
'weekDays': ['MONDAY'],
},
'method': 'POST'
}
)
self.common_api_test('add_alarm',
(),
{'device_id': 'FOO',
'alarm_time': datetime.datetime(year=2013, month=11, day=13, hour=8, minute=16),
'week_days': ['MONDAY'], 'recurring': True, 'enabled': False, 'label': 'ugh',
'snooze_length': 5,
'snooze_count': 5
},
(url,),
{'data':
{'enabled': False,
'recurring': True,
'label': 'ugh',
'snoozeLength': 5,
'snoozeCount': 5,
'time': datetime.datetime(year=2013, month=11, day=13, hour=8, minute=16).strftime("%H:%M%z"),
'vibe': 'DEFAULT',
'weekDays': ['MONDAY'],
},
'method': 'POST'}
)
url = "%s/-/devices/tracker/%s/alarms/%s.json" % (URLBASE, 'FOO', 'BAR')
self.common_api_test('update_alarm',
(),
{'device_id': 'FOO',
'alarm_id': 'BAR',
'alarm_time': datetime.datetime(year=2013, month=11, day=13, hour=8, minute=16),
'week_days': ['MONDAY'], 'recurring': True, 'enabled': False, 'label': 'ugh',
'snooze_length': 5,
'snooze_count': 5
},
(url,),
{'data':
{'enabled': False,
'recurring': True,
'label': 'ugh',
'snoozeLength': 5,
'snoozeCount': 5,
'time': datetime.datetime(year=2013, month=11, day=13, hour=8, minute=16).strftime("%H:%M%z"),
'vibe': 'DEFAULT',
'weekDays': ['MONDAY'],
},
'method': 'POST'}
)
python-fitbit-0.1.3/fitbit_tests/test_auth.py 0000664 0000000 0000000 00000005505 12464570011 0021375 0 ustar 00root root 0000000 0000000 from unittest import TestCase
from fitbit import Fitbit, FitbitOauthClient
import mock
from requests_oauthlib import OAuth1Session
class AuthTest(TestCase):
"""Add tests for auth part of API
mock the oauth library calls to simulate various responses,
make sure we call the right oauth calls, respond correctly based on the responses
"""
client_kwargs = {
'client_key': '',
'client_secret': '',
'user_key': None,
'user_secret': None,
'callback_uri': 'CALLBACK_URL'
}
def test_fetch_request_token(self):
# fetch_request_token needs to make a request and then build a token from the response
fb = Fitbit(**self.client_kwargs)
with mock.patch.object(OAuth1Session, 'fetch_request_token') as frt:
frt.return_value = {
'oauth_callback_confirmed': 'true',
'oauth_token': 'FAKE_OAUTH_TOKEN',
'oauth_token_secret': 'FAKE_OAUTH_TOKEN_SECRET'}
retval = fb.client.fetch_request_token()
self.assertEqual(1, frt.call_count)
# Got the right return value
self.assertEqual('true', retval.get('oauth_callback_confirmed'))
self.assertEqual('FAKE_OAUTH_TOKEN', retval.get('oauth_token'))
self.assertEqual('FAKE_OAUTH_TOKEN_SECRET',
retval.get('oauth_token_secret'))
def test_authorize_token_url(self):
# authorize_token_url calls oauth and returns a URL
fb = Fitbit(**self.client_kwargs)
with mock.patch.object(OAuth1Session, 'authorization_url') as au:
au.return_value = 'FAKEURL'
retval = fb.client.authorize_token_url()
self.assertEqual(1, au.call_count)
self.assertEqual("FAKEURL", retval)
def test_authorize_token_url_with_parameters(self):
# authorize_token_url calls oauth and returns a URL
client = FitbitOauthClient(**self.client_kwargs)
retval = client.authorize_token_url(display="touch")
self.assertTrue("display=touch" in retval)
def test_fetch_access_token(self):
kwargs = self.client_kwargs
kwargs['resource_owner_key'] = ''
kwargs['resource_owner_secret'] = ''
fb = Fitbit(**kwargs)
fake_verifier = "FAKEVERIFIER"
with mock.patch.object(OAuth1Session, 'fetch_access_token') as fat:
fat.return_value = {
'encoded_user_id': 'FAKE_USER_ID',
'oauth_token': 'FAKE_RETURNED_KEY',
'oauth_token_secret': 'FAKE_RETURNED_SECRET'
}
retval = fb.client.fetch_access_token(fake_verifier)
self.assertEqual("FAKE_RETURNED_KEY", retval['oauth_token'])
self.assertEqual("FAKE_RETURNED_SECRET", retval['oauth_token_secret'])
self.assertEqual('FAKE_USER_ID', fb.client.user_id)
python-fitbit-0.1.3/fitbit_tests/test_exceptions.py 0000664 0000000 0000000 00000007076 12464570011 0022622 0 ustar 00root root 0000000 0000000 import unittest
import mock
import requests
import sys
from fitbit import Fitbit
from fitbit import exceptions
class ExceptionTest(unittest.TestCase):
"""
Tests that certain response codes raise certain exceptions
"""
client_kwargs = {
"client_key": "",
"client_secret": "",
"user_key": None,
"user_secret": None,
}
def test_response_ok(self):
"""
This mocks a pretty normal resource, that the request was authenticated,
and data was returned. This test should just run and not raise any
exceptions
"""
r = mock.Mock(spec=requests.Response)
r.status_code = 200
r.content = b'{"normal": "resource"}'
f = Fitbit(**self.client_kwargs)
f.client._request = lambda *args, **kwargs: r
f.user_profile_get()
r.status_code = 202
f.user_profile_get()
r.status_code = 204
f.user_profile_get()
def test_response_auth(self):
"""
This test checks how the client handles different auth responses, and
the exceptions raised by the client.
"""
r = mock.Mock(spec=requests.Response)
r.status_code = 401
r.content = b"{'normal': 'resource'}"
f = Fitbit(**self.client_kwargs)
f.client._request = lambda *args, **kwargs: r
self.assertRaises(exceptions.HTTPUnauthorized, f.user_profile_get)
r.status_code = 403
self.assertRaises(exceptions.HTTPForbidden, f.user_profile_get)
def test_response_error(self):
"""
Tests other HTTP errors
"""
r = mock.Mock(spec=requests.Response)
r.content = b"{'normal': 'resource'}"
f = Fitbit(**self.client_kwargs)
f.client._request = lambda *args, **kwargs: r
r.status_code = 404
self.assertRaises(exceptions.HTTPNotFound, f.user_profile_get)
r.status_code = 409
self.assertRaises(exceptions.HTTPConflict, f.user_profile_get)
r.status_code = 500
self.assertRaises(exceptions.HTTPServerError, f.user_profile_get)
r.status_code = 499
self.assertRaises(exceptions.HTTPBadRequest, f.user_profile_get)
def test_too_many_requests(self):
"""
Tests the 429 response, given in case of exceeding the rate limit
"""
r = mock.Mock(spec=requests.Response)
r.content = b"{'normal': 'resource'}"
r.headers = {'Retry-After': '10'}
f = Fitbit(**self.client_kwargs)
f.client._request = lambda *args, **kwargs: r
r.status_code = 429
try:
f.user_profile_get()
self.assertEqual(True, False) # Won't run if an exception's raised
except exceptions.HTTPTooManyRequests:
e = sys.exc_info()[1]
self.assertEqual(e.retry_after_secs, 10)
def test_serialization(self):
"""
Tests non-json data returned
"""
r = mock.Mock(spec=requests.Response)
r.status_code = 200
r.content = b"iyam not jason"
f = Fitbit(**self.client_kwargs)
f.client._request = lambda *args, **kwargs: r
self.assertRaises(exceptions.BadResponse, f.user_profile_get)
def test_delete_error(self):
"""
Delete requests should return 204
"""
r = mock.Mock(spec=requests.Response)
r.status_code = 201
r.content = b'{"it\'s all": "ok"}'
f = Fitbit(**self.client_kwargs)
f.client._request = lambda *args, **kwargs: r
self.assertRaises(exceptions.DeleteError, f.delete_activities, 12345)
python-fitbit-0.1.3/gather_keys_cli.py 0000775 0000000 0000000 00000005057 12464570011 0020033 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
"""
This was taken, and modified from python-oauth2/example/client.py,
License reproduced below.
--------------------------
The MIT License
Copyright (c) 2007 Leah Culver
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Example consumer. This is not recommended for production.
Instead, you'll want to create your own subclass of OAuthClient
or find one that works with your web framework.
"""
import os
import pprint
import sys
import webbrowser
from fitbit.api import FitbitOauthClient
def gather_keys():
# setup
pp = pprint.PrettyPrinter(indent=4)
print('** OAuth Python Library Example **\n')
client = FitbitOauthClient(CLIENT_KEY, CLIENT_SECRET)
# get request token
print('* Obtain a request token ...\n')
token = client.fetch_request_token()
print('RESPONSE')
pp.pprint(token)
print('')
print('* Authorize the request token in your browser\n')
stderr = os.dup(2)
os.close(2)
os.open(os.devnull, os.O_RDWR)
webbrowser.open(client.authorize_token_url())
os.dup2(stderr, 2)
try:
verifier = raw_input('Verifier: ')
except NameError:
# Python 3.x
verifier = input('Verifier: ')
# get access token
print('\n* Obtain an access token ...\n')
token = client.fetch_access_token(verifier)
print('RESPONSE')
pp.pprint(token)
print('')
if __name__ == '__main__':
if not (len(sys.argv) == 3):
print("Arguments 'client key', 'client secret' are required")
sys.exit(1)
CLIENT_KEY = sys.argv[1]
CLIENT_SECRET = sys.argv[2]
gather_keys()
print('Done.')
python-fitbit-0.1.3/requirements/ 0000775 0000000 0000000 00000000000 12464570011 0017036 5 ustar 00root root 0000000 0000000 python-fitbit-0.1.3/requirements/base.txt 0000664 0000000 0000000 00000000056 12464570011 0020512 0 ustar 00root root 0000000 0000000 python-dateutil>=1.5
requests-oauthlib>=0.4.0
python-fitbit-0.1.3/requirements/dev.txt 0000664 0000000 0000000 00000000062 12464570011 0020353 0 ustar 00root root 0000000 0000000 -r base.txt
-r test.txt
Sphinx==1.2.3
tox==1.8.1
python-fitbit-0.1.3/requirements/test.txt 0000664 0000000 0000000 00000000034 12464570011 0020553 0 ustar 00root root 0000000 0000000 mock==1.0.1
coverage==3.7.1
python-fitbit-0.1.3/setup.py 0000664 0000000 0000000 00000003046 12464570011 0016030 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
from setuptools import setup
required = [line for line in open('requirements/base.txt').read().split("\n")]
required_test = [line for line in open('requirements/test.txt').read().split("\n") if not line.startswith("-r")]
fbinit = open('fitbit/__init__.py').read()
author = re.search("__author__ = '([^']+)'", fbinit).group(1)
author_email = re.search("__author_email__ = '([^']+)'", fbinit).group(1)
version = re.search("__version__ = '([^']+)'", fbinit).group(1)
setup(
name='fitbit',
version=version,
description='Fitbit API Wrapper.',
long_description=open('README.rst').read(),
author=author,
author_email=author_email,
url='https://github.com/orcasgit/python-fitbit',
packages=['fitbit'],
package_data={'': ['LICENSE']},
include_package_data=True,
install_requires=["setuptools"] + required,
license='Apache 2.0',
test_suite='fitbit_tests.all_tests',
tests_require=required_test,
classifiers=(
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: PyPy'
),
)
python-fitbit-0.1.3/tox.ini 0000664 0000000 0000000 00000000577 12464570011 0015637 0 ustar 00root root 0000000 0000000 [tox]
envlist = pypy,py34,py33,py32,py27,py26
[testenv]
commands = coverage run --source=fitbit setup.py test
deps = -r{toxinidir}/requirements/test.txt
[testenv:pypy]
basepython = pypy
[testenv:py34]
basepython = python3.4
[testenv:py33]
basepython = python3.3
[testenv:py32]
basepython = python3.2
[testenv:py27]
basepython = python2.7
[testenv:py26]
basepython = python2.6