Select Git revision
      
  install-sdist-to-test.py
  api.py  1.98 KiB 
"""
API Endpoints
=========================
.. contents:: :local:
/api/things
---------------------
.. autofunction:: compendium_v2.routes.api.things
"""
import binascii
import hashlib
import random
import time
from flask import Blueprint, jsonify
from compendium_v2.routes import common
routes = Blueprint("compendium-v2-api", __name__)
THING_LIST_SCHEMA = {
    '$schema': 'http://json-schema.org/draft-07/schema#',
    'definitions': {
        'thing': {
            'type': 'object',
            'properties': {
                'id': {'type': 'string'},
                'time': {'type': 'number'},
                'state': {'type': 'boolean'},
                'data1': {'type': 'string'},
                'data2': {'type': 'string'},
                'data3': {'type': 'string'}
            },
            'required': ['id', 'time', 'state', 'data1', 'data2', 'data3'],
            'additionalProperties': False
        }
    },
    'type': 'array',
    'items': {'$ref': '#/definitions/thing'}
}
@routes.after_request
def after_request(resp):
    return common.after_request(resp)
@routes.route("/things", methods=['GET', 'POST'])
@common.require_accepts_json
def things():
    """
    handler for /api/things requests
    response will be formatted as:
    .. asjson::
        compendium_v2.routes.api.THING_LIST_SCHEMA
    :return:
    """
    def _hash(s, length):
        m = hashlib.sha256()
        m.update(s.encode('utf-8'))
        digest = binascii.b2a_hex(m.digest()).decode('utf-8')
        return digest[-length:].upper()
    def _make_thing(idx):
        six_months = 24 * 3600 * 180
        return {
            'id': _hash(f'id-{idx}', 4),
            'time': int(time.time() + random.randint(-six_months, six_months)),
            'state': bool(idx % 2),
            'data1': _hash(f'data1-{idx}', 2),
            'data2': _hash(f'data2-{idx}', 8),
            'data3': _hash(f'data3-{idx}', 32)
        }
    response = map(_make_thing, range(20))
    return jsonify(list(response))