示例#1
0
import pytz
from flask import request, abort
from flask_restplus import Namespace, Resource, reqparse
from .core.database import Database
from .core.marshmallow_models import NodeSchema, NewNodeSchema, EditNodeSchema, DatumSchema, NodeTypeSchema, EditNodeTypeSchema, NewNodeTypeSchema
from .core.swagger_models import node, data, datum, node_type, sensor, link, date_array, new_node, new_datum
from .core.utils import token_required
from dateutil import parser as date_parser
from datetime import datetime
from marshmallow import Schema
from functools import reduce

api = Namespace('nodes', description='Node related operations')

# Swagger schemas
node = api.schema_model('Node', node)
new_node = api.schema_model('InputNode', new_node)
data = api.schema_model('Data', data)
datum = api.schema_model('Datum', datum)
new_datum = api.schema_model('InputDatum', new_datum)
node_type = api.schema_model('Node-Type', node_type)
sensor = api.schema_model('Sensor', sensor)
link = api.schema_model('Link', link)
date_array = api.schema_model('DateArray', date_array)


@api.route('/types/add')
class AddNodeType(Resource):
    @api.doc(summary='Add new node types',
             description='Add new node types',
             responses={201: 'Node type added successfully'},
示例#2
0
def get_public_account(msg: bytes):
    return get_account_id(public_key=hashlib.sha256(msg).hexdigest())


# Namespaces
ns_stamp = Namespace(
    'timestamp',
    description=
    'Timestamp on the nano network! Input is utf-8 encoded and sha256 hashed, then sent to that nano address'
)
string_stamp_model = ns_stamp.schema_model(
    'string_timestamp', {
        "$schema": "http://json-schema.org/schema#",
        "type": "object",
        "properties": {
            "target_string": {
                "type": "string"
            }
        },
        "required": ["target_string"],
        "additionalProperties": False
    })


@ns_stamp.route('/string/')
class TimeStampJson(Resource):
    @ns_stamp.doc('timestamp')
    @ns_stamp.expect(string_stamp_model)
    def post(self):
        target_string = request.get_json()['target_string']
        try:
            target_account = get_public_account(target_string.encode('utf-8'))
示例#3
0
    https://marshmallow.readthedocs.io/en/latest/
"""

import jwt
import os
import bcrypt
from flask import request, abort
from flask_restplus import Namespace, Resource, reqparse
from .core.swagger_models import user
from .core.marshmallow_models import UserSchema
from .core.database import Database
from .core.utils import token_required
from datetime import datetime, timedelta

api = Namespace('login', description='login operations')
user = api.schema_model('User', user)


# Receives a valid user and password and then provide a token to access the
# protected routes across the application.
@api.route('/')
class Login(Resource):
    @api.doc(summary='Login to the API', responses={200: 'Login successful'})
    @api.expect(user)
    def post(self):
        user, errors = UserSchema().load(request.get_json(force=True) or {})
        if not errors:
            u = Database().get_user(user['username'])
            if u and bcrypt.checkpw(user['password'].encode('utf-8'),
                                    u['password']):
                # The token expires in one day
示例#4
0
from flask import Blueprint, jsonify
from flask_restplus import Resource, Namespace, reqparse
from app.meep_api.models.waveguide import Waveguide
from app.meep_api.models.json.waveguide import waveguide_json_model
from app.meep_api.models.folder_manager import FolderManager

waveguides = Blueprint('waveguides', __name__)

waveguide_api = Namespace('waveguides',
                          description='Simple waveguides endpoints')
waveguide_model = waveguide_api.schema_model('Waveguide Model',
                                             waveguide_json_model)


@waveguide_api.route('/straight-waveguide')
class StraightWaveguide(Resource):
    @waveguide_api.doc(
        'Returns test text and computes of e/m wave propagation in straight waveguide'
    )
    @waveguide_api.expect(waveguide_model)
    @waveguide_api.param('waveguide_type',
                         'Describing waveguide type selected at the beginning')
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('data', type=dict)
        parser.add_argument('waveguide_type', type=str)
        args = parser.parse_args()

        waveguide_type = 'straight'  #args['waveguide_type']
        del args['waveguide_type']
示例#5
0
 def test_schema_model(self):
     api = Namespace('test')
     api.schema_model('Person', {})
     self.assertIn('Person', api.models)
示例#6
0
from flask_restplus import Resource, Namespace, reqparse
from flask import jsonify
from app.meep_api.models.json.cell import cell_json_model

cell_api = Namespace("cell", description="Cell actions")

cell_model = cell_api.schema_model('Cell Model', cell_json_model)


@cell_api.route('/set', methods=["post"])
class Set(Resource):
    @cell_api.doc('Sets cell')
    @cell_api.expect(cell_model)
    @cell_api.param('waveguide_type',
                    'Describing waveguide type selected at the beginning')
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('x', type=int)
        parser.add_argument('y', type=int)
        parser.add_argument('z', type=int)
        parser.add_argument('waveguide_type', type=str)
        args = parser.parse_args()

        waveguide_type = args['waveguide_type']
        del args['waveguide_type']

        return jsonify(cell=args, waveguide_type=waveguide_type)
示例#7
0
from flask_restplus import Resource, Namespace, reqparse
from flask import jsonify
from app.meep_api.models.waveguide import Waveguide
from app.meep_api.models.json.geometry import geometry_json_model
from app.meep_api.models.preview import Preview as GeometryPreview

geometry_api = Namespace("geometry", description="Geometry actions")

geometry_model = geometry_api.schema_model('Geometry Model',
                                           geometry_json_model)


@geometry_api.route('/set')
class Set(Resource):
    @geometry_api.doc('Sets geometry for straight waveguide')
    @geometry_api.expect(geometry_model)
    @geometry_api.param('waveguide_type',
                        'Describing waveguide type selected at the beginning')
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('coordinates', type=dict)
        parser.add_argument('center', type=dict)
        parser.add_argument('material', type=int)
        parser.add_argument('waveguide_type', type=str)
        args = parser.parse_args()

        waveguide_type = args['waveguide_type']
        del args['waveguide_type']

        return jsonify(geometry=args, waveguide_type=waveguide_type)
示例#8
0
from core.models import puntos as TablaPuntajes
from core.models import Usuarios as TablaUsuarios
from datetime import datetime
from core.database import db

api = Namespace('puntajes', description='Operaciones sobre los puntajes')

puntaje = usuario = api.schema_model(
    'Puntaje', {
        'type': 'object',
        'properties': {
            'usuario': {
                '$ref': '#/definitions/usuario'
            },
            'Puntaje': {
                'type': 'number',
                'description': 'La puntuación de un usuario',
                'example': 9999999
            },
        },
        'Fecha': {
            'type': 'string',
            'description': 'Fecha en el que se registró el puntaje'
        }
    })


@api.route('/')
class Puntajes(Resource):
    @api.doc(summary='Obtener todos los puntajes',
             responses={200: ('Lista de puntajes', [puntaje])})
    def get(self):
示例#9
0
# Environmental variables
# Init app
app = Flask(__name__)
CORS(app)
api = Api(app,
          version='1.0',
          title='Bionet Index',
          description='Bionet Index 1 try')

ns_blast = Namespace('blast', description='Blast on the Bionet')
blast_model = ns_blast.schema_model(
    'blast_seq', {
        "type": "object",
        "properties": {
            "search_sequence": {
                "type": "string"
            }
        },
        "required": ["search_sequence"],
        "additionalProperties": False
    })


@ns_blast.route('/')
class BlastRoute(Resource):
    @ns_blast.doc('blast')
    @ns_blast.expect(blast_model)
    def post(self):
        f = open("files/test_query.fa", "w")
        f.write("> Query Sequence")
        f.write("\n")
示例#10
0
########################
# The different models #
########################
GENES_NS = Namespace('genes', 'Comorbidities related genes')

simple_gene_model = GENES_NS.model(
    'SimpleGene', {
        'symbol': fields.String(required=True, description='The gene symbol'),
    })

simple_gene_model_schema = GENES_NS.schema_model(
    'SimpleGene', {
        'properties': {
            'symbol': {
                'type': 'string',
                'description': 'The gene symbol'
            }
        },
        'type': 'object',
        'required': ['symbol']
    })

gene_model = GENES_NS.model(
    'Gene', {
        'symbol': fields.String(required=True, description='The gene symbol'),
        'ensembl_id': fields.String(description='The EnsEMBL gene id'),
        'uniprot_acc':
        fields.String(description='The UniProt Accession Number')
    })

gene_model_schema = GENES_NS.schema_model(
示例#11
0
logger = logging.getLogger(__name__)

api = Namespace('projects', decorators=[jwt_decoder])

default_response = api.model('DefaultAgaveResponse', {
    "message": fields.String(),
    "version": fields.String(),
    "status": fields.String(default="success")
})

ok_response = api.model('OkResponse', {
    "message": fields.String(default="accepted")
})

feature_schema = api.schema_model('Feature', FeatureSchema)

asset = api.model('Asset', {
    "id": fields.Integer(),
    "path": fields.String(),
    "uuid": fields.String(),
    "asset_type": fields.String(),
    "original_path": fields.String(),
    "original_name": fields.String(),
    "display_path": fields.String()
})

api_feature = api.model('Feature', {
    "id": fields.Integer(),
    "project_id": fields.Integer(),
    "type": fields.String(required=True, default="Feature"),
示例#12
0
from flask import request, abort
from flask_restplus import Namespace, Resource, fields, reqparse
from database.database import Database
from database.swagger_models import client
from database.marshmallow_models import NewClientSchema, ClientSchema, ObjectIdField, Address
from marshmallow import Schema

import requests

api = Namespace('Client',
                description="Api endpoints for client related operations")

#importing swagger schemas
client = api.schema_model('Client', client)


#get all clients
@api.route('/')
class clientList(Resource):
    @api.doc(description='Get all clients',
             responses={200: ('client collection', [client])})
    def get(self):
        return [{
            **cl, '_id': str(cl['_id'])
        } for cl in Database().Get_Clients()]


#get a client by its id
@api.route('/<string:client_id>')
@api.param('client_id', 'Client identifier')
class clientById(Resource):
示例#13
0
from flask import request, abort
from flask_restplus import Namespace, Resource, fields, reqparse
from database.database import Database
from database.swagger_models import food
from database.marshmallow_models import NewFoodSchema, FoodSchema, ObjectIdField, Ingredients
from marshmallow import Schema

import requests


api = Namespace('food',description='Operations related to the food components')

#swagger schemas
food = api.schema_model('Food', food)

#get all foods
@api.route('/')
class foodList(Resource):
    @api.doc(description='Get all food', responses={200: ('food collection', [food])})
    def get(self):
        return [{**fl, '_id': str(fl['_id'])}
                for fl in Database().Get_Foods()]
    
#get food by id
@api.route('/<string:food_id>')
@api.param('food_id','food identifier')
class FoodById(Resource):
    @api.doc(description='Returns a food item',
             responses={200: ('Returned food item', food),
                        404: 'Food item not found'})
    def get(self, food_id):
示例#14
0
palabra = api.schema_model(
    'Palabra', {
        'type': 'object',
        'properties': {
            'Palabra': {
                'type': 'string',
                'description': 'Una palabra',
                'example': 'megidolaon'
            },
            'Categoria': {
                'type': 'integer',
                'description':
                'La categoria de una palabra, 1 ataque, 0 curacion',
                'example': 1
            },
            'Exitos': {
                'type': 'integer',
                'description':
                'Número de veces que se ha escrito la palabra correctamente',
                'example': 12
            },
            'Ocurrencias': {
                'type': 'integer',
                'description':
                'Número de veces que se ha escrito la palabra en total',
                'example': 120
            }
        }
    })
示例#15
0
from flask import request
from flask_restplus import Namespace, Resource
from core.models import Usuarios as TablaUsuarios
from core.database import db

api = Namespace('usuarios', description='Operaciones sobre los usuarios')

usuario = api.schema_model(
    'Usuario', {
        'type': 'object',
        'properties': {
            'IDusuarios': {
                'type': 'integer',
                'description': 'El ID del usuario',
                'ejemplo': 1
            },
            'NombreUsuarios': {
                'type': 'string',
                'description': 'El nombre del usuario',
                'ejemplo': 'Arashi'
            }
        }
    })


# Puesto a modo de ejemplo, no es buena idea dejar al alcance de todos el acceso a la lista de todos los usuarios y menos con las contraseñas
@api.route('/')
class Usuario(Resource):
    @api.doc(summary='Obtener todos los usuarios',
             responses={200: ('Lista de usuarios', [usuario])})
    def get(self):
 def test_schema_model(self):
     api = Namespace('test')
     api.schema_model('Person', {})
     assert 'Person' in api.models
示例#17
0
import pytz
import requests  # Python 3 requests module: http://docs.python-requests.org/en/master/
from flask import request, abort
from flask_restplus import Namespace, Resource, reqparse
from .core.database import Database
from .core.swagger_models import water_body, node, string_array
from .core.marshmallow_models import NewWaterBodySchema
from .core.utils import token_required
from dateutil import parser as date_parser, tz  # python-dateutil module: https://dateutil.readthedocs.io/en/stable/
from functools import reduce
from datetime import datetime

api = Namespace('water-bodies', description='Water bodies related operations')

# API schemas
water_body = api.schema_model('WaterBody', water_body)
node = api.schema_model('Node', node)
string_array = api.schema_model('StringArray', string_array)


@api.route('/add')
class AddWaterBody(Resource):
    @api.doc(summary='Add water bodies to the water bodies collection',
             security="apikey")
    @api.expect([water_body])
    @token_required
    def post(self):
        new_water_bodies, errors = NewWaterBodySchema(many=True).load(
            request.get_json() or {})
        if errors:
            new_water_bodies = [
示例#18
0
 def test_schema_model(self):
     api = Namespace('test')
     api.schema_model('Person', {})
     assert 'Person' in api.models
示例#19
0
            @self.ns.doc('{}_validator'.format(self.name))
            def get(self):
                if validate_json == True:
                    return make_response(jsonify(cls.validator), 200)
                return make_response(
                    jsonify({'message': 'No validator for object'}), 404)


#========#
# Routes #
#========#

###
###
###

ns_protocol = Namespace('protocols', description='Protocols')
protocol_model = ns_protocol.schema_model('protocol', Protocol.validator)
CRUD(ns_protocol, Protocol, protocol_model, 'protocol', validate_json=True)

###

ns_protocolschema = Namespace('protocolschema', description='ProtocolSchema')
protocolschema_model = ns_protocolschema.schema_model('protocolschema',
                                                      ProtocolSchema.validator)
CRUD(ns_protocolschema,
     ProtocolSchema,
     protocolschema_model,
     'protocolschema',
     validate_json=True)