Skip to content

Commit

Permalink
Generate documentation with Sphinx
Browse files Browse the repository at this point in the history
  • Loading branch information
daviewales committed Dec 5, 2023
1 parent eab46a4 commit 226c92b
Show file tree
Hide file tree
Showing 6 changed files with 175 additions and 60 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
__pycache__/
docs/_build

*.json
*.zip
Expand Down
20 changes: 20 additions & 0 deletions docs/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#

# You can set these variables from the command line, and also
# from the environment for the first two.
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)
45 changes: 45 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information

project = 'pmhclib'
copyright = '2023, David Wales, Jonathan Stucken, South Western Sydney Primary Health Network'
author = 'David Wales, Jonathan Stucken, South Western Sydney Primary Health Network'
release = '0.2.0'

# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration

extensions = ['myst_parser', 'sphinx.ext.autodoc', 'autoapi.extension']

templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']


# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output

html_theme = 'alabaster'
html_static_path = ['_static']

# -- Options for autoapi
autoapi_dirs = ['../src/pmhclib']
# autoapi_keep_files = True

# Only document top level package (skip sub-modules)
def skip_submodules(app, what, name, obj, skip, options):
if what == "module":
skip = True
return skip


def setup(sphinx):
sphinx.connect("autoapi-skip-member", skip_submodules)


# -- Render type annotations in function description
autodoc_typehints = 'description'
20 changes: 20 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
.. pmhclib documentation master file, created by
sphinx-quickstart on Tue Dec 5 14:57:39 2023.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to pmhclib's documentation!
===================================

.. toctree::
:maxdepth: 2
:caption: Contents:



Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
35 changes: 35 additions & 0 deletions docs/make.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
@ECHO OFF

pushd %~dp0

REM Command file for Sphinx documentation

if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=.
set BUILDDIR=_build

%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.https://www.sphinx-doc.org/
exit /b 1
)

if "%1" == "" goto help

%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end

:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%

:end
popd
114 changes: 54 additions & 60 deletions src/pmhclib/pmhc.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,16 @@ class CouldNotFindPmhcUpload(Exception):


class SecureString(str):
"""Show *** instead of string value in tracebacks"""
"""Show `'***'` instead of string value in tracebacks"""

def __repr__(self):
return "***"


@dataclass
class PMHCSpecificationRepresentation:
"""Dataclass which provides structure for PMHCSpecification Enum."""

term: str
filter_term: str

Expand All @@ -67,24 +69,28 @@ class PMHCSpecification(PMHCSpecificationRepresentation, Enum):


class PMHC:
"""This class wraps the unofficial PMHC API. Use it to automate
tasks such as uploading to the PMHC website, downloading error
reports, downloading PMHC extracts, etc.
"""This class wraps the unofficial PMHC API.
Use it to automate tasks such as uploading to the PMHC website,
downloading error reports, downloading PMHC extracts, etc.
Usage:
This class is intended to be used as a context manager. This ensures
This class is intended to be used with a context manager. This ensures
that the playwright browser context is correctly closed. For
example:
>>> with PMHC() as pmhc:
... pmhc.login()
... pmhc.download_error_json('7f91a4f5')
... pmhc.download_error_json('94edf5e3-36b1-46d3-9178-bf3b142da6a1')
:param headless: Use headless browser
"""

def __enter__(self):
# Initialise playwright without a context manager
"""Initialise playwright. (Called automatically by context
manager.)
"""
self.p = sync_playwright().start()
self.browser = self.p.chromium.launch(headless=self.headless)
self.context = self.browser.new_context()
Expand All @@ -93,6 +99,9 @@ def __enter__(self):
return self # Return the instance of this class

def __exit__(self, exc_type, exc_value, traceback):
"""Shutdown playwright. (Called automatically when context
manager exits.)
"""
# exc_type, exc_value, and traceback are required parameters in __exit__()
self.browser.close()
self.p.stop()
Expand All @@ -108,7 +117,7 @@ def __init__(self, headless: bool = True):

def login(self):
"""Logs in to PMHC website. This allows us to reuse the login the session
across other class methods
across other class methods.
"""

# Prompt user for credentials if not set in env.
Expand Down Expand Up @@ -176,20 +185,16 @@ def upload_file(
input_file: Path,
test: bool = True,
) -> Path:
"""Uploads a user specified file to PMHC website
Args:
input_file (Path): path to the file e.g. 'cc9dd7b5.csv'
e.g. 'PMHC_MDS_20230101_20230131.xlsx'
test (bool): Upload in 'test' or 'live' mode? Defaults to True ('test').
Use False ('live') with care!
"""Uploads a user specified file to PMHC website.
Raises:
IncorrectFileType: If user uploads a bad filetype
FileNotFoundException: If we cannot find user file
:param input_file: Path to the file e.g. `'cc9dd7b5.csv'`
e.g. `'PMHC_MDS_20230101_20230131.xlsx'`
:param test: Upload in 'test' or 'live' mode? Defaults to `True`
('test'). Use `False` ('live') with care!
Returns:
Path: filename of the new file we generated for matching purposes
:raise IncorrectFileType: If user uploads a bad filetype
:raise FileNotFoundException: If we cannot find user file
:return: Filename of the new file we generated for matching purposes
"""

# check file looks ok
Expand Down Expand Up @@ -273,15 +278,13 @@ def download_error_json(self, uuid: str, download_folder: Path = Path(".")) -> P
"""Downloads a JSON error file from PMHC
This is useful for matching against uploaded files and processing
Args:
uuid (str): PMHC upload uuid from View Uploads page e.g.
94edf5e3-36b1-46d3-9178-bf3b142da6a1
The uuid is found in the URL to the upload summary page.
download_folder (Path): Location to save the downloaded error JSON.
(Default: current directory)
:param uuid: PMHC upload uuid from View Uploads page. For
example: `'94edf5e3-36b1-46d3-9178-bf3b142da6a1'`.
The uuid is found in the URL to the upload summary page.
:param download_folder: Location to save the downloaded error
JSON.
Returns:
Path: Path to JSON file saved to local disk
:return: Path to JSON file saved to local disk
"""

url = f"https://pmhc-mds.net/api/organisations/{self.phn_identifier}/uploads/{uuid}"
Expand All @@ -301,11 +304,11 @@ def download_error_json(self, uuid: str, download_folder: Path = Path(".")) -> P
return filename

def is_upload_processing(self) -> bool:
"""Checks if the user has an upload currently 'processing' in either live or
"""Checks if the user has an upload currently processing in either live or
test mode. Useful for checking before we do certain actions e.g. try upload
another file, because this script can only handle one 'processing' file at a time
Returns:
bool: True if an upload is currently processing
:return: `True` if an upload is currently processing, otherwise `False`.
"""
# Get a list of all this user's 'test' uploads ('processing', 'complete'
# and 'error' status)
Expand All @@ -324,42 +327,33 @@ def is_upload_processing(self) -> bool:
def download_pmhc_mds(
self,
output_directory: Path = Path("."),
start_date: Optional[date] = None,
end_date: Optional[date] = None,
start_date: date = date(2016, 1, 1),
end_date: date = date.today(),
organisation_path: Optional[str] = None,
specification: PMHCSpecification = PMHCSpecification.ALL,
without_associated_dates: bool = True,
matched_episodes: bool = True,
) -> Path:
"""Extract PMHC MDS Data within the date range. If no date range is given,
start_date defaults to 01/01/2016 and end_date defaults to the current date.
Output file is saved to output_directory. (current directory by default)
Args:
output_directory: directory to save download (defaults to
current directory)
start_date: start date for extract (default: 2016-01-01)
end_date: end date for extract (default: today)
organisation_path: PHN identifier defined when parent class is
initialised.
specification: Specification for extract. (default:
PMHCSpecification.ALL, which returns data from all
specifications
without_associated_dates: Enable extract option
"Include data without associated dates" (default: True)
matched_episodes: Enable extract option
"Include all data associated with matched episodes"
(default: True)
Returns:
Path to downloaded extract.
"""Extract PMHC MDS Data within the date range. If no date range
is given, `start_date` defaults to `2016-01-01` and `end_date`
defaults to the current date.
:param output_directory: directory to save download
:param start_date: start date for extract
:param end_date: end date for extract (default: today)
:param organisation_path: PHN identifier (default: inherited
from parent class.)
:param specification: Specification for extract. (default:
`PMHCSpecification.ALL`, which returns data from all
specifications
:param without_associated_dates: Enable extract option
"Include data without associated dates"
:param matched_episodes: Enable extract option
"Include all data associated with matched episodes"
:return: Path to downloaded extract.
"""

if start_date is None:
start_date = date(2016, 1, 1)
if end_date is None:
end_date = date.today()
if organisation_path is None:
organisation_path = self.phn_identifier

Expand Down

0 comments on commit 226c92b

Please sign in to comment.