Files
puppetboard/puppetboard/utils.py
Corey Hammerton af05f67428 puppetboard: Adding PuppetDB 3.x support
Some excerpts from CHANGELOG.rst include:
- Increasing the pypuppetdb requirements from 0.1.x to 0.2.x
- The Reports page now lists reports from the reports endpoint instead of
  a link to a PuppetDB issue with a feature request
- Adding a Catalogs page to view either individual node catalogs or compare
  them against other nodes
- New environment awareness adds a new query parameter to all applicable
  endpoints to filter results based on the current environment. If the
  default environment 'production' is not available, or any other unavailable
  environment, the user is redirected to the first known environment.
- Adding pagination functionality for reports (for now) based on the value of
  the REPORTS_COUNT configuration option (used for the limit and the offset
  calculation). Implementation also makes it possible for other UI enhancements.
- Removing the limit_reports function from puppetboard/utils.py since paging
  parameters are now accepted by the pypuppetdb endpoint functions.
- Bumping the version to 0.1.0
2015-10-26 21:44:33 -04:00

79 lines
2.1 KiB
Python

from __future__ import absolute_import
from __future__ import unicode_literals
import json
from math import ceil
from requests.exceptions import HTTPError, ConnectionError
from pypuppetdb.errors import EmptyResponseError
from flask import abort
def jsonprint(value):
return json.dumps(value, indent=2, separators=(',', ': '))
def get_or_abort(func, *args, **kwargs):
"""Execute the function with its arguments and handle the possible
errors that might occur.
In this case, if we get an exception we simply abort the request.
"""
try:
return func(*args, **kwargs)
except HTTPError as e:
abort(e.response.status_code)
except ConnectionError:
abort(500)
except EmptyResponseError:
abort(204)
def yield_or_stop(generator):
"""Similar in intent to get_or_abort this helper will iterate over our
generators and handle certain errors.
Since this is also used in streaming responses where we can't just abort
a request we raise StopIteration.
"""
while True:
try:
yield next(generator)
except StopIteration:
raise
except (EmptyResponseError, ConnectionError, HTTPError):
raise StopIteration
class Pagination(object):
def __init__(self, page, per_page, total_count):
self.page = page
self.per_page = per_page
self.total_count = total_count
@property
def pages(self):
return int(ceil(self.total_count / float(self.per_page)))
@property
def has_prev(self):
return self.page > 1
@property
def has_next(self):
return self.page < self.pages
def iter_pages(self, left_edge=2, left_current=2,
right_current=5, right_edge=2):
last = 0
for num in xrange(1, self.pages + 1):
if num <= left_edge or \
(num > self.page - left_current - 1 and \
num < self.page + right_current) or \
num > self.pages - right_edge:
if last + 1 != num:
yield None
yield num
last = num