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): api = Namespace('test') parent = api.model('Parent', {}) api.inherit('Child', parent, {}) self.assertIn('Parent', api.models) self.assertIn('Child', 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_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_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
import random from flask import current_app, request from flask_restplus import Namespace from sqlalchemy import desc from app import jobs, WebResponse from app.models.models import ProxyValid, ProxyRaw from app.models.proxy import Proxy from app.utils.base_resource import BaseResource from app.utils.db.redis_helper import RedisHelper from app.utils.web_responsecode import WebResponseCode from app.extension import db as sql log = logging.getLogger(__name__) nsproxy = Namespace('', description='代理接口') @nsproxy.route("/get") class ProxyGetController(BaseResource): def get(self): ''' 请求样例: /get /get?type=valid /get?type=raw :return: ''' # 是否需要未处理的数据 proxy_type = request.args.get('type') type = proxy_type if proxy_type else 'valid' response = WebResponse()
import requests from flask import current_app as app from flask import request from flask_jwt_extended import get_jwt_identity from flask_jwt_extended.exceptions import * from flask_restplus import Namespace, Resource from jwt.exceptions import * from .auth_controller import access_required api = Namespace('access', description='Namespace for method access service') _http_headers = {'Content-Type': 'application/json'} _es_index = 'pms_method_access_lookup' _es_type = 'access' _es_size = 100 mandatory_fields = ["access_code", "access_name", "access_group"] @api.errorhandler(NoAuthorizationError) def handle_auth_error(e): return {'message': str(e)}, 401 @api.errorhandler(CSRFError) def handle_auth_error(e): return {'message': str(e)}, 401 @api.errorhandler(ExpiredSignatureError)
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,
def test_schema_model(self): api = Namespace('test') api.schema_model('Person', {}) assert 'Person' in api.models
from __future__ import division, absolute_import, print_function import numpy as np from flask_restplus import Namespace from flask_restplus import Resource from flask_restplus import fields from flask import jsonify from service.bad_image_service import get_image_prediction from service.very_bad_image_service import get_image_prediction as get_image_prediction2 api = Namespace(name='worse image', description='apis for filtering bad images') # The JSON Model for the data being sent by the user text_msg_model = api.model("text_msg_model", {"urls": fields.String("urls splitted by |")}) def prob_process(p1, p2): r_0 = p1[:, 1] r_non = p1[:, 0] r_1_3 = p2 * r_non[:, None] r = np.concatenate([r_0[:, None], r_1_3], axis=1) return r @api.route("/worse_image/") class WorseImage(Resource): """Resource The embedding generator """
import os from flask import request, jsonify, current_app 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),
def test_model(self): api = Namespace('test') api.model('Person', {}) assert 'Person' in api.models assert isinstance(api.models['Person'], Model)
def test_model(self): api = Namespace('test') api.model('Person', {}) self.assertIn('Person', api.models)
# -*- coding: utf-8 -*- """Private metric endpoints.""" from flask import request from flask_restplus import fields, Namespace, Resource from sqlalchemy import exc from dapp_store_backend.database import db from dapp_store_backend.models.metric import Metric api = Namespace('metric', description='Private metric endpoints.', path='/private/metric') metric_fields = api.model( 'Metric', { 'dapp_id': fields.Integer(required=True, description='ID for dapp.', example=1), 'users': fields.Integer( required=True, description='Unique users for a dapp.', example=99), 'volume': fields.Integer(required=True, description='Total volume for a dapp.', example=100000), 'transactions': fields.Integer(required=True, description='Total number of transactions for a dapp.', example=384) }) metric_list_fields = api.model(
from flask import request from flask_restplus import Namespace, Resource, fields from api.utils import validator from api.service.community_comment import modify_comment_likes import json api = Namespace('likes', description='Community comments CRUD operations') user_like_schema = api.model( 'CommentLike', { 'like_id': fields.Integer(required=False, description='Id of like', readonly=True), 'user_id': fields.Integer(required=True, description='User who make this like'), 'comment_id': fields.Integer(required=True, description='Liked comment id'), 'like_value': fields.Integer( required=True, description='Like value (1 ask for like, -1 ask for dislike)') }) @api.route("/") class LikesRoute(Resource): @api.expect(user_like_schema, envelope='json') @api.doc( responses={
''' Created on 22.07.2016 @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') })
from CTFd.models import db, Users, Solves, Awards, Fails, Tracking, Unlocks, Submissions, Notifications from CTFd.utils.decorators import (authed_only, admins_only, authed, ratelimit) from CTFd.cache import cache, clear_standings from CTFd.utils.config import get_mail_provider from CTFd.utils.email import sendmail from CTFd.utils.user import get_current_user, is_admin from CTFd.utils.decorators.visibility import check_account_visibility, check_score_visibility from CTFd.utils.config.visibility import (accounts_visible, challenges_visible, registration_visible, scores_visible) from CTFd.schemas.submissions import SubmissionSchema from CTFd.schemas.awards import AwardSchema from CTFd.schemas.users import UserSchema users_namespace = Namespace('users', description="Endpoint to retrieve Users") @users_namespace.route('') class UserList(Resource): @check_account_visibility def get(self): users = Users.query.filter_by(banned=False, hidden=False) response = UserSchema(view='user', many=True).dump(users) if response.errors: return {'success': False, 'errors': response.errors}, 400 return {'success': True, 'data': response.data} @admins_only
from flask_restplus import Resource, Namespace, abort from ..service.species_service import * ns = Namespace( 'species', description= 'Returns user provided config information about the reference and ' 'comparison species.') @ns.route('/') class Species(Resource): @staticmethod def get(): data = get_all_species() if data is False: abort( 404, "No species data files containing species information could be found" ) return data, 200 @ns.route('/<int:species_id>') @ns.param( 'species_id', 'NCBI species ID, such as 9606 (H. sapiens), 10090 (M. musculus), etc.') class SpeciesById(Resource): @staticmethod def get(species_id):
from flask_restplus import fields, Namespace, Resource, reqparse from .SharedModel import db api = Namespace('Notes', description='Operations related to specific users notes') #Python notes class class Notes(object): def __init__(self, id, book_id, user_id, notes): self.id = id self.book_id = book_id self.user_id = user_id self.notes = notes #Notes API notes_api_model = api.model( "Notes", { 'id': fields.Integer(description='Notes ID'), 'book_id': fields.Integer(description='Book ID'), 'user_id': fields.Integer(description='User ID'), 'notes': fields.String(description='notes from the user regarding the book'), }) #Database model for notes
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 request, abort, url_for from flask_restplus import fields, Namespace, reqparse, Resource, Api from flask_login import current_user from mgipython.util import error_template from mgipython.model import * from mgipython.service import * from mgipython.service_schema import * from pwi import app # API Classes 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 })
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_parser(self): api = Namespace('test') assert isinstance(api.parser(), restplus.reqparse.RequestParser)
GPIOPin(37), GPIOPin(40), GPIOPin(7), GPIOPin(32), 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()
@author: Jonas ''' import logging from flask import request from flask_restplus import Model, Resource, Namespace, fields from son_editor.impl import platform_connector from son_editor.impl import servicesimpl, catalogue_servicesimpl from son_editor.impl.private_catalogue_impl import publish_private_nsfs from son_editor.util.constants import get_parent, Category, WORKSPACES, PROJECTS, CATALOGUES, PLATFORMS, SERVICES from son_editor.util.requestutil import prepare_response, get_json logger = logging.getLogger(__name__) proj_namespace = Namespace(WORKSPACES + '/<int:ws_id>/' + PROJECTS + "/<int:parent_id>/" + SERVICES, description="Project Service Resources") cata_namespace = Namespace(WORKSPACES + '/<int:ws_id>/' + CATALOGUES + "/<int:parent_id>/" + SERVICES, description="Catalogue Service Resources") plat_namespace = Namespace(WORKSPACES + '/<int:ws_id>/' + PLATFORMS + "/<int:parent_id>/" + SERVICES, description="Platform Service Resources") serv = Model("Service", { 'name': fields.String(required=True, description='The Service Name'), 'vendor': fields.String(required=True, description='The Service Vendor'), 'version': fields.String(required=True, description='The Service Version') }) serv_update = Model("Service Update", { "descriptor": fields.Nested(model=serv, description="The Complete Service Descriptor")
def test_ordered_model(self): api = Namespace('test', ordered=True) api.model('Person', {}) assert 'Person' in api.models assert isinstance(api.models['Person'], OrderedModel)
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:
import hmac from hashlib import sha1 from http import HTTPStatus from logging import getLogger from flask import request from flask_restplus import Namespace, Resource, fields from packit_service.celerizer import celery_app from packit_service.config import ServiceConfig from packit_service.service.api.errors import ValidationFailed logger = getLogger("packit_service") config = ServiceConfig.get_service_config() ns = Namespace("webhooks", description="Webhooks") # Just to be able to specify some payload in Swagger UI ping_payload = ns.model( "Github webhook ping", { "zen": fields.String(required=False), "hook_id": fields.String(required=False), "hook": fields.String(required=False), }, ) @ns.route("/github") class GithubWebhook(Resource): @ns.response(HTTPStatus.OK, "Webhook accepted, returning reply")
Created on 22.07.2016 @author: Jonas ''' from flask.globals import request, session from flask_restplus import Namespace, Model, fields from flask_restplus import Resource from werkzeug.utils import secure_filename from son_editor.app.exceptions import InvalidArgument from son_editor.impl import functionsimpl, catalogue_servicesimpl from son_editor.impl.private_catalogue_impl import publish_private_nsfs from son_editor.util.constants import get_parent, Category, WORKSPACES, PROJECTS, CATALOGUES, PLATFORMS, VNFS from son_editor.util.requestutil import prepare_response, get_json proj_namespace = Namespace(WORKSPACES + '/<int:ws_id>/' + PROJECTS + "/<int:parent_id>/" + VNFS, description="Project VNF Resources") cata_namespace = Namespace(WORKSPACES + '/<int:ws_id>/' + CATALOGUES + "/<int:parent_id>/" + VNFS, description="Catalogue VNF Resources") plat_namespace = Namespace(WORKSPACES + '/<int:ws_id>/' + PLATFORMS + "/<int:parent_id>/" + VNFS, description="Platform VNF Resources") funct = 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_uid = Model("VNF", { 'id': fields.String(required=True, description='The VNF UID'), 'name': fields.String(required=True, description='The VNF Name'),
#!../../../bin/python import logging import json 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')
# -*- coding: utf-8 -*- import json import os from elasticsearch_dsl import Q, A, Search from elasticsearch_dsl.query import Match from flask_restplus import reqparse, Resource, Api, fields, Namespace from .model import ApiModel from app.util.exceptionHandler import ExcepitonHandler from app.util.regToolBox import RegToolBox from app.model.userModel import User as UserModel from app.dao import daoPool fileDir = os.path.dirname(__file__) api = Namespace('users', description='user operation') apiModel = ApiModel(api) regBox = RegToolBox() excpHandler = ExcepitonHandler() sqlDAO = daoPool.sqlDAO ## Request Parsing parser = reqparse.RequestParser() parser.add_argument('username', required=True, help='name of user', location='args') parser.add_argument('email', required=False, help='email of user', location='args')
from flask import make_response, request from flask_restplus import Namespace, Resource, abort from Cerebrum.rest.api import db, auth, fields, utils from Cerebrum.rest.api.v1 import group from Cerebrum.rest.api.v1 import models from Cerebrum.rest.api.v1 import emailaddress from Cerebrum import Errors from Cerebrum.Utils import Factory from Cerebrum.QuarantineHandler import QuarantineHandler from Cerebrum.modules.pwcheck.checker import (check_password, PasswordNotGoodEnough) api = Namespace('accounts', description='Account operations') def find_account(identifier): idtype = 'entity_id' if identifier.isdigit() else 'name' try: try: 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
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'),
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, abort, url_for from flask_restplus import fields, Namespace, reqparse, Resource, Api from flask_login import current_user from mgipython.util import error_template from mgipython.model import MGIType from mgipython.service.mgitype_service import MGITypeService from mgipython.service_schema.search import SearchQuery 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):
@author: Jonas """ import logging 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'),
from flask_restplus import Namespace, Resource, fields from pyris.api import extract api = Namespace('insee', description='Some stats from INSEE for each IRIS') population_parser = api.parser() population_parser.add_argument("by", required=True, location='args', help="By sex or age") logement_parser = api.parser() logement_parser.add_argument("by", required=True, location='args', help="By room, area or year") activite_parser = api.parser() activite_parser.add_argument("by", required=True, location='args', help="By sex, age") @api.route('/') class InseeData(Resource): @api.doc(description='INSEE data list') def get(self): return ['population', 'activite', 'logement', 'menage', 'formation'] @api.route('/population/<string:code>') class IrisPopulation(Resource): @api.doc("get the population for an IRIS") def get(self, code): if len(code) != 9:
import logging 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, ), })
# You should have received a copy of the GNU General Public License # along with Cerebrum; if not, write to the Free Software Foundation, # Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ RESTful Cerebrum group API. """ from flask_restplus import Namespace, Resource, abort, reqparse from flask_restplus import fields as base_fields from werkzeug.exceptions import NotFound from Cerebrum.rest.api import db, auth, utils from Cerebrum.rest.api import fields as crb_fields from Cerebrum.rest.api import validator from Cerebrum import Errors from Cerebrum.Utils import Factory api = Namespace('groups', description='Group operations') def find_group(identifier, idtype='name'): if idtype == 'name' and isinstance(identifier, unicode): identifier = identifier.encode(db.encoding) try: try: group = utils.get_group(identifier=identifier, idtype=idtype, grtype='PosixGroup') except utils.EntityLookupError: group = utils.get_group(identifier=identifier, idtype=idtype) except utils.EntityLookupError as e: raise NotFound(str(e)) return group
from flask_restplus import Resource, Namespace, fields from son_editor.util.requestutil import get_config, update_config from flask import request, Response from son_editor.util.requestutil import prepare_response, get_json namespace = Namespace("config", description="Configuration") def check_auth(username, password): """This function is called to check if a username / password combination is valid. """ if 'config' in get_config(): if 'user' in get_config()['config'] and 'pwd' in get_config()['config']: return username == get_config()['config']['user'] and password == get_config()['config']['pwd'] return False def authenticate(): """Sends a 401 response that enables basic auth""" if 'config' in get_config(): if 'user' in get_config()['config'] and 'pwd' in get_config()['config']: return Response( 'Could not verify your access level for that URL.\n' '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):
from flask_restplus import Resource, Namespace, fields, reqparse from resources.predict_risk import _code_parser from model.files import ASSOCIATE_PATH, FAMILY_PATH, CROSS_PATH from werkzeug.exceptions import NotFound import tushare as ts import json api = Namespace('Graph', description='网络图') def get_json_file(filepath): if not filepath.is_file(): raise NotFound('no such company!') with open(filepath, 'rb') as f: result = json.load(f) return result @api.route('/family') class Family(Resource): @api.expect(_code_parser) def post(self): args = _code_parser.parse_args() code = args['code'] file = FAMILY_PATH.joinpath(code + '.json') return get_json_file(file)