This repository has been archived on 2024-05-31. You can view files and clone it, but cannot push or open issues or pull requests.
devicehub-teal/ereuse_devicehub/resources/device/views.py

73 lines
2.1 KiB
Python
Raw Normal View History

2018-10-03 12:51:22 +00:00
import datetime
2018-09-30 17:40:28 +00:00
import marshmallow
2018-10-03 12:51:22 +00:00
from flask import current_app as app, render_template, request
2018-09-30 17:40:28 +00:00
from flask.json import jsonify
from flask_sqlalchemy import Pagination
2018-10-03 12:51:22 +00:00
from teal.cache import cache
2018-04-10 15:06:39 +00:00
from teal.resource import View
2018-10-03 12:51:22 +00:00
from ereuse_devicehub import auth
2018-09-30 17:40:28 +00:00
from ereuse_devicehub.resources.device.models import Device, Manufacturer
2018-09-07 10:38:02 +00:00
2018-04-10 15:06:39 +00:00
class DeviceView(View):
def get(self, id):
"""
Devices view
---
description: Gets a device or multiple devices.
parameters:
- name: id
type: integer
in: path
description: The identifier of the device.
responses:
200:
description: The device or devices.
"""
return super().get(id)
2018-04-27 17:16:43 +00:00
def one(self, id: int):
2018-04-10 15:06:39 +00:00
"""Gets one device."""
2018-10-03 12:51:22 +00:00
if not request.authorization:
return self.one_public(id)
else:
return self.one_private(id)
def one_public(self, id: int):
device = Device.query.filter_by(id=id).one()
return render_template('devices/layout.html', device=device)
@auth.Auth.requires_auth
def one_private(self, id: int):
device = Device.query.filter_by(id=id).one()
return self.schema.jsonify(device)
2018-10-03 12:51:22 +00:00
@auth.Auth.requires_auth
def find(self, args: dict):
"""Gets many devices."""
return self.schema.jsonify(Device.query, many=True)
2018-09-30 17:40:28 +00:00
class ManufacturerView(View):
class FindArgs(marshmallow.Schema):
name = marshmallow.fields.Str(required=True,
# Disallow like operators
validate=lambda x: '%' not in x and '_' not in x)
2018-10-03 12:51:22 +00:00
@cache(datetime.timedelta(days=1))
2018-09-30 17:40:28 +00:00
def find(self, args: dict):
name = args['name']
manufacturers = Manufacturer.query \
.filter(Manufacturer.name.ilike(name + '%')) \
.paginate(page=1, per_page=6) # type: Pagination
return jsonify(
items=app.resources[Manufacturer.t].schema.dump(
manufacturers.items,
many=True,
nested=1
)
)