def setup_tasks_endpoint(): endpoint = api.namespace( name='tasks', description='Endpoint to handle tasks CRUD operations.') @endpoint.route('/') @endpoint.doc(security='apiKey') class ListTasks(TokenRequiredMixin, Resource): @endpoint.marshal_list_with(TaskSerializer) @endpoint.param( 'chunk', f'dividing tasks into chunks of {LIMIT_PER_CHUNK}, default is 1.') def get(self): ''' Get list of tasks. ''' chunk = request.args.get('chunk', 1, type=int) return Task.query.paginate(chunk, per_page=LIMIT_PER_CHUNK, error_out=False).items, HTTPStatus.OK
'total_pages': fields.Integer( description='Total number of pages of results' ), 'total_items': fields.Integer(description='Total number of results'), 'next_page': fields.String(), 'prev_page': fields.String() } ) customers_list = api.inherit( 'Page of customers', pagination, {'customers': fields.List(fields.Nested(customer_model))} ) ns_customers = api.namespace('customers', description='Customers') parser = reqparse.RequestParser() parser.add_argument('page', 1, type=int, location='args', required=False) parser.add_argument('per_page', 10, choices=[5, 10, 25, 50, 100], type=int, location='args', required=False) @ns_customers.route('/<int:id>') class CustomerService(Resource): @api.marshal_with(customer_model) def get(self, id): return Customer.query.get_or_404(id).to_dict() @api.expect(customer_model)
# -*- coding: utf-8 -*- from flask import json, g from flask_httpauth import HTTPTokenAuth from flask_restplus import Resource from app.elastic import get_user_from_id from app.models import User from app.api import api ns = api.namespace('postman', description='Postman export.') # ================================================================================================ # AUTH # ================================================================================================ # # Auth verification # # ================================================================================================ auth = HTTPTokenAuth(scheme='Token') @auth.verify_token def verify_token(token): """ Verify auth token :param token: User token :type token: str :return: True if valid token, else False
def setup_tickets_endpoint(): endpoint = api.namespace( name='tickets', description='Endpoint to handle tickets CRUD operations.') @endpoint.route('/') @endpoint.doc(security='apiKey') class ListDeleteAndCreateTickets(TokenRequiredMixin, Resource): @endpoint.marshal_list_with(TicketSerializer) @endpoint.param('processed', 'get only processed tickets, by default False.') @endpoint.param( 'chunk', f'dividing tickets into chunks of {LIMIT_PER_CHUNK}, default is 1.' ) def get(self): ''' Get list of tickets. ''' chunk = request.args.get('chunk', 1, type=int) processed = request.args.get('processed', False, type=bool) tickets = Serial.all_clean() if processed: tickets = tickets.filter_by(p=True) return tickets.paginate(chunk, per_page=LIMIT_PER_CHUNK, error_out=False).items, HTTPStatus.OK @endpoint.marshal_with(TicketSerializer) @endpoint.expect(TicketSerializer) def post(self): ''' Generate a new ticket. ''' registered = api.payload.get('n', False) name_or_number = api.payload.get('name', None) task = Task.get(api.payload.get('task_id', None)) office = Office.get(api.payload.get('office_id', None)) if not task: abort(message='Task not found', code=HTTPStatus.NOT_FOUND) if registered and not name_or_number: abort(message='Name must be entered for registered tickets.', code=HTTPStatus.NOT_FOUND) ticket, exception = Serial.create_new_ticket( task, office, name_or_number) if exception: abort(message=str(exception)) return ticket, HTTPStatus.OK def delete(self): ''' Delete all tickets. ''' Serial.all_clean().delete() db.session.commit() return '', HTTPStatus.NO_CONTENT @endpoint.route('/<int:ticket_id>') @endpoint.doc(security='apiKey') class GetAndUpdateTicket(TokenRequiredMixin, GetOrRejectMixin, Resource): module = Serial kwarg = 'ticket_id' @endpoint.marshal_with(TicketSerializer) def get(self, ticket_id): ''' Get a specific ticket. ''' return self.ticket, HTTPStatus.OK @endpoint.marshal_with(TicketSerializer) @endpoint.expect(TicketSerializer) def put(self, ticket_id): ''' Update a specific ticket. ''' api.payload.pop('id', '') self.ticket.query.update(api.payload) db.session.commit() return self.ticket, HTTPStatus.OK def delete(self, ticket_id): ''' Delete a specific ticket. ''' db.session.delete(self.ticket) db.session.commit() return '', HTTPStatus.NO_CONTENT @endpoint.route('/pull') @endpoint.doc(security='apiKey') class PullTicket(TokenRequiredMixin, Resource): @endpoint.marshal_with(TicketSerializer) @endpoint.param('ticket_id', 'to pull a specific ticket with, by default None.') @endpoint.param('office_id', 'to pull a specific ticket from, by default None.') def get(self): ''' Pull a ticket from the waiting list. ''' ticket_id = request.args.get('ticket_id', None, type=int) office_id = request.args.get('office_id', None, type=int) ticket = Serial.get(ticket_id) if ticket_id and not ticket: abort(message='Ticket not found', code=HTTPStatus.NOT_FOUND) next_ticket = ticket or Serial.get_next_ticket() if not next_ticket: abort(message='No tickets left to pull', code=HTTPStatus.NOT_FOUND) next_ticket.pull(office_id, self.auth_token and self.auth_token.id) return next_ticket, HTTPStatus.OK
from flask_restplus import abort from app import models from app.api import api from app.api.endpoints import TaskList, Task ns = api.namespace('text_tasks') @ns.route('/') class TextTaskList(TaskList): @property def model(self): return models.TextTask @property def celery_task(self): from app import celery_tasks return celery_tasks.execute_text_task @ns.route('/<string:tid>') class TextTask(Task): @property def model(self): return models.TextTask @ns.route('/<string:tid>/text') class TextTaskText(TextTask):
from Queue import Empty from flask import current_app from flask_restplus import Resource, fields from app.api import api from app.queue import L1_DATASOURCES from app.queue import L2_DATASOURCES ns = api.namespace('line', description='Operations to get lines displayed on the clock') @ns.route('/<int(min=0, max=1):lineno>') @api.response(404, 'Line not found.') class LineEP(Resource): """ Endpoint to get the lines to be displayed on the clock. """ def get(self, lineno): """ Get the messages queued for a line. """ lineno = int(lineno) plugin = None ret = {'text': '', 'icon': '', 'seconds': 0} plugin_queue = None if lineno == 0: plugin_queue = L1_DATASOURCES
from bson.errors import InvalidId from flask_restplus import abort from mongoengine import ValidationError from werkzeug.utils import redirect from app import models from app.api import api from app.api.endpoints import Task, TaskList from app.models import StatusEnum ns = api.namespace('images_tasks') @ns.route('/') class ImagesTaskList(TaskList): @property def model(self): return models.ImageTask @property def queryset(self): return super().queryset.exclude('images') @property def celery_task(self): from app import celery_tasks return celery_tasks.execute_images_task @ns.route('/<string:tid>') class ImagesTask(Task):
# Importing Flask and dependencies from flask import Blueprint, jsonify, request, make_response from flask_restx import Resource, abort from app.api import api import os # Import model and db from app import db from app.api.developer.model import Developer, DeveloperSchema, DeveloperRestSchema, DeveloperReturnSchema # Defining namespace developer_namespace = api.namespace(os.path.basename( os.path.dirname(os.path.realpath(__file__))), description='Manage developers.') ## Defining reoutes @developer_namespace.route('/<int:id>') class DeveloperApiOne(Resource): def get(self, id): if id is None: abort(400) developer_data = Developer.query.get(id) developer_schema = DeveloperSchema() retval = developer_schema.dump(developer_data) if not retval: abort(404, 'The requested data with id: %d does not exist.' % (id)) return jsonify(retval)
from flask import request from flask_restplus import Resource, fields from app.message import Message from app.queue import L2_DATASOURCES from app.api import api ns = api.namespace( 'message', description='Operations to add messages to be displayed on the clock') message = api.model( 'Message', { 'text': fields.String(description='The text of the messae'), 'icon': fields.String(description='Optional URL to an icon to include'), 'repeat': fields.Integer(description='Number times to display the message'), 'interval_sec': fields.Integer( description='Minimum number of seconds between message repeats'), 'display_sec': fields.Integer( description='Minimum number of seconds the messaage is visible') }) @ns.route('/') @api.expect(message) @api.response(404, 'Message was not added.')
from http import HTTPStatus from flask_restplus import Resource from flask import jsonify, request, abort, make_response from app.api import api from app.validators import UserValidator from app.models import User from app.extensions import db user_namespace = api.namespace('users/', description='User management API') api.add_namespace(user_namespace) @user_namespace.route('/user/') class UsersResource(Resource): """ Describes HTTP methods of users endpoint """ @api.expect(UserValidator.fields) def post(self): """ User Sign Up """ data = request.json errors = UserValidator.RequestValidator().validate(data) if errors: abort(HTTPStatus.UNPROCESSABLE_ENTITY, str(errors)) User.create(data) return make_response(jsonify({"message": "User has created"})) @api.expect(UserValidator.fields)