def test_inherit_from_multiple_parents(self): api = Namespace('test') grand_parent = api.model('GrandParent', {}) parent = api.model('Parent', {}) api.inherit('Child', grand_parent, parent, {}) assert 'GrandParent' in api.models assert 'Parent' in api.models assert 'Child' in api.models
def test_clone_with_multiple_parents(self): api = Namespace('test') grand_parent = api.model('GrandParent', {}) parent = api.model('Parent', {}) api.clone('Child', grand_parent, parent, {}) assert 'Child' in api.models assert 'Parent' in api.models assert 'GrandParent' in api.models
def test_inherit(self): api = Namespace('test') parent = api.model('Parent', {}) api.inherit('Child', parent, {}) self.assertIn('Parent', api.models) self.assertIn('Child', api.models)
def test_clone(self): api = Namespace('test') parent = api.model('Parent', {}) api.clone('Child', parent, {}) assert 'Child' in api.models assert 'Parent' in api.models
def test_inherit(self): authorizations = { 'apikey': { 'type': 'apiKey', 'in': 'header', 'name': 'X-API-KEY' } } api = Namespace('test', authorizations=authorizations) parent = api.model('Parent', {}) api.inherit('Child', parent, {}) assert 'Parent' in api.models assert 'Child' in api.models assert api.authorizations == authorizations
from Cerebrum.rest.api import db, auth, utils from Cerebrum.rest.api import fields as crb_fields from Cerebrum.rest.api.v1 import models api = Namespace('search', description='Search operations') ExternalIdItem = api.model('ExternalIdItem', { 'href': crb_fields.href( endpoint='.person'), 'person_id': base_fields.Integer( description='Person ID', attribute='entity_id'), 'source_system': crb_fields.Constant( ctype='AuthoritativeSystem', description='Source system'), 'id_type': crb_fields.Constant( ctype='EntityExternalId', transform=models.ExternalIdType.serialize, description='External ID type'), 'external_id': base_fields.String( description='External ID value') }) @api.route('/persons/external-ids', endpoint='search-persons-external-ids') class ExternalIdResource(Resource): """Resource for external ID searches.""" # GET / #
@author: Jonas ''' from flask.globals import request from flask_restplus import Namespace, fields from flask_restplus import Resource from son_editor.impl import catalogue_servicesimpl from son_editor.util.constants import WORKSPACES, CATALOGUES, VNFS from son_editor.util.requestutil import prepare_response, get_json namespace = Namespace(WORKSPACES + '/<int:ws_id>/' + CATALOGUES + "/<int:catalogue_id>/" + VNFS, description="Catalogue VNF Resources") funct = namespace.model("VNF", { 'name': fields.String(required=True, description='The VNF Name'), 'vendor': fields.String(required=True, description='The VNF Vendor'), 'version': fields.String(required=True, description='The VNF Version') }) funct_nest = namespace.model("VNF", { "descriptor": fields.Nested(model=funct, description="The Complete VNF Descriptor"), 'id': fields.String(required=True, description='The VNF UID') }) id = namespace.model("VNF_UID", { 'id': fields.String(required=True, description='The VNF UID') }) funct_response = funct.inherit("FunctionResponse", funct, { "descriptor": fields.Nested(model=funct, description="The Complete VNF Descriptor"), "id": fields.Integer(description='The Project ID'),
'version': fields.String(required=True, description='The VNF Version') }) uid = Model("VNF_UID", { 'id': fields.String(required=True, description='The VNF UID') }) funct_response = funct.inherit("FunctionResponse", funct, { "descriptor": fields.Nested(model=funct, description="The Complete VNF Descriptor"), "id": fields.Integer(description='The Project ID'), "project_id": fields.Integer(description='The parent project id'), }) message_response = proj_namespace.model("Message", { 'message': fields.String(required=True, description="The result message") }) proj_namespace.add_model(funct.name, funct) proj_namespace.add_model(funct_response.name, funct_response) @proj_namespace.route('/') @cata_namespace.route('/') @plat_namespace.route('/') @proj_namespace.param('ws_id', 'The Workspace identifier') @cata_namespace.param('ws_id', 'The Workspace identifier') @plat_namespace.param('ws_id', 'The Workspace identifier') @proj_namespace.param('parent_id', 'The Project identifier') @cata_namespace.param('parent_id', 'The Catalogue identifier') @plat_namespace.param('parent_id', 'The Platform identifier')
) base_parser.add_argument( LOCAL_ORDERING_FIELD_NAME, type=inputs.boolean, location="args", default=DataController.DEFAULT_LOCAL_ORDERING_VALUE, ) publish_item_model = data_ns.model( "Publish Item", { BLOCKCHAIN_NAME_FIELD_NAME: fields.String(required=True, description="The blockchain name"), STREAM_NAME_FIELD_NAME: fields.String(required=True, description="The stream name"), KEYS_FIELD_NAME: fields.List(fields.String, required=True, description="a list of keys for the data"), DATA_FIELD_NAME: fields.String(required=True, description="the data to be stored"), }, ) @data_ns.route("/publish_item") class PublishItem(Resource): @data_ns.expect(publish_item_model, validate=True) @data_ns.doc( responses={ status.HTTP_400_BAD_REQUEST: "BAD REQUEST",
import datetime from flask.ext.jwt import current_identity, jwt_required from flask_restplus import Namespace, Resource from packr.models import Order api = Namespace('orders', description='Operations related to orders') orders = api.model('Orders', { }) @api.route('/') class OrdersItem(Resource): @api.expect(orders) @api.response(204, 'Grabbed orders.') @jwt_required() def post(self): orders_list = list() orders_source = None if current_identity.role.role_name == 'user': orders_source = Order.query.filter_by(user_id=current_identity.id) elif current_identity.role.role_name == 'driver': orders_source = Order.query.filter_by( driver_id=current_identity.id) elif current_identity.role.role_name == 'admin': orders_source = Order.query
def test_ordered_model(self): api = Namespace('test', ordered=True) api.model('Person', {}) assert 'Person' in api.models assert isinstance(api.models['Person'], OrderedModel)
parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) from core.sqlClasses import * from core.helpers import token_required parents_api = Namespace('parents', 'Operation with parents') # Setting up ID only parser idOnlyParser = reqparse.RequestParser() idOnlyParser.add_argument('id', type=int, required=True, location="args") # Setting up "First" parser firstNArg = reqparse.RequestParser() firstNArg.add_argument('first', type=int, required=False, location="args") idOnlyParserJson = parents_api.model( 'DeleteEntry', {'id': fields.Integer(default=1, required=True)}) # Defining a newParent model newParent = parents_api.model( 'NewParent', { 'name': fields.String(default="John", required=True), 'surname': fields.String(default="Doe", required=True), 'email': fields.String(default="*****@*****.**", required=True), 'adress': fields.String(default="Students Adress 16 NY", required=True), 'phone': fields.String(default="+421 999 999 999", required=True), 'children': fields.List(fields.Integer, description="Children IDs") }) # Defining a updateParent model updateParent = parents_api.model(
import shlex from flask import request from flask_restplus import Resource, Namespace, fields from son_editor.impl.gitimpl import clone, pull, commit_and_push, create_commit_and_push, delete, list, diff, init, \ status from son_editor.util.constants import WORKSPACES, GIT from son_editor.util.requestutil import get_json, prepare_response namespace = Namespace(WORKSPACES + '/<int:ws_id>/' + GIT, description='Git API') pull_model = namespace.model('Pull information', { 'project_id': fields.Integer(description='Project ID of the project to get pulled from') }) init_model = namespace.model('Init information', { 'project_id': fields.Integer(description='Project ID of the project to call git init from') }) diff_model = namespace.model('Diff information', { 'project_id': fields.Integer(description='Project ID of the project to get diff information') }) clone_model = namespace.model('Clone information', { 'url': fields.String(description='URL to clone from') }) delete_model = namespace.model('Delete information', { 'project_id': fields.Integer(description='Project ID of the project to get diff information'), 'repo_name': fields.String(description='Remote repository that gets deleted'),
@self.ns.route('/full/<uuid>') class FullRoute(Resource): @self.ns.doc('{}_full'.format(self.name)) def get(self,uuid): return crud_get(cls,uuid,full='full') #========# # Routes # #========# ### ns_users = Namespace('users', description='User login') user_model = ns_users.model("user", { "username": fields.String(), "password": fields.String(), "login_key": fields.String() }) @ns_users.route('/') class UserPostRoute(Resource): @ns_users.doc('user_create') @ns_users.expect(user_model) def post(self): '''Post new user. Checks for Login key''' username = request.json.get('username') password = request.json.get('password') login_key = request.json.get('login_key') if username is None or password is None: abort(400) # missing arguments if User.query.filter_by(username=username).first() is not None:
from app.models.contact_person import ContactPerson from app.models.user import User from app.utils.utilities import auth from instance.config import Config company_api = Namespace( 'companies', description='A company creation namespace') address_fields = company_api.model( 'address', { 'district': fields.String(required=False, attribute='district'), 'postal': fields.String(required=False, attribute='postal_code'), 'country': fields.String(required=False, attribute='country'), 'address_line_1': fields.String( required=True, attribute='address_line_1'), 'address_line_2': fields.String( required=True, attribute='address_line_2'), } ) contact_people_fields = company_api.model( 'contact_people', { 'email': fields.String(required=True, attribute='contact.email'), 'person': fields.String(required=True, attribute='person.full_name') } )
import qrcode import qrcode.image.svg import io from flask_restplus import Namespace, Resource, fields from models.authorization import authorize_decorator api = Namespace('QR', description='QR-code api.') qr_code_object = api.model(name='QR-code', model={ 'value': fields.String( description='QR-code will be created from this value, \ link, value etc.'), 'qr_code': fields.String(description='SVG QR-code as a string.'), }) @api.route('') class QRApi(Resource): method_decorators = [authorize_decorator] @api.expect([qr_code_object], validate=False) @api.response(200, 'Success', [qr_code_object]) def post(self): factory = qrcode.image.svg.SvgImage QR_codes = [] text_values = api.payload for qr_code in text_values: qr_code_image = qrcode.make(
"""This module implements prediction API.""" from collections import namedtuple from flask_restplus import Namespace, Resource, fields from prometheus_client import Histogram from dajare.model import GenerationModel api = Namespace('generate', description='Generation related operations') generation = api.model( 'Generation', {'output': fields.String(description='The final dajare')}) GenerateParam = namedtuple('GenerateParam', 'name type required help') generate_parser = api.parser() generate_parser.add_argument('input', type=str, location='form') LATENCY = Histogram('request_latency_seconds', 'Request Latency') @api.route('/') class Generate(Resource): """Resource providing model prediction.""" @api.expect(generate_parser) @api.marshal_with(generation) @LATENCY.time() def post(self): """Call model prediction for the given parameters.
post_task = ns.model( 'post-task', { 'image': fields.String( required=True, min_length=1, description='The docker image where the script is executed'), 'script': fields.String(required=True, min_length=1, description='The shellcode to be executed'), 'scratch': fields.String(required=True, min_length=1, description='Does the job need a scratch dir?'), 'cores': fields.Integer( required=True, min=1, description='The amount of cores needed to peform the task'), 'memory': fields.Integer( required=True, min=1, description="The amount of ram in GiB needed to peform the task"), 'secrets': fields.List( fields.String, required=False, description= 'A list of keys of secrets to be injected into the process') })
from flask import jsonify import requests import json from datetime import datetime, timedelta from repository import Repository from elasticsearch import NotFoundError repository = Repository(app.config) index='account' doc_type='google', api = Namespace('auth', description='Authentication operations') user = api.model('User', { 'login': fields.String(readOnly=True, description='The unique identifier'), 'name': fields.String(required=True, description='Full name'), }) payload = api.model('Payload json', { 'json': fields.String, }) @api.route('/google') class GoogleProvider(Resource): """Google Auth Operations.""" # Using OAuth 2.0 to Access Google APIs. Login flow # https://developers.google.com/identity/protocols/OAuth2 # https://developers.google.com/identity/protocols/OpenIDConnect#exchangecode # Step 1: (Browser) Send an authentication request to Google # Step 2: Exchange authorization code for access token.
from flask_restplus import Namespace, fields, marshal from sg_datalake import DatalakeRecord from package_as_a_service.core.decorators import DecoratedResource import logging dl_logger = logging.getLogger('datalake') namespace = Namespace( 'token', description='SGConnect token informations') token_schema = namespace.model('Token', { 'login_ad': fields.String(description='The Active Directory login'), 'mail': fields.String(description='The contact email'), 'expired': fields.Boolean(description='Is this token expired') }) @namespace.doc(security=[{'oauth2_implicit': ['profile', 'itaas', 'openid']}]) @namespace.route('/') class Authentication(DecoratedResource): """ Display your authentication informations """ @namespace.marshal_list_with(token_schema, envelope="token") @namespace.doc(description='Allow you to retrieve \ information about your SGConnect token') def get(self): """ Your token informations """ token_info = self.get_token_info(g.token) dl_logger.info(DatalakeRecord(g.correlation_id, event="response",
from flask import session from flask_restplus import Resource, Namespace, fields, reqparse, abort from flask_restplus.inputs import boolean from db import datastore from ..restplus import api from ..decorators import require_token, require_admin from helpers import addWhiskey, deleteWhiskey, updateWhiskey, getAllWhiskeyNames logger = logging.getLogger("whiskey-routes") whiskeyApi = Namespace('whiskey', description='Whiskey related operations') whiskey = whiskeyApi.model('Whiskey', { 'name': fields.String(required=True, description='The name of the whiskey'), 'proof': fields.Float(required=True, description='The proof of the whiskey'), 'price': fields.Float(required=True, description='The price of the whiskey'), 'style': fields.String(required=True, description='The style of whiskey'), 'age': fields.Integer(required=True, description='The age of the whiskey'), 'icon': fields.Url(required=False, absolute=True, description='The url for the whiskey icon'), 'url': fields.Url(required=False, absolute=True, description='The original url for the whiskey icon') }) dbm = datastore.DbManager(testMode=False) getAllParser = whiskeyApi.parser() getAllParser.add_argument('currentPage', type=int, required=True, default=1, help='Current page of the query, count starts at 1') getAllParser.add_argument('itemsPerPage', type=int, required=True, default=20, help='Number of items returned per page, max=100') getAllParser.add_argument('sortField', type=str, required=False, default='name', help='The name of the field to sort on: name, price, proof, style, or age') getAllParser.add_argument('namesOnly', type=boolean, required=False, default=False, help='Return just a list of Whiskey names') getParser = whiskeyApi.parser() getParser.add_argument('name', type=str, required=True, help='The name of the whiskey')
from flask_restplus import Resource, fields, reqparse, Namespace from flask import request todonamespace = Namespace("TODO's", description='To play with Dictonary') parselevel=reqparse.RequestParser() parselevel.add_argument('todo_id', type=str, required=True) parselevel.add_argument('todo_data', type=str, required=True) model = todonamespace.model('postInput', { 'todo_id': fields.String, 'todo_data': fields.String }) todos={} @todonamespace.route('/todos') class TodoSimple(Resource): @todonamespace.response(201, 'accepted') @todonamespace.response(400, 'Bad request') @todonamespace.response(500, 'Internal server error') @todonamespace.response(404, 'Not found') @todonamespace.response(403, 'Unauthorized') @todonamespace.expect(model) def post(self): payload = request.get_json() print(payload) key = payload.get('todo_id')
description='creation timestamp'), 'expire_date': crb_fields.DateTime(dt_format='iso8601', description='expire date'), } Group = api.model('Group', { 'href': crb_fields.href('.group'), 'id': _group_fields['id'], 'name': _group_fields['name'], 'visibility': _group_fields['visibility'], 'description': _group_fields['description'], 'created_at': _group_fields['created_at'], 'expire_date': _group_fields['expire_date'], 'contexts': base_fields.List( crb_fields.Constant(ctype='Spread'), description='Visible in these contexts'), 'moderators': crb_fields.href( '.group-moderators', description='URL to the resource containing group moderators'), 'members': crb_fields.href( '.group-members-list', description='URL to the resource containing group members'), }) PosixGroup = api.model('PosixGroup', { 'href': crb_fields.href('.posixgroup'), 'id': _group_fields['id'], 'posix': base_fields.Boolean(
from flask_restplus import Namespace, fields root_api = Namespace('root', description='root') error_fields = root_api.model('Error', {'message': fields.String})
GPIOPin(22), GPIOPin(29), GPIOPin(31), GPIOPin(33), GPIOPin(35), GPIOPin(11), GPIOPin(13), GPIOPin(15), GPIOPin(12), ] api = Namespace('gpio') gpio_model = api.model('gpio_pin', { 'channel': fields.Integer(required=True), 'value': fields.Integer(required=True), 'direction': fields.String(enum=('in', 'out'), required=True), }) @api.route('/') class GPIOListResource(Resource): @api.marshal_with(gpio_model, as_list=True) def get(self): """ List of GPIO pins """ return PINS parser = reqparse.RequestParser() parser.add_argument('direction', type=str, choices=['in', 'out'], location='values') parser.add_argument('value', type=int, choices=[1, 0], location='values') @api.route('/<int:channel>')
from project import bcrypt from project.apis.users.models import User from project.apis.users.services import create_user, get_user_by_email, get_user_by_id api = Namespace("auth", description="Authorisation resource") EMAIL_REGEX = re.compile(r"\S+@\S+\.\S+") REGISTER = api.model( "REGISTER", { "id": fields.String( readOnly=True, description="The user identifier", example="1" ), "email": fields.String( required=True, description="A valid email address", example="*****@*****.**", ), }, ) LOGIN = api.inherit( "LOGIN", REGISTER, { "password": fields.String( required=True, description="A strong password", example="Xy67!abc" ) },
from flask_restplus import Namespace, Resource, fields from mongoengine import ValidationError from flask import request from .models import Movie api = Namespace("movies", description="Movies related operations.") movie_fields = api.model( "Movie", { "id": fields.String(readonly=True), "title": fields.String(required=True), "releaseDate": fields.Date(attribute="release_date"), "actors": fields.List(fields.String(required=True)), "genres": fields.List(fields.String(required=True)), "sumOfMarks": fields.Integer(readonly=True, attribute="sum_of_marks"), "numberOfMarks": fields.Integer(readonly=True, attribute="number_of_marks") }) mark_data_fields = api.model( "Mark Data", {"mark": fields.Integer(required=True, min=1, max=100, example=75)}) movie_action_fields = api.model( "Movie Action", { "type": fields.String(required=True, example="rate"), "data": fields.Nested(mark_data_fields, required=True) })
return 'Home: no user login yet', 200 return "User Home: " + current_user.username, 200 @api.route('/support') class Home(Resource): def get(self): return "Please contact [email protected]; [email protected]", 200 book_ns = Namespace("book", description="Book operations") book_marshaller = book_ns.model( 'Book_Query', { 'title': fields.String(), 'category': fields.String(), 'author': fields.String(), 'year': fields.Integer() }) new_book_marshaller = book_ns.model( 'BookModel', { 'id': fields.Integer(), 'title': fields.String(), 'category': fields.String(), 'author': fields.String(), 'year': fields.Integer() }) query_parser = reqparse.RequestParser() query_parser.add_argument('title', type=str, required=False)
import datetime import json from flask.ext.jwt import current_identity, jwt_required from flask_restplus import Namespace, Resource, fields, reqparse from packr.models import Order, OrderStatus, StatusType api = Namespace('update', description='Operations related to updating an order') update_status = api.model('UpdateStatus', { 'con_number': fields.Integer(readOnly=True, description='The consignment number'), 'status': fields.String(readOnly=True, description='The new status') }) update_driver = api.model('UpdateDriver', { 'con_number': fields.Integer(readOnly=True, description='The consignment number'), 'adminComments': fields.String(readOnly=True, description='The admin comments') }) update_admin = api.model('UpdateAdmin', { 'con_number': fields.Integer(readOnly=True, description='The consignment number'), 'driver': fields.String(readOnly=True, description='The driver'), 'eta': fields.String(readOnly=True,
from flask_restplus import Namespace, fields, Resource from flask_jwt_extended import (create_access_token, create_refresh_token) from flask import request from models import db from models.user import User from utils.validation_checker import is_password_invalid, is_email_invalid api = Namespace('users', description="User sign up") # Swagger params _signup_request = api.model( 'signup', { 'email': fields.String(required=True, description='Email Address'), 'name': fields.String(required=True, description='Name'), 'password': fields.String(required=True, description='Password'), }) _signup_response = api.model( 'signup-response', { 'jwt': fields.String(required=True, description='Access token for the user'), 'refresh_token': fields.String(required=True, description='Refresh token for the user') }) @api.route('') class SignUp(Resource): @api.expect(_signup_request, validate=True) @api.response(code=201, model=_signup_response,
def list_email_addresses(ea): if not isinstance(ea, Email.EmailAddress): ea = find_email_address(ea) et = Email.EmailTarget(db.connection) et.find(ea.email_addr_target_id) return map(lambda (lp, dom, _a_id): {'value': '{}@{}'.format(lp, dom), 'type': et.get_target_type()}, et.get_addresses()) EmailAddress = api.model('EmailAddress', { 'value': fields.base.String( description='The email address'), 'type': fields.Constant( ctype='EmailTarget', description="Email address type, i.e. 'forward', 'target'") }) EmailAddresses = api.model('EmailAddresses', { 'addresses': fields.base.List( fields.base.Nested(EmailAddress), description='List of addresses'), }) @api.route('/<string:address>', endpoint='emailaddresses') @api.doc(params={'address': 'Email address'}) class EmailAddressesResource(Resource): """Resource for listing email addresses."""
from flask_restplus import Namespace, Resource, fields api = Namespace('cats', description='Cats related operations') cat = api.model( 'Cat', { 'id': fields.String(required=True, description='The cat identifier'), 'name': fields.String(required=True, description='The cat name'), }) CATS = [ { 'id': 'felix', 'name': 'Felix' }, ] @api.route('/') class CatList(Resource): @api.doc('list_cats') @api.marshal_list_with(cat) def get(self): """ List all cats """ return CATS @api.route('/<id>') @api.param('id', 'The cat identifier') @api.response(404, 'Cat not found') class Cat(Resource):
api = Namespace('quote', description='Operations related to generating a quote') quote = api.model('Quote', { 'businessName': fields.String(readOnly=True, description='The name of the business'), 'contactName': fields.String(readOnly=True, description='The contact name'), 'phone': fields.String(readOnly=True, description='The phone number'), 'email': fields.String(readOnly=True, description='The email address'), 'type': fields.String(readOnly=True, descriptuon='The service type'), 'dangerous': fields.String(readOnly=True, description='The danger type, if applicable'), 'street': fields.String(readOnly=True, description='The street name and number'), 'suburb': fields.String(readOnly=True, description='The suburb name'), 'state': fields.String(readOnly=True, description='The state'), 'postCode': fields.Integer(readOnly=True, description='The postal code'), 'packages': fields.String(readOnly=True, description='A JSON map of the packages') }) @api.route('/') class QuoteItem(Resource):
import json from flask import jsonify, request from flask_restplus import Resource, Namespace, fields from modules.apis.util import model_result_set_to_json from modules.services.order import OrderService ns = Namespace('orders') order_model = ns.model( 'Order', { 'order_id': fields.Integer, 'original_price': fields.Float, 'final_price': fields.Float, 'order_id': fields.Integer, 'user_id': fields.Integer }) @ns.route('/') class Orders(Resource): @ns.marshal_list_with(order_model) def get(self): """Get all orders""" svc = OrderService() return svc.get_all() @ns.route('/listings/<string:listing_id>') class OrdersByListing(Resource): @ns.marshal_list_with(order_model) def get(self, listing_id):
def test_model(self): api = Namespace('test') api.model('Person', {}) self.assertIn('Person', api.models)
from datetime import datetime from flask_restplus import Namespace, Resource from sqlalchemy import and_, cast, func from sqlalchemy.dialects.postgresql import ARRAY from manifesto.database.models import db from manifesto.database.models.manifesto import Manifesto from manifesto.database.models.proposal import Proposal from manifesto.database.schemas.proposal import serializer, simple_serializer from manifesto.api.utils import bloom_intersection import random ns = Namespace('proposals', description='Proposal related operations') proposal = ns.model('Proposal', serializer) simple_proposal = ns.model('Proposal', simple_serializer) date_type = lambda x: datetime.strptime(x, '%Y-%m-%d').date() parser = ns.parser() parser.add_argument('political_party', type=str, help='Political party') parser.add_argument('election_type', type=str, help='Election type') parser.add_argument('geographical_area', type=str, help='Geographical area') parser.add_argument('election_date', type=date_type, help='Election type with format YYYY-M-DD') parser.add_argument('topics', type=str, help='Topics: search if the topics exist') parser.add_argument('tags', type=str, help='Tags (comma separated values)')
api = Namespace('vocterm', description='VocTerm module operations') # Define the API for fields that you can search by vocterm_parser = reqparse.RequestParser() vocterm_parser.add_argument('_term_key') vocterm_parser.add_argument('_vocab_key') vocterm_parser.add_argument('vocab_name') vocterm_parser.add_argument('id') vocterm_parser.add_argument('creation_date') vocterm_parser.add_argument('modification_date') vocterm_model = api.model('VocTerm', { '_term_key': fields.Integer, '_vocab_key': fields.Integer, 'vocab_name': fields.String, 'id': fields.String, 'creation_date': fields.DateTime, 'modification_date': fields.DateTime }) voctermemaps_parser = reqparse.RequestParser() voctermemaps_parser.add_argument('emapsid') voctermemaps_parser.add_argument('_term_key') voctermemaps_parser.add_argument('_emapa_term_key') voctermemaps_parser.add_argument('_stage_key') voctermemaps_model = api.model('VocTermEMAPS', { 'emapsid': fields.String, '_term_key': fields.Integer, '_emapa_term_key': fields.Integer, '_stage_key': fields.Integer,
from flask_restplus import Namespace, Resource, fields from flask import request from .lists.bubble_sort import bubble_sort api = Namespace('Lists', description='List related operations') lists = api.model( 'List', { 'function': fields.String(description='The name of the operation'), 'output': fields.String(description='The output of the operation') }) class Output(object): def __init__(self, output, function): self.output = output self.function = function @api.route('/bubble_sort', methods=['POST']) @api.param('input', 'The list input', _in='body') @api.response(404, 'Resource not found') class BubbleSort(Resource): @api.doc('list_bubble_sort') @api.marshal_with(lists) def post(self): """ Uses bubble sort on a list. Bubble_sort uses the technique of comparing and swapping.
account = utils.get_account(identifier=identifier, idtype=idtype, actype='PosixUser') except utils.EntityLookupError: account = utils.get_account(identifier=identifier, idtype=idtype) except utils.EntityLookupError as e: abort(404, message=str(e)) return account AccountAffiliation = api.model('AccountAffiliation', { 'affiliation': fields.Constant( ctype='PersonAffiliation', description='Affiliation name'), 'priority': fields.base.Integer( description='Affiliation priority'), 'ou': fields.base.Nested( models.OU, description='Organizational unit'), }) AccountAffiliationList = api.model('AccountAffiliationList', { 'affiliations': fields.base.List( fields.base.Nested( AccountAffiliation), description='Account affiliations'), }) Account = api.model('Account', { 'href': fields.href('.account'), 'name': fields.base.String(
from flask import request from flask_restplus import Namespace, Resource, fields from api.utils import validator from api.service.community_comment import create_community_comment import json api = Namespace('community_comments', description='Community comments CRUD operations') community_comment_schema = api.model('CommunityComment', { 'comment_id': fields.Integer(required=False, description='Id of this comment', readonly=True), 'comment': fields.String(required=True, description='Content of the comment'), 'like_count': fields.Integer(required=False, description='Number of like on this comment', readonly=True), 'user_id': fields.Integer(required=True, description='Id of the user who post this comment'), 'username': fields.String(required=False, description='Username of the user who post this comment', readonly=True), 'user_image': fields.Integer(required=False, description='User image id of the user who post this comment', readonly=True), 'question_id': fields.Integer(required=True, description='Id of the question concerned by this comment'), 'date': fields.String(required=False, description='String who represent the datetime of the post of this comment', readonly=True), 'user_like_status': fields.Integer(required=False, description='If ask, indicate if the user like this post (1 like, -1 unlike, 0 neutral)', readonly=True) }) @api.route("/") class CommunityCommentsRoute(Resource): @api.expect(community_comment_schema, envelope='json') @api.doc(responses={ 201: 'Comment successfully created', 409: 'Conflict, Question not exist / User not exist', 422: 'Validation Error' })
from pwi import app # API Classes api = Namespace('mgitype', description='MGI Type module operations') # Define the API for fields that you can search by mgitype_parser = reqparse.RequestParser() mgitype_parser.add_argument('_mgitype_key') mgitype_parser.add_argument('name') mgitype_parser.add_argument('creation_date') mgitype_parser.add_argument('modification_date') mgitype_model = api.model('MGIType', { '_mgitype_key': fields.Integer, 'name': fields.String, 'creation_date': fields.DateTime, 'modification_date': fields.DateTime }) @api.route('/search', endpoint='mgitype-search-resource') class MGITypeSearchResource(Resource): mgitype_service = MGITypeService() @api.doc(description="Description for MGI Type Search") @api.expect(mgitype_parser) def get(self): """ Search MGIType """
# app/apis/tweets.py from flask_restplus import Namespace, Resource, fields from app.db import tweet_repository api = Namespace('tweets') model = api.model('Model', { 'id': fields.Integer, 'text': fields.String, 'created_at': fields.DateTime }) @api.route('/<int:id>') @api.response(404, 'Tweet not found') class Tweet(Resource): @api.marshal_with(model) def get(self, id): tweet = tweet_repository.get(id) if tweet is None: api.abort(404) else: return tweet
from flask_restplus import Namespace, Resource, abort from Cerebrum.rest.api import db, auth, fields from Cerebrum import Errors from Cerebrum.Entity import EntitySpread api = Namespace('contexts', description='Context operations') # Model for data from EntitySpread.list_spreads() Context = api.model('Context', { 'context': fields.base.String( attribute='spread', description='Context name'), 'description': fields.base.String( description='Context description'), 'entity_type': fields.Constant( ctype='EntityType', attribute='entity_type', description=''), }) @api.route('/', endpoint='contexts') class ContextListResource(Resource): """Resource for contexts.""" context_search_filter = api.parser() context_search_filter.add_argument( 'entity_types', type=str, action='append', help='Filter by entity type(s)')
from flask import Flask, request, jsonify, make_response from flask_restplus import Api, Resource, fields,Namespace from sklearn.externals import joblib import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier name_space = Namespace('englandoutcome', description='Prediction APIs') model = name_space.model('Prediction params', {'HomeTeam': fields.String(required = True, description="Home Team", help="Home Team Field cannot be blank"), 'AwayTeam': fields.String(required = True, description="Away Team", help="Away Team Field cannot be blank"), 'Season': fields.String(required = True, description="Season", help="Season Field cannot be blank")}) classifier = joblib.load('/home/mardim/diploma_app/ML-React-App-Template/service/apis/finalized_model.sav') teams_df = pd.read_csv('/home/mardim/diploma_app/ML-React-App-Template/service/apis/teams.csv') x_test = pd.read_csv('/home/mardim/diploma_app/ML-React-App-Template/service/apis/test_df_england.csv') x_train = pd.read_csv('/home/mardim/diploma_app/ML-React-App-Template/service/apis/train_df_england.csv') selected_features = ['away_ma_sqrt_shotons', 'away_ca_corners', 'away_ca_pow2_corners', 'away_ca_sqrt_corners', 'away_ma_rcards', 'away_ca_rcards', 'away_ca_pow2_rcards', 'away_ma_sqrt_rcards', 'away_ca_sqrt_rcards', 'away_ca_possessions', 'away_ca_sqrt_possessions', 'home_elo_rate', 'home_ca_goals', 'home_ca_pow2_goals', 'home_ca_sqrt_goals', 'home_ca_shotons', 'home_ma_shotoffs', 'home_ma_pow2_shotoffs', 'home_ca_fouls', 'home_ca_pow2_fouls', 'home_ca_sqrt_fouls', 'home_ca_ycards', 'home_ca_pow2_ycards', 'home_ca_sqrt_ycards', 'home_ma_pow2_rcards', 'home_ca_pow2_rcards', 'home_ma_sqrt_rcards', 'home_ma_possessions']
from flask_jwt import _jwt_required, JWTError, current_identity from flask_restplus import Api, Resource, Namespace, fields from cassandra.cqlengine.query import BatchQuery from werkzeug.utils import secure_filename from datetime import datetime from dateutil import parser from ..model import Line api = Namespace('lines', description='Line distribution and consumption') prop_model = api.model('Properties', { 'trip_id': fields.String(description='Trip UUID'), 'username': fields.String(description='username'), 'start_at': fields.DateTime(description='Time of first point'), 'end_at': fields.DateTime(description='Time of last point'), }) geom_model = api.model('Geometry', { 'type': fields.String(description='Geometry type'), 'coordinates': fields.List(fields.List( fields.Float, description=('lon, lat pair'))) }) line_model = api.model('Line', { 'type': fields.String(description='GeoJSON type'), 'geometry': fields.Nested(geom_model), 'properties': fields.Nested(prop_model) })
academy_parser = reqparse.RequestParser() academy_parser.add_argument('courseId', help='{error_msg}') academy_parser.add_argument('courseHandle', help='{error_msg}') academy_course_update_parser = reqparse.RequestParser() academy_course_update_parser.add_argument('id', help='{error_msg}') academy_course_update_parser.add_argument('activeStep', type=int, help='{error_msg}') academy_course_save_parser = reqparse.RequestParser() academy_course_update_parser.add_argument('id', help='{error_msg}') academy_course_save_parser.add_argument('data', help='{error_msg}') course = api.model('Course', { 'id': fields.String(required=True, description='The course identifier'), }) categories, courses = main() fa = FirestoreAcademy() @api.route('/categories') class AcademyCategories(Resource): @api.doc('get_categories') def get(self): # need backend to generate categories return categories, 200, { 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Methods": "GET" }
def test_model(self): api = Namespace('test') api.model('Person', {}) assert 'Person' in api.models assert isinstance(api.models['Person'], Model)
from karmapi import base from flask import request from flask_restplus import Namespace, Resource, fields api = Namespace("euro", description="api for euro") from karmapi.meta.weather import Image Image = api.model("Image", Image) @api.route('/locations/<location>/<item>') class location(Resource): """ Rough notes on how to plot centred on a location using basemap What I really want to do is implement a Karma Pi path something like this: locations/{location}/{item} That will show you {item} from location's point of view. Now {item} works best if it does not have any /'s, so for the item parameter we'll convert /'s to ,'s and see how that looks. The idea is {item} will be a path to something in Karma Pi. So here is how it might go:
from flask_restplus import Namespace, Resource, fields from werkzeug.datastructures import FileStorage from config import MODEL_META_DATA from core.backend import ModelWrapper, read_image api = Namespace('model', description='Model information and inference operations') model_meta = api.model('ModelMetadata', { 'id': fields.String(required=True, description='Model identifier'), 'name': fields.String(required=True, description='Model name'), 'description': fields.String(required=True, description='Model description'), 'license': fields.String(required=False, description='Model license') }) @api.route('/metadata') class Model(Resource): @api.doc('get_metadata') @api.marshal_with(model_meta) def get(self): '''Return the metadata associated with the model''' return MODEL_META_DATA label_prediction = api.model('LabelPrediction', { 'label_id': fields.String(required=False, description='Label identifier'), 'label': fields.String(required=True, description='Class label'), 'probability': fields.Float(required=True) }) predict_response = api.model('ModelPredictResponse', {
from flask import request from flask_restplus import Namespace, Resource, fields import jwt from application.api.users.services import get_user_by_email, get_user_by_id, add_user from application.api.users.models import User from application import bcrypt auth_namespace = Namespace("auth") user = auth_namespace.model( "User", { "username": fields.String(required=True), "email": fields.String(required=True) }, ) full_user = auth_namespace.inherit("Full User", user, {"password": fields.String(required=True)}) login = auth_namespace.model( "User", { "email": fields.String(required=True), "password": fields.String(required=True), }, ) refresh = auth_namespace.model("Refresh", {"refresh_token": fields.String(required=True)})
from Cerebrum import Errors from Cerebrum.rest.api import db, auth, validator from Cerebrum.rest.api import fields as crb_fields from Cerebrum.rest.api.v1 import models api = Namespace('search', description='Search operations') ExternalIdItem = api.model( 'ExternalIdItem', { 'href': crb_fields.href(endpoint='.person'), 'person_id': base_fields.Integer(description='Person ID', attribute='entity_id'), 'source_system': crb_fields.Constant(ctype='AuthoritativeSystem', description='Source system'), 'id_type': crb_fields.Constant(ctype='EntityExternalId', transform=models.ExternalIdType.serialize, description='External ID type'), 'external_id': base_fields.String(description='External ID value') }) @api.route('/persons/external-ids', endpoint='search-persons-external-ids') class ExternalIdResource(Resource): """Resource for external ID searches.""" # GET / #
from flask_restplus import fields, Resource, Namespace import controllers from block import blockchain from block.b_core import Block ns = Namespace(name='transaction', description='how to register a transaction for eocoin') post_transaction = ns.model( 'transaction', { 'from': fields.String( description='Who sent it', example='Billy', required=True), 'to': fields.String( description='Who received it', example='Greg', required=True), 'amount': fields.Integer( description='How much eo was given', example=200, required=True) }) post_transaction_success_response = ns.model( 'Success', { 'message': fields.String(description='transaction successful', example='transaction successful') }) my_transactions = []
from flask_restplus import Namespace, Resource, fields from flask import url_for from restplus import api import logging sampleApi = Namespace('sample', description='Sample') logger = logging.getLogger(__name__) sample = sampleApi.model('Sample', { 'id': fields.String(required=True, description='The sample identifier'), 'name': fields.String(required=True, description='The sample name'), }) SAMPLES = [ {'id': 'felix', 'name': 'Felix'}, ] @api.route('/') class SampleList(Resource): @api.doc('list_samples') @api.marshal_list_with(sample) def get(self): '''List all samples''' return SAMPLES @api.route('/<id>') @api.param('id', 'The sample identifier') @api.response(404, 'Sample not found') class Sample(Resource):
from flask import request from flask_restplus import Resource, Namespace, fields ns_messages = Namespace('Messages', description='Handles message actions') m_model = ns_messages.model( 'harbinger_message', { 'topic': fields.String(description='Topic name'), 'date_added': fields.DateTime(description=''), 'payload': fields.String( desciption= 'The body of the message for the consumer to do something with'), 'expiration_date': fields.DateTime(description='') }) @ns_messages.route('') class HarbingerMessageList(Resource): @ns_messages.doc(responses={200: 'Success'}) @ns_messages.doc(responses={404: 'Newer message for topic not found'}) @ns_messages.doc(responses={500: 'Server error'}) def get(self): """Returns list of newer messages for the provided topic""" # TODO: Flesh out return 'Newer message for topic not found' @ns_messages.doc(responses={201: 'Message created'})
from flask import session from flask.globals import request from flask_restplus import Resource, Namespace from flask_restplus import fields from son_editor.impl import workspaceimpl from son_editor.impl.private_catalogue_impl import get_private_nsfs_list from son_editor.util.constants import WORKSPACES, SERVICES, VNFS from son_editor.util.requestutil import prepare_response, get_json namespace = Namespace(WORKSPACES, description="Workspace Resources") logger = logging.getLogger(__name__) rep = namespace.model("Repository", { 'name': fields.String(required=True, description='The Repository Name'), 'url': fields.Url(required=True, description='The Repository URL') }) ws = namespace.model("Workspace", { 'name': fields.String(required=True, description='The Workspace Name'), "catalogues": fields.List(fields.Nested(rep)), "platforms": fields.List(fields.Nested(rep)) }) ws_response = namespace.inherit("WorkspaceResponse", ws, { "path": fields.String(description='The Physical Workspace location'), "id": fields.Integer(description='The Workspace ID') }) descriptor_content = namespace.model("Descriptor Content", {})
from flask_restplus import Namespace, Resource, fields from cloudant.client import CouchDB from flask import request from app import config api = Namespace('Assets', description='asset managmenet operations') assets_location = api.model('location', {"value": fields.String}) assets = api.model( 'assets', { "_id": fields.String(required=True), "tid": fields.String, "location": fields.List(fields.Nested(assets_location)) }) """ CouchDB Connecntion initializeiton """ try: client = CouchDB(config.ASSETS_USER, config.ASSETS_PASSWD, url=config.ASSETS_URL, connect=True) session = client.session() mydb = client[config.ASSETS_DB] except: print("No DB Connection possible") @api.route('/') @api.response(404, 'Asset not found.')
import numpy as np from datetime import datetime from flask import request, current_app as app from flask_restplus import Namespace, Resource, fields logger = logging.getLogger(__name__) ns = Namespace( 'predict', description='mnist Prediction API') ResourceFields = ns.model('mnist Predictor Resource', { 'image': fields.List( fields.Integer, description='List of pixel intensities for image', required=True, min_length=1, ), }) Model = ns.model('mnist Predictor', { 'predictions': fields.List( fields.Raw, description='Probabilities for each number', required=True, min_length=1, ), }) @ns.route('/')
from flask_restplus import Resource, Namespace, reqparse, fields, marshal_with from .gpio import GPIO api = Namespace('version') version_model = api.model('version', { 'product': fields.String, 'rev': fields.String }) version_list = api.model('version_list', { 'host': fields.Nested(version_model), }) @api.route('/') class Version(Resource): @api.marshal_with(version_list) def get(self): return { 'host': {'product': 'raspberry_pi', 'rev': GPIO.RPI_INFO['P1_REVISION']}, }
'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'}) return Response('Web configuration was deactivated', 404) def requires_auth(f): def decorated(*args, **kwargs): auth = request.authorization if not auth or not check_auth(auth.username, auth.password): return authenticate() return f(*args, **kwargs) return decorated config_model = namespace.model("Config", {}) @namespace.route("") class Configuration(Resource): """ Web configuration """ @requires_auth def get(self): """ Show Configuration Show the current server configuration (requires authentication via Basic Auth) """ return prepare_response(get_config()) @namespace.expect(config_model) @namespace.doc("Update Configuration")
from flask_restplus import Namespace, fields, Resource api = Namespace('upload_training_images') # Swagger params _uti_request = api.model( 'Upload Training Images', { 'model_id': fields.Integer(required=True, description='Model Id'), 'src': fields.String(required=True, description='Source images folder path in s3 bucket'), 'label': fields.String(required=True, description='Image labels') }) @api.route('') class UploadTrainingImages(Resource): @api.expect(_uti_request, validate=True) def post(self): # TODO 1. Copy images from src to destination s3 folder # TODO 2. Store training label in DB return 200