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>')
from flask_restplus import Namespace, Resource, fields from flask import request from werkzeug.datastructures import FileStorage api = Namespace('Signature', description='Process') upload_parser = api.parser() # Input arguments includes multiple file input upload_parser.add_argument('file', location='files', type=FileStorage, required=True, action='append') upload_parser.add_argument('token', required=True) upload_parser.add_argument('user_name', required=True) @api.route('/verify_signature/') @api.expect(upload_parser) class Signature(Resource): def post(self): uploaded_file = request.files print('files:', uploaded_file) return "User Authenticated with 98% Confidence", 201 get_status_parser = api.parser() get_status_parser.add_argument('record_id', required=True) @api.route('/check_status/') @api.expect(get_status_parser) class Process(Resource): def get(self): return {'status': 'processing'}, 203
from app.models.ingredient import Ingredient from app.web.controllers.entities.basic_response import BasicResponse, BasicResponseSchema from db import session from schemas import IngredientClientSchema ingredients_namespace = Namespace('ingredients', description='Ingredients CRUD') ingredients_fields = ingredients_namespace.model( 'Ingredient', { 'name': fields.String(example='Egg'), 'calories': fields.Float(example=200.0), }) auth_parser = ingredients_namespace.parser() auth_parser.add_argument('Authorization', location='headers', help='Bearer token') @ingredients_namespace.route('/', strict_slashes=True) @ingredients_namespace.expect(auth_parser, validate=True) class IngredientsListResource(Resource): method_decorators = [jwt_required] def create_params(self) -> dict: parser = reqparse.RequestParser() parser.add_argument('name', type=str, required=True) parser.add_argument('calories', type=float, required=True) return parser.parse_args()
elif detected['type'] == 'person': person = Persons(objectId=i + countOfObjectsIndbAPI) db.session.add(person) else: make_response({"error": "Undefined object"}, 400) db.session.add(coordinates) db.session.add(Object) db.session.commit() db.session.flush() socketio.emit('infoUpdated', {'data': 42}) make_response({"success": "Info updated"}, 200) imageInfoIndex = api.parser() imageInfoIndex.add_argument('cameraId', location='args', type=str, required=True) imageInfoIndex.add_argument('indexOfImage', location='args', type=str, required=True) @api.route(routes['getImageInfoByIndexOfImage']) class ImageInfoByIndexOfImage(Resource): @api.expect(imageInfoIndex) def get(self): query = request.args
from flask import Flask, request from flask_restplus import Namespace, Resource, Api, fields import pymongo from bson import ObjectId from database import get_db api = Namespace('acuerdosUser', description='acuerdos users related operations') artesanosUserParser = api.parser() artesanosUserParser.add_argument('page', type=int, help='page number', location='head') artesanosUserParser.add_argument('pageSize', type=int, help='page size', location='head') queryAcuerdosUser = { "$project": { "artesanoID": { "$toObjectId": "$artesano" }, "cliente": 1, "artesano": 1, "acuerdo": 1, "descripcion": 1, "valor": 1, "fechaInicio": 1, "fechaFin": 1, "comentario": 1
# coding=utf-8 from flask import Flask, request, redirect from flask_restplus import Namespace, Resource, fields, Model from .model import APIModel import json __author__ = 'dolacmeo' __doc__ = '' user_api = Namespace('user', description="用户系统接口") user_login_parser = user_api.parser() user_login_parser.add_argument('ident', type=str, required=True, help='登录名', location='form') user_login_parser.add_argument('pwd', type=str, required=True, help='登录密码', location='form') user_login_response = user_api.model('User_login', { 'success': fields.Boolean(required=True, description='成功标识', example=True), '_id': fields.String(required=True, description='数据库id', example='57d3aeea0b05551588e1bae8'), 'apikey': fields.String(required=True, description='apikey', example='FCA46A3D0EDD711037FC88C10CD1D0E1'), 'error': fields.String(required=False, description='错误信息', example='') }) @user_api.route('/login') @user_api.response(201, '操作成功') @user_api.response(406, '验证失败') class UserLogin(Resource): @user_api.doc('用户登录', parser=user_login_parser) @user_api.marshal_with(user_login_response, code=201) def post(self): """用户登录 获取APIKEY """
from schemas.hw_benchmark import HWBenchmarkSchema from logic.process_files import process_files_request from logic.overall_average import calc_overall_average from logic.utils.create_plots import render_image from files.list_files import list_files, get_file from config import BATTERY_TYPES, BOT_TYPES, RELEASES, HUT_VERSIONS from .template import EndpointConfiguration # pylint: disable=no-self-use api = Namespace('hw_benchmark', description='Request related to Hardware Benchmarks') upload_parser = api.parser() upload_parser.add_argument('meta_json', location='files', type=FileStorage, required=True) upload_parser.add_argument('latencies_bag', location='files', type=FileStorage, required=True) upload_parser.add_argument('sd_card_json', location='files', type=FileStorage, required=True) upload_parser.add_argument('localization_bag', location='files', type=FileStorage,
from pprint import pprint from datetime import datetime from . import socketio,client, twilio_phone api = Namespace('reviews', description='Review related operations') posting_id = api.model('posting_id', { 'email': fields.String(description="email of person being reviewed"), 'content': fields.String(description="Content of review"), 'numStars': fields.Float(description="number of stars in review") }) friend_data = api.model('friend_data_for_review', { 'friend': fields.String(description="User email or username"), }) parser = api.parser() parser.add_argument('Authorization',type=str,location='headers',help='Bearer Access Token', required=True) def tokenToEmail(args): token = args['Authorization'] if not token: return None try: decToken = jwt.decode(token,"SECRET_KEY") except: return None
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:
def test_parser(self): api = Namespace('test') assert isinstance(api.parser(), restplus.reqparse.RequestParser)
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') postParser = whiskeyApi.parser() postParser.add_argument('name', type=str, required=True, help='The name of the whiskey') postParser.add_argument('proof', type=float, required=False, help='The proof of the whiskey') postParser.add_argument('price', type=float, required=False, help='The price of the whiskey') postParser.add_argument('style', type=str, required=False, help='The style of the whiskey') postParser.add_argument('age', type=int, required=False, help='The age of the whiskey') postParser.add_argument('icon', type=str, required=False, help='The url for the whiskey icon')
from flask import abort, request from flask_restplus import Namespace, Resource from models.database import db from models.models import POI, Tag from models.forms import POIForm, POIGeneratorForm import json from sqlalchemy.exc import IntegrityError from dataprocessing.resource_finder import get_points_of_interest api = Namespace('poi', description="POI Routes") poi_parser = api.parser() poi_parser.add_argument('name', type=str, help='name', location='form', required=True) poi_parser.add_argument('latitude', type=float, help='latitude', location='form', required=True) poi_parser.add_argument('longitude', type=float, help='longitude', location='form', required=True) poi_parser.add_argument('tags', type=str, help='json string [{"name":"tag1"},{"name":"tag2"}]', location='form') poi_parser.add_argument('description', type=str, help='Description', location='form') poi_generator_parser = api.parser() poi_generator_parser.add_argument('latitude', type=float, help='latitude', location='form', required=True) poi_generator_parser.add_argument('longitude', type=float, help='longitude', location='form', required=True) poi_generator_parser.add_argument('radius', type=float, help='radius', location='form', required=True) @api.route('/') class POICrud(Resource): @api.expect(poi_parser, csrf_enabled=False) @api.doc(responses={403: 'Form Invalid',404: 'Database Error'}) def post(self): 'Posts a POI for client input' if request.form.getlist('latitude')!=[]: form = POIForm(request.form)
logger = logging.getLogger(__name__) authApi = Namespace('auth', description='User authentication and authorization related operations') authRegister = authApi.model('Register', { 'token': fields.String(required=True, description='The user access token'), 'provider': fields.Integer(required=True, description='The provider the token belongs to'), 'email': fields.String(required=True, description='Email address of the user'), }) authLogin = authApi.model('Login', { 'token': fields.String(required=True, description='The user access token'), 'provider': fields.Integer(required=True, description='The provider the token belongs to'), }) regParser = authApi.parser() regParser.add_argument('token', type=str, required=True, help='The user access token') regParser.add_argument('provider', type=int, required=True, help='The provider the token belongs to') regParser.add_argument('email', type=str, required=True, help='Email address of the user') loginParser = authApi.parser() loginParser.add_argument('token', type=str, required=True, help='The user access token') loginParser.add_argument('provider', type=int, required=True, help='The provider the token belongs to') @api.route('/register') @api.expect(regParser) class AuthRegister(Resource): @api.marshal_list_with(authRegister) def post(self): args = regParser.parse_args() return registerUser(args['token'], args['provider'], args['email'])
import http.client from flask import request from datetime import datetime from sqlalchemy.orm import joinedload from flask_restplus import Namespace, Resource, fields from locations.models import Product, Location from locations.db import db from locations.pagination import get_next_page, get_previous_page api_namespace = Namespace('api', description='API operations') # Input and output formats for Product product_parser = api_namespace.parser() product_parser.add_argument('product_description', type=str, help='Description of the product') model = { 'product_id': fields.Integer(attribute='id'), 'product_description': fields.String(attribute='description'), } product_model = api_namespace.model('Product', model) @api_namespace.route('/product/') class ProductsListCreate(Resource): @api_namespace.doc('list_products') @api_namespace.marshal_with(product_model) def get(self): ''' Retrieves all the products
'updated_at': fields.DateTime(description="May be updated if LDAP details or email change") }), skip_none=True ) }) user_profile_update_dto = api.model('user_profile_update', { 'email': fields.String(required=True, description='New user email') }) user_profile_update_response_dto = api.model('user_profile_update_response', { 'error': fields.Boolean(description="True on error, false on success"), 'message': fields.String(description="Some error or success message"), 'details': fields.Nested(api.model('user_profile_update_response_details', {})) }) user_header_token_dto = api.parser() user_header_token_dto.add_argument( 'X-Api-Auth-Token', help="Token is renewed each time this header exist", required=True, location='headers' ) @api.route( '/profile', doc={"description": "Performs profile-related actions such has getting et updating details about the user (name, email, username...)"} ) class Profile(Resource): @api.marshal_with(user_profile_response_dto, skip_none=True) @api.expect(user_header_token_dto, validate=True)
description='Label identifier'), 'label': fields.String(required=True, description='Class label'), 'probability': fields.Float(required=True) }) predict_response = api.model( 'ModelPredictResponse', { 'status': fields.String(required=True, description='Response status message'), 'predictions': fields.List(fields.Nested(label_prediction), description='Predicted labels and probabilities') }) # set up parser for image input data image_parser = api.parser() image_parser.add_argument('image', type=FileStorage, location='files', required=True) @api.route('/predict') class Predict(Resource): model_wrapper = ModelWrapper() @api.doc('predict') @api.expect(image_parser) @api.marshal_with(predict_response) def post(self):
import numpy as np # Python libs. import flask import logging from flask_restplus import Resource, Namespace # Project files. from . import lib from config import CONFIGURATION from webmaps.models.slots_cluster import ParkingSlotsCluster from constans import VALIDATION_NAMESPACE NAMESPACE = Namespace( 'parking-slot', description='Api namespace representing a parking slot.') LOGGER = CONFIGURATION.get_logger(__name__) # Model for parsing arguments. user_location_model = NAMESPACE.parser() user_location_model.add_argument( 'longitude', type=float, help='Longitude of parking slot.', required=True) user_location_model.add_argument( 'latitude', type=float, help='Latitude of parking slot.', required=True) user_location_model.add_argument( 'radius', type=float, help='Radius of circle to look for parking.', required=True ) user_location_model.add_argument( 'time', type=float, help='Time of day the user wants to park.', required=True ) @NAMESPACE.route('/')
'sour': fields.Float(required=False, description='Sourness of the whiskey'), 'heat': fields.Float(required=False, description='Hotness of the whiskey'), 'smooth': fields.Float(required=False, description='Smoothness of the whiskey'), 'finish': fields.Float(required=False, description='Finish of the whiskey'), 'crisp': fields.Float(required=False, description='Crispness of the whiskey'), 'leather': fields.Float(required=False, description='Leatheriness of the whiskey'), 'wood': fields.Float(required=False, description='Woodiness of the whiskey'), 'smoke': fields.Float(required=False, description='Smokeyness of the whiskey'), 'citrus': fields.Float(required=False, description='Citrusness of the whiskey'), 'floral': fields.Float(required=False, description='Floralness of the whiskey'), 'fruit': fields.Float(required=False, description='Fruitiness of the whiskey'), }) dbm = datastore.DbManager(testMode=False) getAllParser = ratingApi.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='whiskeyId', help='The name of the field to sort on: userId, whiskeyId, rating, wood, smoke, etc') getParser = ratingApi.parser() getParser.add_argument('whiskeyId', type=int, required=True, help='The ID of the whiskey') getParser.add_argument('userId', type=int, required=True, help='The ID of the user') ppParser = ratingApi.parser() ppParser.add_argument('whiskeyId', type=int, required=True, help='The ID of the whiskey') ppParser.add_argument('userId', type=int, required=True, help='The ID of the user') ppParser.add_argument('rating', type=float, required=False, help='User rating of the whiskey') ppParser.add_argument('notes', type=str, required=False, help='User note about the whiskey') ppParser.add_argument('sweet', type=float, required=False, help='Sweetness of the whiskey') ppParser.add_argument('sour', type=float, required=False, help='Sourness of the whiskey')
from flask_restplus import Namespace, Resource from apis.test_point.services import TestPointService test_point_endpoints = Namespace('test_point', description='Test point related operations') headers = test_point_endpoints.parser() headers.add_argument('Authorization', location='headers', required=True, help="Access token. E.g.: Bearer [JWT]") @test_point_endpoints.route('/all', doc=False) class GetAllTestPoints(Resource): @test_point_endpoints.doc('all') def get(self): """Get all test points""" return TestPointService().get_all() @test_point_endpoints.route('/city/<string:city>', doc=False) class GetTestPointsByCity(Resource): @test_point_endpoints.doc('by_city') def get(self, city): """Get tests points by city""" return TestPointService().get_by_city(city) def bind(api): api.add_namespace(test_point_endpoints)
description="5GTANGO SMP-CCS REST API " + "to control the industry pilot SSM.") app.register_blueprint(blueprint) api.add_namespace(api_v1) def serve_rest_api(service_address="0.0.0.0", service_port=9011, debug=True): app.run( host=service_address, port=int(service_port), debug=debug, # do not use the reloder: to avoid restarts and stat loss use_reloader=False) ssmstate_put_parser = api_v1.parser() ssmstate_put_parser.add_argument("uuid", type=str, required=True, help="Service Inst. UUID") ssmstate_put_parser.add_argument("quarantaine", type=inputs.boolean, required=False, help="Updated quarantaine status") @api_v1.route("/ssmstatus") class SsmStateEndpoint(Resource): @api_v1.response(200, "OK") def get(self): return app.store.get_dict()
from flask import Flask, request from flask_restplus import Namespace, Resource, Api, fields import pymongo from bson import ObjectId from database import get_db api = Namespace('clientes', description='clientes related operations') clientesParser = api.parser() clientesParser.add_argument('page', type=int, help='page number', location='head') clientesParser.add_argument('pageSize', type=int, help='page size', location='head') queryClientes = { "tipoUser": 1, "tipoId": 1, "identificacion": 1, "email": 1, "apellidos": 1, "nombres": 1, "direccion": 1, "ubicacion": 1, "telefonos": 1, "estado": 1, "intentos": 1, "servicios": 1
from .serializers import ProductSerializers from urpx.exceptions import InvalidUsage from urpx.extensions import db, cache import asyncio import aiohttp import os import json import requests import urllib.parse import random api = Namespace('Product API', description='Products related operation') serializers = ProductSerializers(api) auth_parser = api.parser() auth_parser.add_argument('Authorization', location='headers', required=True, help='Bearer <access_token>') SUPPORT_REASON = { 'cost': '금액', 'amount': '수량', } @api.route('api/products/recommends') @api.expect(auth_parser, validate=True) class ProductRecommendsResource(Resource): @jwt_required
from flask import send_file, make_response, request, abort, jsonify import os import time from flask_restplus import Namespace, Resource, inputs, fields from dao.incoming_image_dao import IncomingImageDAO from config import defaultConfigPath from apis.helper_methods import checkXManual api = Namespace('image/raw', description="All raw image functions route through here") rawParser = api.parser() rawParser.add_argument( 'X-Manual', location='headers', type=inputs.boolean, required=True, help='Specify whether this is a manual request (True) or autonomous (False)' ) rawImageModel = api.model( 'Raw Image Info', { 'id': fields.Integer(description='Auto-generated id for the image', example=1234), 'timestamp': fields.Float(description='ROS unix epoch UTC timestamp for the image', example=1541063315.2), 'image_path': fields.String( description=
from flask_restplus import Namespace, Resource from apis.data.services import ReportService from flask import request from flask_jwt_extended import jwt_required data_endpoints = Namespace('data', description='Data related operations') headers = data_endpoints.parser() headers.add_argument('Authorization', location='headers', required=True, help="Access token. E.g.: Bearer [JWT]") @data_endpoints.route('/state/<string:state_code>') @data_endpoints.expect(headers) class GetStateCases(Resource): @jwt_required @data_endpoints.doc('by_state') def get(self, state_code): """Get confirmed, suspects, recovered and death cases for a given state""" return ReportService().search_city_cases_by_state(state_code) @data_endpoints.route('/all') @data_endpoints.expect(headers) class GetAllCases(Resource): @jwt_required @data_endpoints.doc('all') def get(self):
from flask_restplus import Namespace, Resource from src import engine, session from models.user import User from models.request import Request import urllib3 import json api = Namespace('review', description='Review related operations') parser1 = api.parser() parser1.add_argument('email', location='args', default='email') @api.route('/getuser') class GetUserReview(Resource): """ Retrieve all reviews for a single user. """ @api.expect(parser1) def get(self): args = parser1.parse_args() email = args.get('email') #Need to test this query query = f'''select reviews.revOfferId, reviews.score, reviews.description from reviews join (Select offers.offerId, offers.user_email as "supplierEmailOff", offers.requestId from offers join requests on (offers.requestId = requests.requestId)
from flask import Flask, request from flask_restplus import Namespace, Resource, Api, fields import pymongo from bson import ObjectId from database import get_db api = Namespace('artesanos', description='artesanos related operations') artesanosParser = api.parser() artesanosParser.add_argument( 'page', type=int, help='page number', location='head') artesanosParser.add_argument('pageSize', type=int, help='page size', location='head') queryArtesanos = {"tipoUser": 1, "tipoId": 1, "identificacion": 1, "email": 1, "apellidos": 1, "nombres": 1, "direccion": 1, "ubicacion": 1, "telefonos": 1, "estado": 1, "intentos": 1, "servicios": 1 } servicesParser = api.parser() servicesParser.add_argument(
from exceptions import PasswordWrongException, NotFoundException, AlreadyExists from factory.BlFactory import userBl from utils.JwtUtil import JwtUtil from vo import UserVO ns = Namespace('user', description='关于用户(登录注册)') login_parameters = ns.model( 'LoginParameters', { 'username': fields.String(required=True, description='用户名'), 'password': fields.String(required=True, description='密码'), 'role': fields.String(required=True, description='角色') }) login_parser = ns.parser() login_parser.add_argument('username', type=str, help='用户名', location='form') login_parser.add_argument('password', type=str, help='密码', location='form') login_parser.add_argument('role', type=str, help='角色', location='form') @ns.route('') @ns.response(200, 'OK') @ns.response(404, '没有找到用户名或者密码') @ns.response(403, '用户名或者密码不正确') @ns.response(500, '内部错误') class User(Resource): @ns.doc(decription="登录") @ns.expect(login_parser) def post(self): try:
with app.app_context(): with open(args.dump_swagger_path, "w") as f: # TODO dump in nice formatting f.write(json.dumps(api.__schema__)) def serve_forever(args, debug=True): """ Start REST API server. Blocks. """ # TODO replace this with WSGIServer for better performance app.cliargs = args app.run(host=args.service_address, port=args.service_port, debug=debug) packages_parser = api_v1.parser() packages_parser.add_argument("package", location="files", type=FileStorage, required=True, help="Uploaded package file") packages_parser.add_argument("callback_url", location="form", required=False, default=None, help="URL called after unpackaging (optional)") packages_parser.add_argument("layer", location="form", required=False, default=None, help="Layer tag to be unpackaged (optional)")
from datetime import datetime from dateutil import parser from flask import make_response, jsonify, Response from flask_jwt_extended import get_jwt_identity, jwt_required from flask_restplus import abort, Namespace, Resource from models.asset import Asset from models.transaction import Transaction from models.user import User API = Namespace('transactions', description='transactions endpoint') CREATE_PARSER = API.parser() CREATE_PARSER.add_argument('asset_id', type=str, required=True, help='The unique identifier for the asset', location='json') CREATE_PARSER.add_argument('quantity', type=float, required=True, help='The quantity of the asset', location='json') CREATE_PARSER.add_argument('date_purchased', type=str, required=True, help='The date the asset was purchased', location='json') CREATE_PARSER.add_argument( 'date_sold',
return res value = api.model( 'Value', { 'value': fields.Raw(required=True, description='Value '), 'count': fields.Integer(required=False, description='Count '), }) values = api.model( 'Values', { 'values': fields.Nested(value, required=True, description='Values'), 'info': info_field, }) parser = api.parser() parser.add_argument( 'voc', type=inputs.boolean, help= 'Enable inclusion of controlled vocabulary terms and synonyms (true/false)', default=False) parser_body = api.parser() # parser_body.add_argument('voc', type=inputs.boolean, # help='Enable enriched search over controlled vocabulary terms and synonyms (true/false)', # default=False) parser_body.add_argument('body', type="json", help='json ', location='json') parser_body.add_argument('rel_distance', type=int, default=3) body_desc = 'It must be in the format {\"gcm\":{},\"type\":\"original\",\"kv\":{}}.\n ' \
from flask_restplus import Namespace, Resource, fields, abort from sqlalchemy import cast, String from sqlalchemy.exc import IntegrityError from app.models import User, Products from app import db from app.FtsRequest import FtsRequest from app.rest.Auth import Auth # Define namespace api = Namespace('FTS', description='Requests to Federal Tax Service', path='/fts') # JSON Parsers # # FTS users request JSON fields fts_user_request = api.parser() fts_user_request.add_argument('name', type=str, required=True, help='No name provided', location='json') fts_user_request.add_argument('email', type=str, required=True, help='No email provided', location='json') fts_user_request.add_argument('phone', type=str, required=True, help='No phone provided', location='json') # Receipt request query fields receipt_request = api.parser() receipt_request.add_argument('fn', type=int, required=True, help='No fn provided', location='args') receipt_request.add_argument('fd', type=int, required=True, help='No fd provided', location='args') receipt_request.add_argument('fp', type=int, required=True, help='No fp provided', location='args')
import pymongo from bson import ObjectId from database import get_db api = Namespace('instructors', description='Instructors related operations') instructorPayload = api.model( 'instructorPayload', { "tipoId": fields.String(["cedula", "ruc", "pasaporte"]), "identificacion": fields.String, "nombres": fields.String, "apellidos": fields.String, "telefono": fields.String }) instructorParser = api.parser() instructorParser.add_argument('page', type=int, help='page number', location='head') instructorParser.add_argument('pageSize', type=int, help='page size', location='head') @api.route('/') class Instructores(Resource): @api.doc(parser=instructorParser) def get(self): collection = get_db()['instructores']
'samples': fields.Raw( description='Dictionary where key=timestamp integer \ and value=data value', example={'timestamp1':'value1', 'timestampe2':'value2'} ) }) point_create_success_msg = 'Point created' point_create_fail_msg = 'Failed to create point' point_delete_success_msg = 'Point deleted' point_delete_fail_msg = 'Failed to delete point' influxdb_time_format = "2009-11-10T23:00:00Z" point_query_parser = point_api.parser() point_query_parser.add_argument('tag_query', type=str, location='args', help=model_to_json(m_point_post) ) point_query_parser.add_argument('geo_query', type=str, location='args') point_query_parser.add_argument('name', type=str, location='args') # TODO: Can this be more specified to have certain JSON structure in the str? @point_api.doc() @point_api.route('/') class PointGenericAPI(Resource): # @point_api.doc(body=m_point) @point_api.expect(point_query_parser) @point_api.response(200, 'Points found', m_point) @point_api.marshal_list_with(m_point_list)
from flask_restplus import Namespace, fields api_namespace = Namespace('api', description='Albums microservice API operations') auth_parser = api_namespace.parser() auth_parser.add_argument('Authorization', location='headers', type=str, help='Bearer Access Token') album_parser = auth_parser.copy() album_parser.add_argument('name', type=str, required=True, help='Album name') album_parser.add_argument('price', type=float, required=True, help='Album price') album_parser.add_argument('genre', type=str, required=True, help='Album genre') album_parser.add_argument('description', type=str, required=True, help='Album description') song_parser = auth_parser.copy() song_parser.add_argument('name', type=str, required=True, help='Song name') song_parser.add_argument('album_id', type=int, required=True, help='Album id') search_parser = api_namespace.parser() search_parser.add_argument('search', type=str, required=False,
from flask_restplus import Namespace, Resource from flask_restplus import fields from flask_restplus import inputs import sqlalchemy import flask from utils import sql_query_generator, log_query from model.models import db api = Namespace('pair', description='Operations to perform queries on key-value metadata pairs') query = api.model('Pair', { 'key': fields.String(attribute='column_name', required=True, description='Field name '), # 'info': fields.Nested(info, required=False, description='Info', skip_none=True), }) parser = api.parser() parser.add_argument('body', type="json", help='json ', location='json') parser.add_argument('q', type=str) parser.add_argument('exact', type=inputs.boolean, default=False) parser.add_argument('rel_distance', type=int, default=3) value_parser = api.parser() value_parser.add_argument('body', type="json", help='json ', location='json') value_parser.add_argument('is_gcm', type=inputs.boolean, default=True) value_parser.add_argument('rel_distance', type=int, default=3) ################################API DOCUMENTATION STRINGS################################### body_desc = 'It represents the context of the key-value query, based on the previous selection on gcm part.' \ 'It must be in the format {\"gcm\":{},\"type\":\"original\",\"kv\":{}}.\n ' \ 'Example values for the three parameters: \n ' \ '- gcm may contain \"disease\":[\"prostate adenocarcinoma\",\"prostate cancer\"],\"assembly\":[\"grch38\"]\n ' \
attribute='spread', description='Context'), 'status': fields.Constant( ctype='AccountHomeStatus', description='Home status'), 'disk_id': fields.base.Integer( description='Disk entity ID'), }) AccountHomeList = api.model('AccountHomeList', { 'homes': fields.base.List( fields.base.Nested(AccountHome), description='Home directories'), }) password_parser = api.parser() password_parser.add_argument( 'password', type=validator.String(), required=True, location='form', help='Password', ) PasswordChanged = api.model('PasswordChanged', { 'password': fields.base.String( description='New password') }) PasswordVerification = api.model('PasswordVerification', { 'verified': fields.base.Boolean(