from flask_restplus import reqparse adbmonitor_arguments = reqparse.RequestParser() adbmonitor_arguments.add_argument('id', type=int, required=False, default=0, help='ID') adbmonitor_arguments.add_argument('group_id', type=int, required=False, default=0, help='Group ID') adbmonitor_arguments.add_argument('device_id', type=int, required=False, default=0, help='Device ID') adbmonitor_arguments.add_argument('udid', type=str, required=False, help='UDID')
except: traceback.print_exc() return False def delete_links(ids): try: db.delete_links(ids) return True except: traceback.print_exc() return False # https://flask-restplus.readthedocs.io/en/stable/parsing.html parser_create = reqparse.RequestParser() parser_create.add_argument('url', type=str, required=True, location='form', help='url') parser_create.add_argument('description', type=str, required=True, location='form') parser_create.add_argument('image_url', type=str, location='form') parser_delete = reqparse.RequestParser() parser_delete.add_argument('ids', type=str, required=True, action='split') parser_header = reqparse.RequestParser() parser_header.add_argument('Authorization', type=str, required=True, location='headers') @api.route('/') class Links(CustomResource): @api.doc('get all links') @api.expect(parser_header) @token_required
from flask_restplus import reqparse from werkzeug.datastructures import FileStorage """ Parsers are 'templates' for information sent as body in POST and PUT requests. They provide some validation and help swagger generate API documentation. More info about request parsing: https://flask-restplus.readthedocs.io/en/stable/parsing.html """ user_info = reqparse.RequestParser(bundle_errors=True) user_info.add_argument('username', type=str, required=True, help='Username') user_info.add_argument('password', type=str, required=True, help='Password') photo_upload = reqparse.RequestParser(bundle_errors=True) photo_upload.add_argument('photo', type=FileStorage, location='files', required=True, help='Uploaded photo') photo_info = reqparse.RequestParser(bundle_errors=True) photo_info.add_argument('photo_id', type=int, required=True, help='Photo ID') ta_photo_upload = reqparse.RequestParser(bundle_errors=True) ta_photo_upload.add_argument('username', type=str, required=True, help='Username') ta_photo_upload.add_argument('password', type=str, required=True, help='Password')
from ..util.dto import NoticeDto from ..service.notice_service import ( save_new_notice, get_all_notices, get_by_notice_id, delete_by_notice_id ) api = NoticeDto.api _notice_load = NoticeDto.notice _notice_post = NoticeDto.notice_post _notice_save = NoticeDto.notice_save _notice_delete = NoticeDto.notice_delete arguments = reqparse.RequestParser() arguments.add_argument('page', type=int, required=False, default=1, help='현재 페이지') arguments.add_argument('per_page', type=int, required=False, default=20, help='한 페이지에 보여질 갯수') @api.route('/') class NoticeList(Resource): @api.doc('공지사항 리스트') @api.expect(arguments) @api.marshal_with(_notice_load) def get(self): """공지사항 전체 리스트""" args = arguments.parse_args(request) page = args.get('page', 1) per_page = args.get('per_page', 200) return get_all_notices(page, per_page)
# +---------------------------------------------------------------------------+ # | File contributors : | # | - Georges Bossert <gbossert (a) miskin.fr> | # +---------------------------------------------------------------------------+ # +---------------------------------------------------------------------------+ # | Standard library imports | # +---------------------------------------------------------------------------+ # +---------------------------------------------------------------------------+ # | Related third party imports | # +---------------------------------------------------------------------------+ from flask_restplus import reqparse # +---------------------------------------------------------------------------+ # | Local application imports | # +---------------------------------------------------------------------------+ new_domain_data = reqparse.RequestParser() new_domain_data.add_argument('name', type=str, required=True, location='json', help="Name of the field") new_domain_data.add_argument('tid', type=str, required=True, location='json', help="Data Type ID")
from flask_restplus import reqparse status_parser = reqparse.RequestParser() status_parser.add_argument('lab_ids', type=str, required=True, help='Ids of labs', action='append')
from flask_restplus import reqparse google_cb_args = reqparse.RequestParser() google_cb_args.add_argument('code', type=str, required=True, help='Google code') google_cb_args.add_argument('scope', type=str, required=False, help='Google scope') google_cb_args.add_argument('authuser', type=str, required=False, help='Google auth user') google_cb_args.add_argument('prompt', type=str, required=False, help='Google promt') google_cb_args.add_argument('state', type=str, required=False, help='Google state')
api = Api( version='1.3.0', title='Market Search', description='An API for searching and retrieving job listings from the ' 'entire job market', default='market', default_label="An API for searching job listings.") # Namespace configuration ns_market = Namespace('All job ads', description='Search and retrieve ~97% of all job ads.') api.add_namespace(ns_market, '/') # Queries market_query = reqparse.RequestParser() market_query.add_argument(settings.APIKEY, location='headers', required=True) market_query.add_argument(settings.OFFSET, type=inputs.int_range(0, settings.MAX_OFFSET), default=0) market_query.add_argument(settings.LIMIT, type=inputs.int_range(0, settings.MAX_LIMIT), default=10) market_query.add_argument(settings.SHOW_EXPIRED, choices=['true', 'false']) market_query.add_argument(settings.FREETEXT_QUERY) market_query.add_argument(settings.PLACE, action='append') market_query.add_argument(settings.EMPLOYER, action='append') market_query.add_argument(settings.STATISTICS, choices=list(settings.auranest_stats_options.keys()), action='append') market_query.add_argument(settings.STAT_LMT,
from flask_restplus import Resource, fields, reqparse, Namespace from flask import request todonamespace = Namespace("TODO's", description='To play with Dictonary') parselevel=reqparse.RequestParser() parselevel.add_argument('todo_id', type=str, required=True) parselevel.add_argument('todo_data', type=str, required=True) model = todonamespace.model('postInput', { 'todo_id': fields.String, 'todo_data': fields.String }) todos={} @todonamespace.route('/todos') class TodoSimple(Resource): @todonamespace.response(201, 'accepted') @todonamespace.response(400, 'Bad request') @todonamespace.response(500, 'Internal server error') @todonamespace.response(404, 'Not found') @todonamespace.response(403, 'Unauthorized') @todonamespace.expect(model) def post(self): payload = request.get_json() print(payload) key = payload.get('todo_id')
import os import sys import inspect # Importin from parent directory currentdir = os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) from core.sqlClasses import * from core.helpers import token_required parents_api = Namespace('parents', 'Operation with parents') # Setting up ID only parser idOnlyParser = reqparse.RequestParser() idOnlyParser.add_argument('id', type=int, required=True, location="args") # Setting up "First" parser firstNArg = reqparse.RequestParser() firstNArg.add_argument('first', type=int, required=False, location="args") idOnlyParserJson = parents_api.model( 'DeleteEntry', {'id': fields.Integer(default=1, required=True)}) # Defining a newParent model newParent = parents_api.model( 'NewParent', { 'name': fields.String(default="John", required=True), 'surname': fields.String(default="Doe", required=True), 'email': fields.String(default="*****@*****.**", required=True),
from virgilant_admin.database import db from virgilant_admin.database.models import RawRecords, MaskedRecords from flask import Response from sqlalchemy.orm.exc import NoResultFound from flask_restplus import fields from virgilant_admin.api.define import api from flask_restplus import reqparse from datetime import datetime def parseInputDatetime(s): return datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%fZ') ArgParser = reqparse.RequestParser() ArgParser.add_argument('numRecords', help="Number of Records. Format: Int", type=int) ArgParser.add_argument( 'start_datetime', help="Start Generated On Time. Format:'%Y-%m-%dT%H:%M:%S.%fZ", type=parseInputDatetime) ArgParser.add_argument( 'end_datetime', help="End Generated On Time. Format:'%Y-%m-%dT%H:%M:%S.%fZ", type=parseInputDatetime) def getAllRawRecords(): qryRes = RawRecords\
from flask_restplus import Namespace, Resource, reqparse from flask_login import login_required, current_user from ..util.pagination_util import Pagination from ..util import query_util, color_util from ..models import CategoryModel, AnnotationModel import datetime api = Namespace('category', description='Category related operations') create_category = reqparse.RequestParser() create_category.add_argument('name', required=True, location='json') create_category.add_argument('supercategory', location='json') create_category.add_argument('color', location='json') create_category.add_argument('metadata', type=dict, location='json') page_data = reqparse.RequestParser() page_data.add_argument('page', default=1, type=int) page_data.add_argument('limit', default=20, type=int) @api.route('/') class Category(Resource): @login_required def get(self): """ Returns all categories """ return query_util.fix_ids(current_user.categories.all()) @api.expect(create_category) @login_required
from flask_restplus import Namespace, Resource, fields, reqparse from app_controllers.challenges.gitlab_manager import GitlabManager import os gitlab_parser = reqparse.RequestParser() gitlab_parser.add_argument('challenge', help='{error_msg}', type=dict, location='json') gm = GitlabManager() api = Namespace('gitlab', description='Gitlab related operations') @api.route('/securethebox/github') class GitlabSetup(Resource): @api.doc('test') def post(self): args = gitlab_parser.parse_args() try: print("github") return "success", 201, { 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Methods": "POST" } except: return "error", 404
# Python Module Import import logging # Apps Module Import from apps.decorators.jwt_auth import jwt_token_required from apps.account.views import api from apps.models.user import User from apps.models.database import get_session from apps.utils.validate import check_username, check_password, check_email from apps.utils.response import success_response, fail_response from apps.utils.status_code import ERROR_UNAUTHORIZED ns_users = api.namespace("users") # create parser create_parser = reqparse.RequestParser() create_parser.add_argument('username', required=True) create_parser.add_argument('password', required=True) create_parser.add_argument('password_confirmed', required=True) create_parser.add_argument('email', required=True) # update parser update_parser = reqparse.RequestParser() update_parser.add_argument('password', required=True) update_parser.add_argument('password_confirmed', required=True) update_parser.add_argument('email', required=True) @ns_users.route('') class Home(Resource): @jwt_token_required
''' argumets expected by gene_suggest get method ''' from flask_restplus import reqparse gene_suggestion_arguments = reqparse.RequestParser() gene_suggestion_arguments.add_argument( 'query', type=str, help='the partial query typed by the user, e.g. `brc` ', default="") gene_suggestion_arguments.add_argument( 'species', type=str, help='the name of the target species, e.g. `homo_sapiens`', required=True) gene_suggestion_arguments.add_argument( 'limit', type=int, help='the maximum number of suggestions to return, e.g. `10`', required=True)
# disable verbose 404 error message app.config['ERROR_404_HELP'] = False # create DB engine db_engine = DatabaseEngine() # create plot info plot_info = PlotInfo(db_engine, app.logger) # create ÖREB info oereb_info = OerebInfo(app.logger) # create plot owner info plot_owner = PlotOwner(db_engine, app.logger) # request parser pos_parser = reqparse.RequestParser(argument_class=CaseInsensitiveArgument) pos_parser.add_argument('x', type=float, required=True) pos_parser.add_argument('y', type=float, required=True) plot_owner_parser = reqparse.RequestParser( argument_class=CaseInsensitiveArgument) plot_owner_parser.add_argument('token') # routes @api.route('/', endpoint='root') class QueryPos(Resource): @api.param('x', 'X coordinate in LV95', required=True) @api.param('y', 'Y coordinate in LV95', required=True) @api.expect(pos_parser) def get(self):
# | it under the terms of the GNU General Public License as published by | # | the Free Software Foundation, either version 3 of the License, or | # | (at your option) any later version. | # | | # | This program is distributed in the hope that it will be useful, | # | but WITHOUT ANY WARRANTY; without even the implied warranty of | # | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | # | GNU General Public License for more details. | # | | # | You should have received a copy of the GNU General Public License | # | along with this program. If not, see <http://www.gnu.org/licenses/>. | # +---------------------------------------------------------------------------+ from flask_restplus import reqparse new_symbol = reqparse.RequestParser() new_symbol.add_argument('name', type = str, required = True, location = 'json', help = "Name of the symbol") add_field = reqparse.RequestParser() add_field.add_argument('fid_before_new', type = str, required = False, location = 'json', help = "ID of the field the new field should be inserted after")
from flask_login import login_user, login_required, logout_user, current_user from werkzeug.security import generate_password_hash, check_password_hash from flask_restplus import Namespace, Resource, reqparse from ..models import UserModel from ..config import Config from ..util.query_util import fix_ids import logging logger = logging.getLogger('gunicorn.error') api = Namespace('user', description='User related operations') register = reqparse.RequestParser() register.add_argument('username', required=True, location='json') register.add_argument('password', required=True, location='json') register.add_argument('email', location='json') register.add_argument('name', location='json') login = reqparse.RequestParser() login.add_argument('password', required=True, location='json') login.add_argument('username', required=True, location='json') set_password = reqparse.RequestParser() set_password.add_argument('password', required=True, location='json') set_password.add_argument('new_password', required=True, location='json') @api.route('/') class User(Resource): @login_required
''' * Author : see AUTHORS * Licence: MIT, see LICENSE ''' from flask_restplus import reqparse user_login_arguments = reqparse.RequestParser() user_login_arguments.add_argument('username', type=str, help='username', required=True, location='json') user_login_arguments.add_argument('password', type=str, help='password', required=True, location='json') user_change_password_arguments = reqparse.RequestParser() user_change_password_arguments.add_argument('old_password', type=str, help='old password', required=True) user_change_password_arguments.add_argument('new_password', type=str, help='new password', required=True) change_user_role_arguments = reqparse.RequestParser() change_user_role_arguments.add_argument('user_id',
def get(self): """get chemprops info based on search criteria""" callParams = ('ChemicalName', 'Abbreviation', 'TradeName', 'uSMILES') parser = reqparse.RequestParser( ) # marshmallow is preferred parser, this is technically deprecated but supported long term parser.add_argument('polfil', required=True, help=ChemPropsApiDoc.getDoc('get', '/', 'polfil')) parser.add_argument('nmId', required=True, help=ChemPropsApiDoc.getDoc('get', '/', 'nmId')) for p in callParams: parser.add_argument(p, required=(p == 'ChemicalName'), help=ChemPropsApiDoc.getDoc('get', '/', p)) args = parser.parse_args() cp = nmChemPropsAPI(args['nmId']) polfil = args['polfil'] params = dict() for p in callParams: if args[p] is not None: params[p] = args[p] rv = {} data = None try: if polfil == 'fil': # filler rv = cp.searchFillers(params) if rv is not None: data = { 'StandardName': rv['_id'], 'density': rv['_density'] } marshal(data, ChemPropsDto.chemprops) Config.getApp().logger.debug(__name__ + ' chemprops.get(\'' + polfil + '\', ' + str(params) + '): returned - ' + str(rv)) elif polfil == 'pol': # polymer rv = cp.searchPolymers(params) if rv is not None: Config.getApp().logger.debug(__name__ + ' chemprops.get(\'' + polfil + '\', ' + str(params) + '): returned - ' + str(rv)) data = { 'StandardName': rv['_stdname'], 'density': rv['_density'], 'uSMILES': rv['_id'] } marshal(data, ChemPropsDto.chemprops) else: return None, 400 # pol or fil required if data is not None: return data, 200 else: return None, 404 except: fullStr = traceback.format_exc() Config.getApp().logger.error(__name__ + 'error executing chemprops.get(\'' + polfil + '\', ' + str(params) + '): ' + fullStr) # data.StandardName = '' # data.density = float('nan') return None, 500
from flask import Flask, request from flask_restplus import Resource, Api, reqparse from scouter import Scouter app = Flask(__name__) api = Api(app, version='1.0', title="Location intelligence API", description='REST API that provides location intelligence data',) api.namespaces.clear() ns = api.namespace('peers-insight', description='Get insight into peers by your location') scouter = Scouter() peers_parser = reqparse.RequestParser() peers_parser.add_argument('lat', type=float, required=True, help='Latitude of your location') peers_parser.add_argument('lon', type=float, required=True, help='Longitude of your location') @ns.route('/peers') @ns.expect(peers_parser) class Peers(Resource): def get(self): """ Returns ranked list of restaurants in similar location """ args = request.args latitude = float(args['lat']) longitude = float(args['lon']) ret = scouter.similarly_located_restaurants(longitude, latitude) return ret if __name__ == '__main__':
''' * Author : see AUTHORS * Licence: MIT, see LICENSE ''' from src.api.fitcrack.argumentsParser import pagination from flask_restplus import reqparse dictionary_parser = pagination.copy() dictionary_parser.add_argument('search', type=str, required=False) dictionaryFromFile_parser = reqparse.RequestParser() dictionaryFromFile_parser.add_argument('files', type=list, required=True, location='json') dictionaryFromFile_parser.add_argument('sort', type=bool, location='json')
from flask_restplus import reqparse def create_partial_parser(parser): partial_parser = parser.copy() for arg in partial_parser.args: arg.required = False return partial_parser pagination_arguments = reqparse.RequestParser() pagination_arguments.add_argument('page', type=int, location='args') pagination_arguments.add_argument('per_page', type=int, default=10, location='args') bulk_delete_parser = reqparse.RequestParser() bulk_delete_parser.add_argument('ids', type=list, required=True, location='json')
'title': fields.String(), 'category': fields.String(), 'author': fields.String(), 'year': fields.Integer() }) new_book_marshaller = book_ns.model( 'BookModel', { 'id': fields.Integer(), 'title': fields.String(), 'category': fields.String(), 'author': fields.String(), 'year': fields.Integer() }) query_parser = reqparse.RequestParser() query_parser.add_argument('title', type=str, required=False) query_parser.add_argument('category', type=str, required=False) query_parser.add_argument('author', type=str, required=False) query_parser.add_argument('year', type=int, required=False) query_parser.add_argument('year1', type=int, required=False) query_parser.add_argument('year2', type=int, required=False) @book_ns.route('') @book_ns.response(400, 'Bad request') class Book(Resource): @book_ns.response(201, 'Created') @book_ns.marshal_with(new_book_marshaller, code=201) @book_ns.expect(book_marshaller, validate=True) def post(self):
from flask import request, jsonify from flask_restplus import Namespace, Resource, fields, reqparse, inputs import requests from requests.auth import HTTPBasicAuth api = Namespace('openData', 'wrapper of end point without autorization') parserSearch = reqparse.RequestParser() parserSearch.add_argument('address', type=inputs.regex(""), help="address of the appartment", default="42, West Mead", required=True) parserSearch.add_argument('postcode', type=inputs.regex(""), help="postcode of the appartment", default="HA4 0TL", required=True) parserLmkey = reqparse.RequestParser() parserLmkey.add_argument('lmkey', type=inputs.natural, help="lmkey of the appartment", default="1827209002922020092007053442338480", required=True) @api.route('/api/v1/domestic/search') class search(Resource): @api.response(200,"Success") @api.expect(parserSearch) def get(self): """ :return: the search of an appartment based on address and postcode """ url = "https://epc.opendatacommunities.org/api/v1/domestic/search" user = "******"
def post(self): """Returns a JWT access token for this user. email/password authentication is strictly enforced; no other methods should work. """ data = request.get_json() # data = request.data print("data: ", data) arg_parser = reqparse.RequestParser() arg_parser.add_argument( "exp", default=15552000, help="Parameter must be an integer", type=int ) args = arg_parser.parse_args() print(args) auth = request.authorization print("auth req: ", auth) if not auth: # Try extracting from POST body print("here") auth = request.get_json() print("here") print("auth: ", auth) if not auth or not ("email" in auth and "password" in auth): abort(401, "Missing authentication credentials") # if auth["is_driver"]: # # if it is a driver # user = Driver.identify(auth["email"]) # password = auth["password"] # else: # # If it is a restaurant # user = Restaurant.identify(auth["email"]) # password = auth["password"] is_driver = True user = Driver.identify(auth["email"]) password = auth["password"] if not user: user = Restaurant.identify(auth["email"]) is_driver = False if not user or not user.verify_password(password): current_app.logger.warn( "Incorrect credentials for {} from {}".format( auth["email"], *request.access_route ) ) abort(401, "Incorrect email or password") access_token = user.gen_access_token(args["exp"]) current_app.logger.info("[AUTH] User {} logged IN from {}".format( user.email, *request.access_route )) access_token.update({ "is_driver": is_driver }) # return resp, 200 return access_token
class MineTypeDetailResource(Resource, UserMixin, ErrorMixin): parser = reqparse.RequestParser(trim=True) parser.add_argument( 'mine_type_guid', type=str, help= 'Unique identifier for the mine type with which to associate this details record.' ) parser.add_argument('mine_disturbance_code', type=str, help='Mine disturbance type identifier.') parser.add_argument('mine_commodity_code', type=str, help='Mine commodity type identifier.') @api.expect(parser) @requires_role_mine_edit def post(self): data = self.parser.parse_args() mine_type_guid = data['mine_type_guid'] mine_disturbance_code = data['mine_disturbance_code'] mine_commodity_code = data['mine_commodity_code'] if not mine_type_guid: self.raise_error(400, 'Error: Missing mine_type_guid.') if not mine_disturbance_code and not mine_commodity_code: self.raise_error( 400, 'Error: Missing mine_disturbance_code or mine_commodity_code.') if mine_disturbance_code and mine_commodity_code: self.raise_error( 400, 'Error: Unable to create mine_type_detail with disturbance and commodity.' ) try: mine_type_detail = MineTypeDetail.create_mine_type_detail( mine_type_guid, mine_disturbance_code, mine_commodity_code, add_to_session=False) if mine_disturbance_code: (code, name, config) = (mine_disturbance_code, 'mine_disturbance_code', DISTURBANCE_CODES_CONFIG) if mine_commodity_code: (code, name, config) = (mine_commodity_code, 'mine_commodity_code', COMMODITY_CODES_CONFIG) try: mine_type = MineType.find_by_guid(mine_type_guid) assert mine_type.mine_tenure_type_code in config[code][ 'mine_tenure_type_codes'] except (AssertionError, KeyError) as e: self.raise_error(400, 'Error: Invalid ' + name + '.') mine_type_detail.save() except exc.IntegrityError as e: self.raise_error(400, 'Error: Unable to create mine_type_detail.') return mine_type_detail.json() @api.expect(parser) @requires_role_mine_edit def delete(self, mine_type_detail_xref_guid=None): data = self.parser.parse_args() if not mine_type_detail_xref_guid: self.raise_error(400, 'Error: Missing mine_type_detail_xref_guid.') mine_type_detail = MineTypeDetail.find_by_guid( mine_type_detail_xref_guid) if not mine_type_detail: self.raise_error(400, 'Error: Invalid mine_type_detail_guid.') try: MineTypeDetail.expire_record(mine_type_detail) except exc.IntegrityError as e: self.raise_error(400, 'Error: Unable to update mine_type_detail.') return mine_type_detail.json()
from google_images_download import google_images_download as gid from ..util.pagination_util import Pagination from ..util import query_util, coco_util from ..models import * import datetime import json import os api = Namespace('dataset', description='Dataset related operations') dataset_create = reqparse.RequestParser() dataset_create.add_argument('name', required=True) dataset_create.add_argument('categories', type=list, required=False, location='json', help="List of default categories for sub images") page_data = reqparse.RequestParser() page_data.add_argument('page', default=1, type=int) page_data.add_argument('limit', default=20, type=int) page_data.add_argument('folder', required=False, default='', help='Folder for data') delete_data = reqparse.RequestParser() delete_data.add_argument('fully', default=False, type=bool, help="Fully delete dataset (no undo)") coco_upload = reqparse.RequestParser() coco_upload.add_argument('coco', location='files', type=FileStorage, required=True, help='Json coco')
from app.commons.auth.moudles import TokenBase, VerificationCode from app.commons.files_utils import FileHandler from app.commons.auth.moudles import VerificationCode from app.commons.change_format import RET, add_response from app.commons.log_handler import logger from app.commons.db_utils.db import DB from app.commons.my_exception import DBError, DBNotExistError, SendEmailError from app.commons.token_handler import create_token from app.core import User from app.commons.token_handler import create_verification_code from app.commons.send_email import SendEmail from app.commons.error_handler.error_register import ErrorRegister ns = Namespace('users') base_parser = reqparse.RequestParser() base_parser.add_argument('Authorization', type=str, location='headers', required=True) login_parser = ns.parser() login_parser.add_argument('account', type=str, required=True, location='form') login_parser.add_argument('password', type=str, required=True, location='form') ErrorRegister(ns, exceptions=[DBError, DBNotExistError, SendEmailError]) # Login,登录方式:账户名登录 @ns.route('/account-login') class UserLoginByAccount(Resource): @ns.doc(parser=login_parser) def post(self, *args): args = login_parser.parse_args()
class MineTailingsStorageFacilityListResource(Resource, UserMixin): parser = reqparse.RequestParser() parser.add_argument( 'mine_tailings_storage_facility_name', type=str, trim=True, help='Name of the tailings storage facility.', required=True) @api.doc(description='Gets the tailing storage facilites for the given mine') @api.marshal_with( MINE_TSF_MODEL, envelope='mine_tailings_storage_facilities', as_list=True, code=200) @requires_role_view_all def get(self, mine_guid): mine = Mine.find_by_mine_guid(mine_guid) if not mine: raise NotFound('Mine not found.') return mine.mine_tailings_storage_facilities @api.doc(description='Creates a new tailing storage facility for the given mine') @api.marshal_with(MINE_TSF_MODEL, code=200) @requires_role_mine_edit def post(self, mine_guid): mine = Mine.find_by_mine_guid(mine_guid) if not mine: raise NotFound('Mine not found.') # see if this would be the first TSF mine_tsf_list = mine.mine_tailings_storage_facilities is_mine_first_tsf = len(mine_tsf_list) == 0 data = self.parser.parse_args() mine_tsf = MineTailingsStorageFacility.create( mine, mine_tailings_storage_facility_name=data['mine_tailings_storage_facility_name']) mine.mine_tailings_storage_facilities.append(mine_tsf) if is_mine_first_tsf: try: req_documents_url = get_documents_svc_url('/required?category=TSF&sub_category=INI') get_tsf_docs_resp = requests.get( req_documents_url, headers={'Authorization': request.headers.get('Authorization')}) if get_tsf_docs_resp.status_code != 200: raise Exception(f'get_tsf_req_docs returned >> {get_tsf_docs_resp.status_code}') tsf_required_documents = get_tsf_docs_resp.json()['required_documents'] new_expected_documents = [] for tsf_req_doc in tsf_required_documents: new_expected_documents.append({ 'req_document_guid': tsf_req_doc['req_document_guid'], 'document_name': tsf_req_doc['req_document_name'], 'document_description': tsf_req_doc['description'], 'document_due_date_type': tsf_req_doc['req_document_due_date_type'], 'document_due_date_period_months': tsf_req_doc['req_document_due_date_period_months'], 'hsrc_code': tsf_req_doc['hsrc_code'] }) doc_assignment_response = requests.post( get_documents_svc_url('/expected/mines/' + str(mine_guid)), headers={'Authorization': request.headers.get('Authorization')}, json={'documents': new_expected_documents}) if doc_assignment_response.status_code != 200: raise Exception( f"Error creating tsf expected documents >> {doc_assignment_response}") except Exception as e: db.session.rollback() current_app.logger.error(str(e)) raise InternalServerError(str(e) + ", tsf not created") mine.save() return mine_tsf