def __init__(self, api, *args, **kwargs): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('usuario') self.reqparse.add_argument('password') super().__init__(api=api, *args, **kwargs)
import copy from flask_restx import reqparse from jamaica.v1.cocktails.parsers import cocktail_list_parser inventory_resolve_parser = reqparse.RequestParser() inventory_resolve_parser.add_argument('cocktail', type=str, help='cocktail slug') inventory_resolve_parser.add_argument('spec', type=str, help='spec slug from the cocktail') # inventory_resolve_parser.add_argument('ingredient', type=str, help='cocktail slug') # This matches everything that the cocktail_list_parser can do. Well.... almost. inventory_recipes_parser = copy.deepcopy(cocktail_list_parser) inventory_recipes_parser.add_argument('missing', type=str, help='Count of missing') inventory_recipes_parser.remove_argument('instructions')
description='The address of the Customer'), 'active': fields.Boolean(required=True, description='Is the Customer avaialble for purchase?') }) customer_model = api.inherit( 'CustomerModel', create_model, { 'id': fields.String( readOnly=True, description='The unique id assigned internally by service'), }) # query string arguments customer_args = reqparse.RequestParser() customer_args.add_argument('first_name', type=str, required=False, help='List Customers by first name') customer_args.add_argument('last_name', type=str, required=False, help='List Customers by last name') customer_args.add_argument('email', type=str, required=False, help='List Customers by email') customer_args.add_argument('address', type=str, required=False,
import numpy as np available_methods = { "reference_point_method": ReferencePointMethod, "reference_point_method_alt": ReferencePointMethod, # for testing purposes only! "synchronous_nimbus": NIMBUS, "nautilus_navigator": NautilusNavigator, "rvea": RVEA, "irvea": RVEA, "iopis": IOPIS_NSGAIII, "rvea/class": RVEA, "enautilus": ENautilus, } method_create_parser = reqparse.RequestParser() method_create_parser.add_argument( "problem_id", type=str, help= "The id of the problem the method being created should attempt to solve.", required=True, ) method_create_parser.add_argument( "method", type=str, help= (f"Specify which method to use. Available methods are: {list(available_methods.keys())}" ), required=True, )
fields.String( required=False, description="The hash of the transaction on the blockchain"), "blockchain_id": fields.Integer(required=False, description="The id on the blockchain"), "booking_status": fields.String( required=True, description="The status of the booking", enum=[x.value for x in BookingStatus], attribute="booking_status.value", ), }, ) bookings_parser = reqparse.RequestParser() bookings_parser.add_argument( "tenant_id", type=FilterParam("tenant_id", ops.eq, schema="int"), help="id of tenant", store_missing=False, ) bookings_parser.add_argument( "publication_id", type=FilterParam("publication_id", ops.eq, schema="int"), help="id of publication", store_missing=False, ) bookings_parser.add_argument( "initial_date", type=FilterParam(
def get(self): parser = reqparse.RequestParser() parser.add_argument('dayCount', type=int, required=True) args = parser.parse_args() return userController.get_activity(None, args['dayCount'])
description='Reports that can be run on subsets of genomic and repseq data' ) report_defs = None def load_report_defs(): with open('api/reports/reports.json') as fi: global report_defs report_defs = json.load(fi)['reports'] for k, report_def in report_defs.items(): if 'thumbnail' in report_def: report_defs[k]['thumbnail'] = app.config[ 'STATIC_LINK'] + 'img/reports/' + report_def['thumbnail'] report_list_arguments = reqparse.RequestParser() report_list_arguments.add_argument('species', type=str) report_list_arguments.add_argument('genomic_datasets', type=str) report_list_arguments.add_argument('rep_datasets', type=str) @ns.route('/reports/list') @api.response(404, 'No reports available!') class ReportsApi(Resource): @digby_protected() @api.expect(report_list_arguments, validate=True) def get(self): try: args = report_list_arguments.parse_args(request) scope = set()
from flask_restx import reqparse from jinjamator.daemon.api.endpoints.environments import available_environments from jinjamator.daemon.api.inputs import task_data from werkzeug.datastructures import FileStorage import logging log = logging.getLogger() task_arguments = reqparse.RequestParser() task_arguments.add_argument( "schema-type", type=str, required=False, default="full", choices=["schema", "options", "view", "data", "full"], help="Select which subpart of the schema should be returned", ) task_arguments.add_argument( "preload-data", type=task_data, required=False, help="preload data into schema", ) job_arguments = reqparse.RequestParser() job_arguments.add_argument( "log-level", type=str, required=False,
from flask_restx import reqparse, inputs from environment_settings import LIQPAY_SANDBOX_BY_DEFAULT_ENABLED parser_query = reqparse.RequestParser() parser_query.add_argument( "sandbox", type=inputs.boolean, default=inputs.boolean(LIQPAY_SANDBOX_BY_DEFAULT_ENABLED))
"sql/spice/select_spice_list.sql") recipeList = database_processor.fetch_data_in_database_pd_dataframe( QUERY_SELECT_SPICE_LIST).to_dict(orient="records") # START - Get nextId QUERY_NEXTID_SPICE = file_processor.read_sql_file( "sql/spice/nextid_spice.sql") sql_creation = QUERY_NEXTID_SPICE nextId = database_processor.fetch_data_in_database(sql_creation) # END - Get nextId if recipeList: return {'payload': recipeList, 'nextId': nextId[0][0]} api.abort(404) postParser = reqparse.RequestParser() postParser.add_argument('name', required=True, type=str) updateParser = reqparse.RequestParser() updateParser.add_argument('spice_id', required=True, type=int, help="Id cannot be blank!") updateParser.add_argument('name', required=False, type=str) deleteParser = reqparse.RequestParser() deleteParser.add_argument('spice_id', required=True, type=int, help="Id cannot be blank!")
create_session, dynamic_annotation_cache, sqlalchemy_cache, ) from materializationengine.info_client import get_aligned_volumes from materializationengine.blueprints.reset_auth import reset_auth from materializationengine.models import AnalysisTable, AnalysisVersion, Base from materializationengine.schemas import AnalysisTableSchema, AnalysisVersionSchema from middle_auth_client import auth_required, auth_requires_admin from sqlalchemy import MetaData, Table from sqlalchemy.engine.url import make_url from sqlalchemy.exc import NoSuchTableError __version__ = "2.12.12" bulk_upload_parser = reqparse.RequestParser() bulk_upload_parser.add_argument("column_mapping", required=True, type=dict, location="json") bulk_upload_parser.add_argument("project", required=True, type=str) bulk_upload_parser.add_argument("file_path", required=True, type=str) bulk_upload_parser.add_argument("schema", required=True, type=str) bulk_upload_parser.add_argument("materialized_ts", type=float) missing_chunk_parser = reqparse.RequestParser() missing_chunk_parser.add_argument("chunks", required=True, type=list, location="json") missing_chunk_parser.add_argument("column_mapping",
app = Flask(__name__) api = Api(app) DATABASE_HOST = 'mongodb' DATABASE_NAME = 'BookRentalManager' app.config['MONGO_DBNAME'] = DATABASE_NAME app.config['MONGO_URI'] = f'mongodb://{DATABASE_HOST}:27017/{DATABASE_NAME}' URL = f'mongodb://{DATABASE_HOST}:27017/{DATABASE_NAME}' connect(DATABASE_NAME, host=f'{DATABASE_HOST}:27017') CORS(app, resources={r'/*': {'origins': '*'}}) logger = get_logger('API') customers_parser = reqparse.RequestParser() customers_parser.add_argument( 'name', type=str, help="Cutomer's name", store_missing=False) customers_parser.add_argument( 'phone', type=str, help="Customer's phone number", store_missing=False) def result(f): @wraps(f) def func(*args, **kwargs): try: connect(DATABASE_NAME, host=f'{DATABASE_HOST}:27017') r = f(*args, **kwargs) return r # return make_response(jsonify(result), 200) except ValueError as e:
from flask_restx import Namespace, Resource, fields, reqparse, inputs from flask import request from flask_praetorian import auth_required, current_user from app import models, db, guard from app.core.func import emails, random_generator import sqlalchemy api = Namespace("auth", description="Authentication related operation") token = api.model( "Token", { "access_token": fields.String(required=True, description="The user identifier"), }, ) login_parser = reqparse.RequestParser() login_parser.add_argument("username", type=str, required=True, location='json') login_parser.add_argument("password", type=str, required=True, location='json') token_refresh_parser = reqparse.RequestParser() token_refresh_parser.add_argument("token", type=str, required=True, location='json') @api.route("/") class ApiAuthentication(Resource): @api.doc("auth_user") @api.marshal_list_with(token) @api.doc(security=[]) @api.expect(login_parser) def post(self): """authenticates user"""
from flask_restx import (Api as baseapi, inputs, Resource, reqparse) from tshistory import api as tsapi, util from tshistory_rest.util import (binary_pack_meta_data, enum, has_formula, todict, utcdt) def no_content(): # see https://github.com/flask-restful/flask-restful/issues/736 resp = make_response('', 204) resp.headers.clear() return resp base = reqparse.RequestParser() base.add_argument('name', type=str, required=True, help='timeseries name') update = base.copy() update.add_argument('series', type=str, required=True, help='json representation of the series') update.add_argument('author', type=str, required=True, help='author of the insertion') update.add_argument('insertion_date', type=utcdt, default=None,
def get(self): parser = reqparse.RequestParser() return userController.get_all_users(**parser.parse_args())
'id': fields.Integer(required=True, description='The id for each order'), 'created_date': fields.DateTime(required=False, description='The date at which order was created'), 'customer_id': fields.Integer(required=True, description='The customer id of the Order'), 'order_items': fields.List(fields.Nested(item_model, required=True), required=True, description='The items in the Order') }) # query string arguments order_args = reqparse.RequestParser() order_args.add_argument('customer_id', type=int, required=False, help='List Orders by Customer id') ###################################################################### # Error Handlers ###################################################################### @app.errorhandler(DataValidationError) def request_validation_error(error): """ Handles Value Errors from bad data """ return bad_request(error)
def post(self): parser = reqparse.RequestParser() parser.add_argument('fileName', type=str, required=True) return fileController.get_file(**parser.parse_args())
def get(self): parser = reqparse.RequestParser() args = parser.parse_args() return 'hello world'
def post(self): parser = reqparse.RequestParser() parser.add_argument('username', type=str, required=True) args = parser.parse_args() return userController.unfollow_user(flask_login.current_user, args['username'])
import datetime from flask_restx import Resource, reqparse from flask_jwt_extended import jwt_required from box import Box from model.orm import db from serialize.person import person_serializer from model.company import Company from model.person import Person from model.nature_of_control import NatureOfControl from .company import api psc_list_parser = reqparse.RequestParser() psc_list_parser.add_argument('name', type=str, location='args') psc_list_parser.add_argument('yearOfBirth', type=int, location='args') psc_list_parser.add_argument('nationality', type=str, location='args') @api.route('/<string:company_number>/person') class PersonListApi(Resource): @api.marshal_list_with(person_serializer) @jwt_required def get(self, company_number): args = Box(psc_list_parser.parse_args()) company = Company.query.get_or_404(company_number) people = company.people return [person for person in people if (not args.name or args.name.lower() in person.name.lower()) and (not args.yearOfBirth or person.dob_year == args.yearOfBirth) and (not args.nationality or person.nationality.lower() == args.nationality.lower())]
from flask_restx import Namespace, Resource, fields, marshal_with, reqparse from src.api.v1.helpers import ( DescriptiveArgument, extend_reaction, make_response, success_response, ) from src.api.v1.models.reactions import reaction from src.queries.reactions import get_reactions from src.utils.db_session import get_db_read_replica from src.utils.redis_cache import cache from src.utils.redis_metrics import record_metrics ns = Namespace("reactions", description="Reaction related operations") get_reactions_parser = reqparse.RequestParser( argument_class=DescriptiveArgument) get_reactions_parser.add_argument( "type", required=False, description="The type of reactions for which to query.") get_reactions_parser.add_argument( "tx_signatures", required=True, action="split", description= "The `reacted_to` transaction id(s) of the reactions in question.", ) get_reactions_response = make_response("reactions", ns, fields.List(fields.Nested(reaction)))
from flask_restx import Namespace, reqparse, Resource from modules.enums import * from modules.locations import get_amfam_locations_by_zipcode api = Namespace('locations', description='Locations related operations', validate=True) locations_parser = reqparse.RequestParser() locations_parser.add_argument(arg_locations_zipcode, required=True, help='Zip code') locations_parser.add_argument(arg_locations_radius, help='Radius') @api.route('/nearby') class LocationsClass(Resource): @api.expect(locations_parser) def get(self): args = locations_parser.parse_args() zipcode = args[arg_locations_zipcode] radius = 10 if args[arg_locations_radius] is not None: radius = int(args[arg_locations_radius]) return get_amfam_locations_by_zipcode(zipcode, radius)
@ns.doc(id="""Get User""", params={'user_id': 'A User ID'}, responses={ 200: 'Success', 400: 'Bad request', 500: 'Server error' }) @ns.marshal_with(user_response) @cache(ttl_sec=5) def get(self, user_id): """Fetch a single user.""" user_id = decode_with_abort(user_id, ns) return get_single_user(user_id, None) full_user_parser = reqparse.RequestParser() full_user_parser.add_argument('user_id', required=False) @full_ns.route(USER_ROUTE) class FullUser(Resource): @record_metrics @full_ns.marshal_with(full_user_response) @cache(ttl_sec=5) def get(self, user_id): user_id = decode_with_abort(user_id, ns) args = full_user_parser.parse_args() current_user_id = get_current_user_id(args) return get_single_user(user_id, current_user_id)
#!flask/bin/python # Copyright 2020 Luis Blazquez Miñambres (@luisblazquezm), Miguel Cabezas Puerto (@MiguelCabezasPuerto), Óscar Sánchez Juanes (@oscarsanchezj) and Francisco Pinto-Santos (@gandalfran) # See LICENSE for details. from flask_restx import reqparse news_argument_parser = reqparse.RequestParser() news_argument_parser.add_argument('q', location='args', type=str, required=True, default=None, help='The keyword to search news from.') news_argument_parser.add_argument('country_code', location='args', type=str, required=False, default=None, help='Country to search news from.')
# create tenant handler tenant_handler = TenantHandler(app.logger) def legend_service_handler(): """Get or create a LegendService instance for a tenant.""" tenant = tenant_handler.tenant() handler = tenant_handler.handler('legend', 'legend', tenant) if handler is None: handler = tenant_handler.register_handler( 'legend', tenant, LegendService(tenant, app.logger)) return handler # request parser legend_parser = reqparse.RequestParser(argument_class=CaseInsensitiveArgument) legend_parser.add_argument('layer', required=True) legend_parser.add_argument('format') legend_parser.add_argument('bbox') legend_parser.add_argument('crs') legend_parser.add_argument('scale') legend_parser.add_argument('width') legend_parser.add_argument('height') legend_parser.add_argument('dpi') legend_parser.add_argument('boxspace') legend_parser.add_argument('layerspace') legend_parser.add_argument('layertitlespace') legend_parser.add_argument('symbolspace') legend_parser.add_argument('iconlabelspace') legend_parser.add_argument('symbolwidth') legend_parser.add_argument('symbolheight')
from flask_restx import reqparse from beers.database.models import Beer def sku(value): check = Beer.query.filter_by(sku=value).first() if check: raise ValueError('SKU is already used.') return value sku.__schema__ = {'type': 'string', 'format': 'SKU'} authorization_arguments = reqparse.RequestParser() authorization_arguments.add_argument('Authorization', type=str, required=True, help='Access token', location='headers') beer_create_arguments = reqparse.RequestParser() beer_create_arguments.add_argument('Authorization', type=str, required=True, help='Access token', location='headers') beer_create_arguments.add_argument('sku', type=sku, required=True, help='Stock keeping unit', location='form')
class Todos(Resource): schema = TodoSchema() post_parser = reqparse.RequestParser(bundle_errors=True) post_parser.add_argument("todoTitle", required=True, location="form") post_parser.add_argument("todoContents", location="form") put_parser = post_parser.copy() put_parser.add_argument("todoId", required=True, type=int, location="form") patch_parser = reqparse.RequestParser(bundle_errors=True) patch_parser.add_argument("todoId", required=True, type=int, location="form") patch_parser.add_argument("todoCompleted", required=True, type=inputs.boolean, location="form") delete_parser = patch_parser.copy() delete_parser.remove_argument("todoCompleted") @api.response(201, "Created") @api.response(401, "Unauthorized") def post(self): if not current_user.is_authenticated: abort(401) args = self.post_parser.parse_args() user = User.query.get(current_user.id) new_todo = Todo(title=args["todoTitle"], contents=args["todoContents"]) user.todos.append(new_todo) db.session.add(new_todo) db.session.commit() return {"status": "Success"}, 201 @api.response(200, "OK") @api.response(401, "Unauthorized") def get(self): if not current_user.is_authenticated: abort(401) return self.schema.dump( Todo.query.filter_by(user_id=current_user.id).all(), many=True) @api.response(200, "OK") @api.response(401, "Unauthorized") def put(self): if not current_user.is_authenticated: abort(401) args = self.put_parser.parse_args() todo = Todo.query.filter_by(id=args["todoId"], user_id=current_user.id).first() if todo is None: return {"status": "Not found"} todo.title = args["todoTitle"] todo.contents = args["todoContents"] db.session.commit() return {"status": "Success"} @api.expect(patch_parser) @api.response(200, "OK") @api.response(401, "Unauthorized") def patch(self): if not current_user.is_authenticated: abort(401) args = self.patch_parser.parse_args() todo = Todo.query.filter_by(id=args["todoId"], user_id=current_user.id).first() if todo is None: return {"status": "Not found"} todo.completed = args["todoCompleted"] db.session.commit() return {"status": "Success"} @api.expect(delete_parser) @api.response(200, "OK") @api.response(401, "Unauthorized") def delete(self): if not current_user.is_authenticated: abort(401) args = self.delete_parser.parse_args() todo = Todo.query.filter_by(id=args["todoId"], user_id=current_user.id).first() if todo is None: return {"status": "Not found"} db.session.delete(todo) db.session.commit() return {"status": "Success"}
def post(self): parser = reqparse.RequestParser() parser.add_argument('userId', type=str, required=True) return
from flask import Blueprint, jsonify, request, send_file from flask_restx import Resource, reqparse, inputs, fields from werkzeug.exceptions import NotFound, BadRequest, Unauthorized, UnprocessableEntity, InternalServerError from werkzeug.utils import secure_filename from ...helpers import token_verify_or_raise, RESPONSE_OK, delete_excel from ...models import db, status, roles from ...models.comments import Comments from ...models.contributionform import Contributionform from ...models.member_view import MemberView from ...models.employer_view import EmployerView from xlutils.copy import copy from . import ns from ... import APP, LOG parser = reqparse.RequestParser() parser.add_argument('Authorization', type=str, location='headers', required=True) parser.add_argument('username', type=str, location='headers', required=True) parser.add_argument('Ipaddress', type=str, location='headers', required=True) parser.add_argument('employerusername', type=str, location='form', required=True) parser.add_argument('employername', type=str, location='form', required=True) parser.add_argument('startDate', type=str, location='form', required=True) parser.add_argument('endDate', type=str, location='form', required=True) parser.add_argument('Comment', type=str, location='form', required=False) parser.add_argument('file', type=FileStorage, location='files', required=True) response_model = ns.model('PostInitiateContribution', { 'error': fields.String, 'result': fields.String, })
from flask_restx import Namespace, Resource, fields, reqparse from flask import abort from core.models import * from core.utils import * api = Namespace('turmas', description='Operações relacionadas as turmas', decorators=[token_required()]) turma_get_parser = reqparse.RequestParser(bundle_errors=True) turma_get_parser.add_argument('nome', type=str, help='Nome da disciplina') turma_get_parser.add_argument('codigo', type=str, help='Codigo da disciplina a ser atualizado') turma_get_parser.add_argument('semestre', type=str, help='Semestre de oferta da disciplina') turma_get_parser.add_argument('professor_id', type=int, help='ID do professor que ministra a disciplina') turma_field = api.model( 'TurmaField', { 'nome': fields.String, 'codigo': fields.String, 'semestre': fields.String, 'professor_id': fields.Integer }) @api.doc(