[med-svn] [python-fitbit] 01/13: Imported Upstream version 0.0.2
Iain Learmonth
irl-guest at moszumanska.debian.org
Mon Feb 3 21:25:53 UTC 2014
This is an automated email from the git hooks/post-receive script.
irl-guest pushed a commit to branch master
in repository python-fitbit.
commit 4d0d24bbb87c0baa7a56cf1a8b75ba7b28433615
Author: Iain R. Learmonth <irl at fsfe.org>
Date: Mon Feb 3 19:09:33 2014 +0000
Imported Upstream version 0.0.2
---
.gitignore | 7 +
.travis.yml | 7 +
AUTHORS | 4 +
LICENSE | 13 +
MANIFEST.in | 1 +
README.rst | 14 +
TODO | 6 +
docs/Makefile | 153 +++++++++
docs/conf.py | 242 ++++++++++++++
docs/index.rst | 48 +++
docs/make.bat | 190 +++++++++++
fitbit/__init__.py | 24 ++
fitbit/api.py | 683 ++++++++++++++++++++++++++++++++++++++++
fitbit/exceptions.py | 48 +++
fitbit/gather_keys_cli.py | 97 ++++++
fitbit/utils.py | 39 +++
fitbit_tests/__init__.py | 21 ++
fitbit_tests/base.py | 18 ++
fitbit_tests/test_api.py | 328 +++++++++++++++++++
fitbit_tests/test_auth.py | 88 ++++++
fitbit_tests/test_exceptions.py | 104 ++++++
requirements.txt | 4 +
requirements_dev.txt | 4 +
requirements_test.txt | 1 +
setup.py | 39 +++
25 files changed, 2183 insertions(+)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..bbc49fd
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,7 @@
+*.pyc
+*.DS_Store
+*~
+docs/_build
+*.egg-info
+*.egg
+dist
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..e8cd8a0
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,7 @@
+language: python
+
+python:
+ - 2.6
+ - 2.7
+
+script: python setup.py test
diff --git a/AUTHORS b/AUTHORS
new file mode 100644
index 0000000..93ff530
--- /dev/null
+++ b/AUTHORS
@@ -0,0 +1,4 @@
+Issac Kelly (Kelly Creative Tech)
+Percy Perez (ORCAS)
+Rebecca Lovewell (Caktus Consulting Group)
+Dan Poirier (Caktus Consulting Group)
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..2dab89d
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,13 @@
+Copyright 2012 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.
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000..44a59eb
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1 @@
+include LICENSE AUTHORS README.rst requirements* docs/*
diff --git a/README.rst b/README.rst
new file mode 100644
index 0000000..e2914b9
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,14 @@
+=============
+python-fitbit
+=============
+
+.. image:: https://travis-ci.org/orcasgit/python-fitbit.png?branch=master :target: https://travis-ci.org/orcasgit/python-fitbit
+
+Fitbit API Python Client Implementation
+
+For documentation: `http://python-fitbit.readthedocs.org/ <http://python-fitbit.readthedocs.org/>`_
+
+Requirements
+============
+
+* Python 2.6+
diff --git a/TODO b/TODO
new file mode 100644
index 0000000..cc97776
--- /dev/null
+++ b/TODO
@@ -0,0 +1,6 @@
+TODO
+
+* Public calls only based on consumer_key, (should work, untested)
+* Change Units
+* Docs
+* Tests
diff --git a/docs/Makefile b/docs/Makefile
new file mode 100644
index 0000000..d81ba7f
--- /dev/null
+++ b/docs/Makefile
@@ -0,0 +1,153 @@
+# 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 <target>' where <target> 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."
diff --git a/docs/conf.py b/docs/conf.py
new file mode 100644
index 0000000..4e73820
--- /dev/null
+++ b/docs/conf.py
@@ -0,0 +1,242 @@
+# -*- 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 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.0'
+# The full version, including alpha/beta/rc tags.
+release = '0.0.2'
+
+# 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
+# "<project> v<release> 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 <link> 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', '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'], 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', 'Python-Fitbit', 'One line description of project.',
+ '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'
diff --git a/docs/index.rst b/docs/index.rst
new file mode 100644
index 0000000..ff6e3ea
--- /dev/null
+++ b/docs/index.rst
@@ -0,0 +1,48 @@
+.. 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 oAuath for authentication, it supports both us and si
+measurements
+
+Quickstart
+==========
+
+Here is some example usage::
+
+ import fitbit
+ unauth_client = fitbit.Fitbit('<consumer_key>', '<consumer_secret>')
+ # 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 <con_key> <con_sec> for development
+ authd_client = fitbit.Fitbit('<consumer_key>', '<consumer_secret>', user_key='<user_key>', user_secret='<user_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`
+
diff --git a/docs/make.bat b/docs/make.bat
new file mode 100644
index 0000000..a90538b
--- /dev/null
+++ b/docs/make.bat
@@ -0,0 +1,190 @@
+ at 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 ^<target^>` where ^<target^> 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
diff --git a/fitbit/__init__.py b/fitbit/__init__.py
new file mode 100644
index 0000000..f4a23d7
--- /dev/null
+++ b/fitbit/__init__.py
@@ -0,0 +1,24 @@
+# -*- coding: utf-8 -*-
+"""
+Fitbit API Library
+------------------
+
+:copyright: 2012 ORCAS.
+:license: BSD, see LICENSE for more details.
+"""
+
+from .api import Fitbit, FitbitConsumer, FitbitOauthClient
+
+# Meta.
+
+__title__ = 'fitbit'
+__author__ = 'Issac Kelly and ORCAS'
+__author_email__ = 'pperez at orcasinc.com'
+__copyright__ = 'Copyright 2012 ORCAS'
+__license__ = 'Apache 2.0'
+
+__version__ = '0.0.2'
+
+# Module namespace.
+
+all_tests = []
\ No newline at end of file
diff --git a/fitbit/api.py b/fitbit/api.py
new file mode 100644
index 0000000..7516476
--- /dev/null
+++ b/fitbit/api.py
@@ -0,0 +1,683 @@
+# -*- coding: utf-8 -*-
+import oauth2 as oauth
+import requests
+import json
+import datetime
+import urllib
+
+from requests_oauthlib import OAuth1Session
+from fitbit.exceptions import (BadResponse, DeleteError, HTTPBadRequest,
+ HTTPUnauthorized, HTTPForbidden,
+ HTTPServerError, HTTPConflict, HTTPNotFound)
+from fitbit.utils import curry
+
+
+class FitbitConsumer(oauth.Consumer):
+ pass
+
+
+# example client using httplib with headers
+class FitbitOauthClient(oauth.Client):
+ API_ENDPOINT = "https://api.fitbit.com"
+ AUTHORIZE_ENDPOINT = "https://www.fitbit.com"
+ API_VERSION = 1
+ _signature_method = oauth.SignatureMethod_HMAC_SHA1()
+
+ 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, consumer_key, consumer_secret, user_key=None,
+ user_secret=None, user_id=None, *args, **kwargs):
+ if user_key and user_secret:
+ self._token = oauth.Token(user_key, user_secret)
+ else:
+ # This allows public calls to be made
+ self._token = None
+ if user_id:
+ self.user_id = user_id
+ self._consumer = FitbitConsumer(consumer_key, consumer_secret)
+ super(FitbitOauthClient, self).__init__(self._consumer, *args, **kwargs)
+
+ def _request(self, method, url, **kwargs):
+ """
+ A simple wrapper around requests.
+ """
+ return requests.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'
+ request = oauth.Request.from_consumer_and_token(self._consumer, self._token, http_method=method, http_url=url, parameters=data)
+ request.sign_request(self._signature_method, self._consumer,
+ self._token)
+ response = self._request(method, url, data=data,
+ headers=request.to_header())
+
+ 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 >= 500:
+ raise HTTPServerError(response)
+ elif response.status_code >= 400:
+ raise HTTPBadRequest(response)
+ return response
+
+ def fetch_request_token(self, parameters=None):
+ """
+ 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 the next
+ step. Returns that token.
+
+ Set parameters['oauth_callback'] 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.
+ """
+
+ """
+ via headers
+ -> OAuthToken
+
+ Providing 'oauth_callback' parameter in the Authorization header of
+ request_token_url request, will have priority over the dev.fitbit.com
+ settings, ie. parameters = {'oauth_callback': 'callback_url'}
+ """
+
+ request = oauth.Request.from_consumer_and_token(
+ self._consumer,
+ http_url=self.request_token_url,
+ parameters=parameters
+ )
+ request.sign_request(self._signature_method, self._consumer, None)
+ response = self._request(request.method, self.request_token_url,
+ headers=request.to_header())
+ return oauth.Token.from_string(response.content)
+
+ def authorize_token_url(self, token):
+ """Step 2: Given the token returned by fetch_request_token(), 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.
+ """
+ request = oauth.Request.from_token_and_callback(
+ token=token,
+ http_url=self.authorization_url
+ )
+ return request.to_url()
+
+ #def authorize_token(self, token):
+ # # via url
+ # # -> typically just some okay response
+ # request = oauth.Request.from_token_and_callback(token=token,
+ # http_url=self.authorization_url)
+ # response = self._request(request.method, request.to_url(),
+ # headers=request.to_header())
+ # return response.content
+
+ def fetch_access_token(self, token, verifier):
+ """Step 4: Given the token from step 1, and the verifier from step 3 (see step 2),
+ calls fitbit again and returns an access token object. Extract .key and .secret
+ from that and save them, then pass them as user_key and user_secret in future
+ API calls to fitbit to get this user's data.
+ """
+ client = OAuth1Session(
+ self._consumer.key,
+ client_secret=self._consumer.secret,
+ resource_owner_key=token.key,
+ resource_owner_secret=token.secret,
+ verifier=verifier)
+ response = client.fetch_access_token(self.access_token_url)
+
+ self.user_id = response['encoded_user_id']
+ self._token = oauth.Token(
+ key=response['oauth_token'],
+ secret=response['oauth_token_secret'])
+ return self._token
+
+
+class Fitbit(object):
+ US = 'en_US'
+ METRIC = 'en_UK'
+
+ API_ENDPOINT = "https://api.fitbit.com"
+ API_VERSION = 1
+
+ _resource_list = [
+ 'body',
+ 'activities',
+ 'foods',
+ 'water',
+ 'sleep',
+ 'heart',
+ 'bp',
+ 'glucose',
+ ]
+
+ _qualifiers = [
+ 'recent',
+ 'favorite',
+ 'frequent',
+ ]
+
+ def __init__(self, consumer_key, consumer_secret, system=US, **kwargs):
+ self.client = FitbitOauthClient(consumer_key, consumer_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, 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)
+ 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': <dict of user data>}
+
+ 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': <dict of user data>}
+
+ 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(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, basestring):
+ 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, basestring):
+ 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, basestring):
+ 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 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 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 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,
+ urllib.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_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, consumer_key, consumer_secret, user_key=None,
+ user_secret=None, user_id=None, system=US):
+ client = FitbitOauthClient(consumer_key, consumer_secret, user_key,
+ user_secret, user_id)
+ return self(client, system)
diff --git a/fitbit/exceptions.py b/fitbit/exceptions.py
new file mode 100644
index 0000000..33ccc20
--- /dev/null
+++ b/fitbit/exceptions.py
@@ -0,0 +1,48 @@
+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)['errors']
+ message = '\n'.join([error['message'] for error in errors])
+ except Exception:
+ message = response
+ super(HTTPException, self).__init__(message, *args, **kwargs)
+
+class HTTPBadRequest(HTTPException):
+ pass
+
+
+class HTTPUnauthorized(HTTPException):
+ pass
+
+
+class HTTPForbidden(HTTPException):
+ pass
+
+
+class HTTPServerError(HTTPException):
+ pass
+
+
+class HTTPConflict(HTTPException):
+ """
+ Used by Fitbit as rate limiter
+ """
+ pass
+
+
+class HTTPNotFound(HTTPException):
+ pass
diff --git a/fitbit/gather_keys_cli.py b/fitbit/gather_keys_cli.py
new file mode 100755
index 0000000..a11c2fb
--- /dev/null
+++ b/fitbit/gather_keys_cli.py
@@ -0,0 +1,97 @@
+#!/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.
+"""
+
+from api import FitbitOauthClient
+import time
+import oauth2 as oauth
+import urlparse
+import platform
+import subprocess
+
+
+
+def gather_keys():
+ # setup
+ print '** OAuth Python Library Example **'
+ client = FitbitOauthClient(CONSUMER_KEY, CONSUMER_SECRET)
+
+ print ''
+
+ # get request token
+ print '* Obtain a request token ...'
+ print ''
+ token = client.fetch_request_token()
+ print 'FROM RESPONSE'
+ print 'key: %s' % str(token.key)
+ print 'secret: %s' % str(token.secret)
+ print 'callback confirmed? %s' % str(token.callback_confirmed)
+ print ''
+
+ print '* Authorize the request token in your browser'
+ print ''
+ if platform.mac_ver():
+ subprocess.Popen(['open', client.authorize_token_url(token)])
+ else:
+ print 'open: %s' % client.authorize_token_url(token)
+ print ''
+ verifier = raw_input('Verifier: ')
+ print verifier
+ print ''
+
+ # get access token
+ print '* Obtain an access token ...'
+ print ''
+ print 'REQUEST (via headers)'
+ print ''
+ token = client.fetch_access_token(token, verifier)
+ print 'FROM RESPONSE'
+ print 'key: %s' % str(token.key)
+ print 'secret: %s' % str(token.secret)
+ print ''
+
+
+def pause():
+ print ''
+ time.sleep(1)
+
+if __name__ == '__main__':
+ import sys
+
+ if not (len(sys.argv) == 3):
+ print "Arguments 'client key', 'client secret' are required"
+ sys.exit(1)
+ CONSUMER_KEY = sys.argv[1]
+ CONSUMER_SECRET = sys.argv[2]
+
+ gather_keys()
+ print 'Done.'
diff --git a/fitbit/utils.py b/fitbit/utils.py
new file mode 100644
index 0000000..07eb04e
--- /dev/null
+++ b/fitbit/utils.py
@@ -0,0 +1,39 @@
+"""
+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
diff --git a/fitbit_tests/__init__.py b/fitbit_tests/__init__.py
new file mode 100644
index 0000000..06457ff
--- /dev/null
+++ b/fitbit_tests/__init__.py
@@ -0,0 +1,21 @@
+import unittest
+from test_exceptions import ExceptionTest
+from test_auth import AuthTest
+from fitbit_tests.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
diff --git a/fitbit_tests/base.py b/fitbit_tests/base.py
new file mode 100644
index 0000000..9bb7866
--- /dev/null
+++ b/fitbit_tests/base.py
@@ -0,0 +1,18 @@
+import unittest
+
+class APITestCase(unittest.TestCase):
+
+
+ def __init__(self, consumer_key="", consumer_secret="", client_key=None, client_secret=None, *args, **kwargs):
+ self.consumer_key = consumer_key
+ self.consumer_secret = consumer_secret
+ self.client_key = client_key
+ self.client_secret = client_secret
+
+ self.client_kwargs = {
+ "consumer_key": consumer_key,
+ "consumer_secret": consumer_secret,
+ "client_key": client_key,
+ "client_secret": client_secret,
+ }
+ super(APITestCase, self).__init__(*args, **kwargs)
diff --git a/fitbit_tests/test_api.py b/fitbit_tests/test_api.py
new file mode 100644
index 0000000..0a0c696
--- /dev/null
+++ b/fitbit_tests/test_api.py
@@ -0,0 +1,328 @@
+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(consumer_key='x', consumer_secret='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 = "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(consumer_key='x', consumer_secret='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(consumer_key='x', consumer_secret='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_recent_activities(self):
+ user_id = "LukeSkywalker"
+ with mock.patch('fitbit.api.Fitbit.activity_stats') as act_stats:
+ fb = Fitbit(consumer_key='x', consumer_secret='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_foods(self):
+ 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('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",), {})
+
+ 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/activities/FOOBAR.json" % (Fitbit.API_ENDPOINT, Fitbit.API_VERSION)
+ self.common_api_test('activity_detail', ("FOOBAR",), {}, (url,), {})
+
+ 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 at bar",), {}, (url,), {'data':{'invitedUserEmail': "foo at bar"}})
+ self.common_api_test('invite_friend_by_userid', ("foo at bar",), {}, (url,), {'data':{'invitedUserId': "foo at 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"}})
diff --git a/fitbit_tests/test_auth.py b/fitbit_tests/test_auth.py
new file mode 100644
index 0000000..ea8a0ea
--- /dev/null
+++ b/fitbit_tests/test_auth.py
@@ -0,0 +1,88 @@
+from unittest import TestCase
+from fitbit import Fitbit
+import mock
+import oauth2 as oauth
+
+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 = {
+ "consumer_key": "",
+ "consumer_secret": "",
+ "user_key": None,
+ "user_secret": None,
+ }
+
+ 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)
+ callback_url = "CALLBACK_URL"
+ parameters = {'oauth_callback': callback_url}
+ with mock.patch.object(oauth.Request, 'from_consumer_and_token') as from_consumer_and_token:
+ mock_request = mock.Mock()
+ mock_request.to_header.return_value = "MOCKHEADERS"
+ mock_request.method = 'GET'
+ from_consumer_and_token.return_value = mock_request
+ with mock.patch('fitbit.api.FitbitOauthClient._request') as _request:
+ fake_response = mock.Mock()
+ fake_response.content = "FAKECONTENT"
+ fake_response.status_code = 200
+ _request.return_value = fake_response
+ with mock.patch.object(oauth.Token, 'from_string') as from_string:
+ from_string.return_value = "FAKERETURNVALUE"
+
+ retval = fb.client.fetch_request_token(parameters)
+ # Got the right return value
+ self.assertEqual("FAKERETURNVALUE", retval)
+ # The right parms were passed along the way to getting there
+ self.assertEqual(1, from_consumer_and_token.call_count)
+ self.assertEqual((fb.client._consumer,), from_consumer_and_token.call_args[0])
+ self.assertEqual({'http_url': fb.client.request_token_url, 'parameters': parameters}, from_consumer_and_token.call_args[1])
+ self.assertEqual(1, mock_request.sign_request.call_count)
+ self.assertEqual((fb.client._signature_method, fb.client._consumer, None), mock_request.sign_request.call_args[0])
+ self.assertEqual(1, _request.call_count)
+ self.assertEqual((mock_request.method,fb.client.request_token_url), _request.call_args[0])
+ self.assertEqual({'headers': "MOCKHEADERS"}, _request.call_args[1])
+ self.assertEqual(1, from_string.call_count)
+ self.assertEqual(("FAKECONTENT",), from_string.call_args[0])
+
+ def test_authorize_token_url(self):
+ # authorize_token_url calls oauth and returns a URL
+ fb = Fitbit(**self.client_kwargs)
+ fake_token = "FAKETOKEN"
+ with mock.patch.object(oauth.Request, "from_token_and_callback") as from_token_and_callback:
+ mock_request = mock.Mock()
+ mock_request.to_url.return_value = "FAKEURL"
+ from_token_and_callback.return_value = mock_request
+ retval = fb.client.authorize_token_url(fake_token)
+ self.assertEqual("FAKEURL", retval)
+ self.assertEqual(1, from_token_and_callback.call_count)
+ kwargs = from_token_and_callback.call_args_list[0][1]
+ self.assertEqual({'token': fake_token, 'http_url': fb.client.authorization_url}, kwargs)
+
+ def test_fetch_access_token(self):
+ fb = Fitbit(**self.client_kwargs)
+ fake_token = mock.Mock(key="FAKEKEY", secret="FAKESECRET")
+ fake_verifier = "FAKEVERIFIER"
+ with mock.patch('requests_oauthlib.OAuth1Session.fetch_access_token') as fetch_access_token:
+ fetch_access_token.return_value = {
+ 'encoded_user_id': 'FAKEUSERID',
+ 'oauth_token': 'FAKERETURNEDKEY',
+ 'oauth_token_secret': 'FAKERETURNEDSECRET'
+ }
+ retval = fb.client.fetch_access_token(fake_token, fake_verifier)
+ self.assertEqual("FAKERETURNEDKEY", retval.key)
+ self.assertEqual("FAKERETURNEDSECRET", retval.secret)
+ self.assertEqual('FAKEUSERID', fb.client.user_id)
+
+ def test_fetch_access_token_error(self):
+ fb = Fitbit(**self.client_kwargs)
+ with mock.patch('requests.sessions.Session.post') as post:
+ post.return_value = mock.Mock(text="not a url encoded string")
+ fake_token = mock.Mock(key="FAKEKEY", secret="FAKESECRET")
+ self.assertRaises(ValueError,
+ fb.client.fetch_access_token,
+ fake_token, "fake_verifier")
diff --git a/fitbit_tests/test_exceptions.py b/fitbit_tests/test_exceptions.py
new file mode 100644
index 0000000..98eba79
--- /dev/null
+++ b/fitbit_tests/test_exceptions.py
@@ -0,0 +1,104 @@
+import unittest
+import mock
+import requests
+from fitbit import Fitbit
+from fitbit import exceptions
+
+class ExceptionTest(unittest.TestCase):
+ """
+ Tests that certain response codes raise certain exceptions
+ """
+ client_kwargs = {
+ "consumer_key": "",
+ "consumer_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 = '{"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 = "{'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 = "{'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_serialization(self):
+ """
+ Tests non-json data returned
+ """
+ r = mock.Mock(spec=requests.Response)
+ r.status_code = 200
+ r.content = "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 = '{"it\'s all": "ok"}'
+
+ f = Fitbit(**self.client_kwargs)
+ f.client._request = lambda *args, **kwargs: r
+ self.assertRaises(exceptions.DeleteError, f.delete_activities, 12345)
+
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..e26d6b8
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,4 @@
+oauth2>=1.5.211
+requests>=0.14.0
+python-dateutil>=1.5
+requests-oauthlib
\ No newline at end of file
diff --git a/requirements_dev.txt b/requirements_dev.txt
new file mode 100644
index 0000000..5442982
--- /dev/null
+++ b/requirements_dev.txt
@@ -0,0 +1,4 @@
+-r requirements.txt
+-r requirements_test.txt
+Sphinx==1.1.3
+Mock
diff --git a/requirements_test.txt b/requirements_test.txt
new file mode 100644
index 0000000..9d11ae4
--- /dev/null
+++ b/requirements_test.txt
@@ -0,0 +1 @@
+mock==0.8.0
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..a9063b2
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,39 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import re
+
+from setuptools import setup
+
+required = [line for line in open('requirements.txt').read().split("\n")]
+required_dev = [line for line in open('requirements_dev.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=["distribute"] + required,
+ license='Apache 2.0',
+ test_suite='fitbit_tests.all_tests',
+ tests_require=required_dev,
+ 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',
+ ),
+)
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-med/python-fitbit.git
More information about the debian-med-commit
mailing list