Merge branch 'add-docs' into 'master'

Sphinx documentation

See merge request Lucidiot/pyurbantz!1
This commit is contained in:
Lucidiot 2018-10-25 17:10:49 +00:00
commit 7a993a469b
14 changed files with 438 additions and 50 deletions

3
.gitignore vendored
View File

@ -21,6 +21,7 @@ wheels/
.installed.cfg
*.egg
MANIFEST
docs/_build/
htmlcov/
.tox/
@ -58,4 +59,4 @@ Session.vim
tags
[._]*.un~
.vscode/*
.vscode/*

View File

@ -55,3 +55,18 @@ deploy-testpypi:
- python setup.py sdist bdist_wheel
- twine upload dist/* -r testpypi
pages:
stage: deploy
when: manual
only:
- master@Lucidiot/pyurbantz
artifacts:
paths:
- public
before_script:
- pip install .[dev]
script:
- cd docs
- make html
- mv _build/html ../public

View File

@ -1,48 +1,3 @@
# pyurbantz
A Python package to help with an undocumented API of UrbanTZ.
The UrbanTZ company provides a delivery management platform of the same name
for other companies. To provide delivery tracking to their customers, those
companies can send links to a tracking page on UrbanTZ's website, which uses
a unique delivery ID in the URL to show tracking information.
Those tracking pages perform requests to an undocumented API endpoint with this
tracking ID. The endpoint provides much more information than what is actually
used in the pages; this package aims to provide a Python interface to help
creating better tracking interfaces.
## Requirements
This package just needs [requests](https://python-requests.org). That's it.
## Scripts
This package provides a simple tracker script, `urbantz.tracker`, that can be
invoked like this:
``` bash
python -m urbantz.tracker <ID> [-f|--frequency <seconds>]
```
The script will perform a request every 10 seconds (by default) to the
UrbanTZ API, then print the current date, time, and distance between the
delivery truck and the destination.
## Development
### Setup
Sample setup using
[`virtualenvwrapper`](https://virtualenvwrapper.readthedocs.io/):
```
mkvirtualenv pyurbantz -a .
pip install -e .[dev]
```
### Linting
The source code follows the PEP 8 code style and performs CI checks using the
`flake8` tool. To perform the same checks locally, run `flake8` on the root
directory of this repository.
A Python package to help with an undocumented API of UrbanTZ. [Browse documentation](https://lucidiot.gitlab.io/pyurbantz)

1
VERSION Normal file
View File

@ -0,0 +1 @@
0.1.0

19
docs/Makefile Normal file
View File

@ -0,0 +1,19 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

20
docs/api.rst Normal file
View File

@ -0,0 +1,20 @@
API Reference
=============
Deliveries
----------
.. automodule:: urbantz.delivery
:members:
Exceptions
----------
.. automodule:: urbantz.exceptions
:members:
Helper classes
--------------
.. automodule:: urbantz.utils
:members:

182
docs/conf.py Normal file
View File

@ -0,0 +1,182 @@
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# 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.
#
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
# -- Project information -----------------------------------------------------
project = 'pyurbantz'
copyright = '2018, Lucidiot and contributors'
author = 'Lucidiot and contributors'
# The short X.Y version
version = ''
# The full version, including alpha/beta/rc tags
release = open('../VERSION').read().strip()
# -- 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',
'sphinx.ext.coverage',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'default'
# -- 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 = 'alabaster'
# 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 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']
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'pyurbantzdoc'
# -- 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': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'pyurbantz.tex', 'pyurbantz Documentation',
'Lucidiot and contributors', 'manual'),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'pyurbantz', 'pyurbantz Documentation',
[author], 1)
]
# -- 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 = [
(master_doc, 'pyurbantz', 'pyurbantz Documentation',
author, 'pyurbantz', 'One line description of project.',
'Miscellaneous'),
]
# -- Options for Epub output -------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# -- Extension configuration -------------------------------------------------
# Concatenate the class' and __init__'s docstrings when documenting a class
autoclass_content = 'both'

53
docs/contributing.rst Normal file
View File

@ -0,0 +1,53 @@
Contributing
============
Contributions to the project are greatly appreciated.
Bugs and suggestions
--------------------
You may `submit an issue`_ to GitLab to warn of any bugs, ask for new features,
or ask any questions that are not answered in this documentation.
When reporting a bug, do not forget to put in your version of Python and your
version of *pyurbantz*. This will greatly help when troubleshooting, as most
errors often come from version incompatibilities.
Development
-----------
Setup
^^^^^
You will need a virtual envionment to work properly. `virtualenvwrapper`_ is
recommended::
git clone https://gitlab.com/Lucidiot/pyurbantz
cd pyurbantz
mkvirtualenv -a . pyurbantz
pip install -e .[dev]
This will clone the repository, create a virtual environment named ``pyurbantz``,
then tell pip to let the package be editable (``-e``). The ``[dev]`` suffix adds
the extra requirements useful for development.
Linting
^^^^^^^
The source code follows the PEP 8 code style and performs CI checks using the
``flake8`` tool. To perform the same checks locally, run ``flake8`` on the root
directory of this repository.
Documentation
-------------
The documentation you are reading is generated by the `Sphinx`_ tool.
The text files that hold the documentation's contents are written in
`reStructuredText`_ and are available under the ``/docs`` folder of the
`GitLab repository`_.
.. _submit an issue: https://gitlab.com/Lucidiot/pyurbantz/issues/new
.. _virtualenvwrapper: https://virtualenvwrapper.readthedocs.io
.. _GitLab repository: https://gitlab.com/Lucidiot/pyurbantz
.. _Sphinx: http://www.sphinx-doc.org/
.. _reStructuredText: http://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html

70
docs/index.rst Normal file
View File

@ -0,0 +1,70 @@
Python UrbanTZ client
=====================
:ref:`genindex` - :ref:`modindex` - :ref:`search`
.. image:: https://img.shields.io/pypi/v/pyurbantz.svg
:target: https://pypi.org/project/pyurbantz
.. image:: https://img.shields.io/pypi/l/pyurbantz.svg
:target: https://pypi.org/project/pyurbantz
.. image:: https://img.shields.io/pypi/format/pyurbantz.svg
:target: https://pypi.org/project/pyurbantz
.. image:: https://img.shields.io/pypi/pyversions/pyurbantz.svg
:target: https://pypi.org/project/pyurbantz
.. image:: https://img.shields.io/pypi/status/pyurbantz.svg
:target: https://pypi.org/project/pyurbantz
.. image:: https://gitlab.com/Lucidiot/pyurbantz/badges/master/pipeline.svg
:target: https://gitlab.com/Lucidiot/pyurbantz/pipelines
.. image:: https://requires.io/github/Lucidiot/pyurbantz/requirements.svg?branch=master
:target: https://requires.io/github/Lucidiot/pyurbantz/requirements/?branch=master
.. image:: https://img.shields.io/github/last-commit/Lucidiot/pyurbantz.svg
:target: https://gitlab.com/Lucidiot/pyurbantz/commits
.. image:: https://img.shields.io/badge/badge%20count-9-brightgreen.svg
:target: https://gitlab.com/Lucidiot/pyurbantz
A Python package to help with an undocumented API of
`UrbanTZ <https://www.urbantz.com/>`_.
The UrbanTZ company provides a delivery management platform of the same name
for other companies. To provide delivery tracking to their customers, those
companies can send links to a tracking page on UrbanTZ's website, which uses
a unique delivery ID in the URL to show tracking information.
Those tracking pages perform requests to an undocumented API endpoint with this
tracking ID. The endpoint provides much more information than what is actually
used in the pages; this package aims to provide a Python interface to help
creating better tracking interfaces.
Requirements
------------
This package just needs `requests <https://python-requests.org>`_. That's it.
Scripts
-------
This package provides a simple tracker script, ``urbantz.tracker``, that can be
invoked like this::
python -m urbantz.tracker <ID> [-f|--frequency <seconds>]
The script will perform a request every 10 seconds (by default) to the
UrbanTZ API, then print the current date, time and distance between the
delivery truck and the destination.
Other topics
------------
.. toctree::
:maxdepth: 2
contributing
api

View File

@ -1 +1,2 @@
flake8>=3.5
Sphinx>=1.8.1

View File

@ -7,7 +7,7 @@ def read_requirements(filename):
setup(
name='pyurbantz',
version='0.1.0',
version=open('VERSION').read().strip(),
author='Lucidiot',
packages=find_packages(
exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),

View File

@ -10,19 +10,58 @@ class Delivery(object):
"""
def __init__(self, id):
"""
:param str id: A delivery ID.
"""
self.id = id
"""
The delivery ID.
:type: str
"""
self.last_updated = None
"""
Last API update date/time. Is None if data has never been fetched
from the API.
:type: datetime or None
"""
self.position = None
"""
Coordinates of the delivery truck's position.
:type: urbantz.utils.Coordinates
"""
self.destination = None
"""
Coordinates of the delivery destination.
:type: urbantz.utils.Coordinates
"""
def __repr__(self):
return '{}({})'.format(self.__class__.__name__, self.id)
@property
def api_url(self):
"""
URL pointing to the API endpoint to use for the specific delivery.
:type: str
"""
return 'https://backend.urbantz.com/public/task/tracking/' + self.id
def update(self):
"""
Fetch the latest delivery information from the API.
:raises requests.exceptions.HTTPError: If the response has an
HTTP 4xx or 5xx code.
:raises urbantz.exceptions.APIError: If the API returned an error.
"""
resp = requests.get(self.api_url)
resp.raise_for_status()
data = resp.json()

View File

@ -1,6 +1,14 @@
class APIError(Exception):
"""
An error returned by the UrbanTZ API.
This does not include HTTP errors.
"""
def __init__(self, error):
"""
:param error: Parsed JSON error from the API.
:type error: dict
"""
self.message = error.get('message')
self.code = error.get('code')

View File

@ -10,7 +10,10 @@ class Coordinates(object):
def __init__(self, lat=0, lng=0):
"""
Coordinates from decimal degrees
Get coordinates from decimal degrees.
:param float lat: Latitude in decimal degrees.
:param float lng: Longitude in decimal degrees.
"""
self.lat = lat
self.lng = lng
@ -82,11 +85,22 @@ class Coordinates(object):
return self.__class__(lat=ceil(self.lat), lng=ceil(self.lng))
def to_radians(self):
"""
Convert to a ``(lat, lng)`` tuple in radians.
:returns: Coordinates in radians.
:rtype: tuple(float, float)
"""
return tuple(map(radians, self))
def distance(self, other):
"""
Compute Haversine distance between two coordinates.
Compute Haversine distance between two coordinates in meters.
:param other: Another pair of coordinates to compute distance against.
:type other: Coordinates
:returns: Distance between the two coordinates, in meters.
:rtype: float
"""
if not hasattr(other, 'to_radians'):
raise NotImplementedError(
@ -100,9 +114,19 @@ class Coordinates(object):
def toJSON(self):
"""
Convert to UrbanTZ JSON geometry
:returns: UrbanTZ-compatible JSON geometry data
:rtype: list(float)
"""
return [self.lng, self.lat]
@staticmethod
def fromJSON(geometry):
"""
Get a Coordinates instance from parsed UrbanTZ JSON geometry data.
:param geometry: Parsed UrbanTZ geometry data: a list holding
``[lng, lat]`` in decimal degrees.
:type geometry: list(float)
"""
return Coordinates(lng=geometry[0], lat=geometry[1])