def register_graphql(namespace: Namespace, api: Api): """Method used to register the GraphQL namespace and endpoint.""" # Create expected headers and payload headers = api.parser() payload = api.model( 'Payload', { 'query': fields.String(required=True, description='GraphQL query or mutation', example='{allIndicatorTypes{nodes{id,name}}}') }) @namespace.route('/graphql', endpoint='with-parser') @namespace.doc() class GraphQL(Resource): @namespace.expect(headers, payload, validate=True) def post(self): """ Execute GraphQL queries and mutations Use this endpoint to send http request to the GraphQL API. """ payload = request.json try: # Validate http request payload and convert it to GraphQL document graphql_document = utils.validate_graphql_request( payload['query']) # Verify GraphQL mutation can be handled interceptor = Interceptor() mutation_name = interceptor.get_mutation_name(graphql_document) # Surcharge payload before request if mutation_name: mutation_arguments = interceptor.get_mutation_arguments( graphql_document) payload['query'] = interceptor.before_request( mutation_name, mutation_arguments) # Execute request on GraphQL API status, data = utils.execute_graphql_request(payload) if status != 200: raise RequestException(status, data) # Execute custom scripts after request if mutation_name: data = interceptor.after_request(mutation_name, data) return make_response(jsonify(data), status) except RequestException as exception: return exception.to_response() except APIError as exception: return make_response( jsonify({'message': exception.explanation}), exception.status_code)
def init_args(api: Api) -> Any: upload_parser = api.parser() upload_parser.add_argument('file', location='files', help="input binary file", type=FileStorage, required=True) upload_parser.add_argument('language', type=str, help="recognition language", required=False, default="rus+eng", choices=["rus+eng", "rus", "eng"]) upload_parser.add_argument("with_attachments", type=bool, required=False, help="option to enable analysis of attached files.", default=False) upload_parser.add_argument("return_html", type=bool, required=False, help="an option to return the response in html form.", default=False) upload_parser.add_argument("document_type", type=str, required=False, help="document type", default="", choices=["", "law", "article"]) upload_parser.add_argument("structure_type", type=str, required=False, help="output structure type (linear or tree)", default="linear", choices=["linear", "tree"]) return upload_parser
def create_app(): template_path = "../resources/templates" static_path = "../resources/static" flask_app = Flask(__name__, template_folder=template_path, static_folder=static_path) # Crate Views logger.info("Create Server Health Check") create_view(flask_app) Bootstrap(flask_app) flask_app.config['BOOTSTRAP_SERVE_LOCAL'] = True # Create Api rest_api = Api(flask_app, doc=False) rest_parser = rest_api.parser() logger.info("Create Api For Check") create_api(rest_api) logger.info("All Application Create Done") return flask_app
import importlib from analytics_lst import analytics as lst from anova import anova app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) api = Api(app) #server_path = r"C:\Users\Harish\PycharmProjects\cceproject\data\raw_data" if os.path.exists(os.path.join(os.path.expanduser("~"), "serverdata")): server_path = os.path.join(os.path.expanduser("~"), "serverdata") else: server_path = os.path.join(os.path.expanduser("~"), "serverdata") os.makedirs(server_path) file_upload_model = api.parser() file_upload_model.add_argument('file', type=FileStorage, location='files', required=True) file_visualize_model = api.parser() file_visualize_model.add_argument('request_id', type=str, location='args') output_model = api.parser() output_model.add_argument('request_id', type=str, location='args') output_model.add_argument('method', type=str, location='args') output_model.add_argument('analytic_name', type=str, location='args') preprocess_model = api.model("preprocess_request", { 'request_id': fields.String,
'TaskID', { 'deadline': fields.Integer, 'task_id': fields.Integer, 'task_name': fields.String(required=True, description='Name of Task'), 'user_name': fields.String(required=True, description='Worker the task is assigned to'), 'priority': fields.Integer(required=True, description='Priority of the task'), }) # parser for worker parser_person = api.parser() parser_person.add_argument('name', type=str, required=True, help='Name of worker', location='form') parser_person.add_argument('team', type=str, required=True, help='Team of worker', location='form') # parser to delete worker parser_person_delete = api.parser() parser_person_delete.add_argument('name',
# copy the model definition from data api and register models here node_entity = api.model('NodeEntity', node.NODE_ENTITY) link_entity = api.model('LinkEntity', link.LINK_ENTITY) traffic_entity = api.model('TrafficEntity', traffic.TRAFFIC_ENTITY) multicast_entity = api.model('MulticastEntity', multicast_group.MULTICAST_ENTITY) INTERNAL_DATA = { 'node': fields.Nested(node_entity), 'link': fields.Nested(link_entity), 'traffic': fields.Nested(traffic_entity), 'multicast_group': fields.Nested(multicast_entity), } internal_data = api.model('InternalData', INTERNAL_DATA) input_parser = api.parser() input_parser.add_argument( 'file', type=FileStorage, location='files', required=True) error_message = api.model('ErrorMessage', ERROR_MESSAGE) @api.response(400, RESPONSE_EXPECTED_ERROR, [error_message]) @api.response(500, RESPONSE_UNKNOWN_ERROR) @api.route("") @api.doc( model=internal_data # success output (for response 200) ) class ImportOpeartion(Resource): @api.doc( description="Import an OEM database file into the backend.", body=input_parser
def test_api_shortcut(self): api = Api(self.app) parser = api.parser() self.assertIsInstance(parser, RequestParser)
} def response_question6(query_result_collection, query_result_entries): result = {"indicator": query_result_collection[0], "indicator_value": query_result_collection[1], "entries": [] } for res in query_result_entries: result["entries"].append({"country": res[0], "value": res[1] }) return result parser = api.parser() parser_2 = api.parser() parser_3 = api.parser() parser.add_argument('indicator_id', type=str, location='args') parser_2.add_argument('order_by', type=str, location='args', action='split') parser_3.add_argument('q', type=str, location='args') @api.route("/collections") class Task1and3(Resource): @api.response(200, 'Success') @api.response(201, 'Created') @api.response(400, 'Bad Request') @api.response(404, 'Not Found') @api.param('indicator_id', 'The indicator identifier (e.g."NY.GDP.MKTP.CD")') @api.doc(parser=parser, description="Add a new world bank collection")
def create_app(self) -> Flask: """ Initialises the the app and the api object. It adds all the provided endpoints. Also does this method define the documentation for the swagger UI and the definitions for the api object structure. :returns: the app object """ # check if lingeling is present try: subprocess.check_output(["lingeling", "--version"]) except Exception as e: raise Exception( "The SAT solver binary could not be called. " "Please make sure that lingeling is build and present in the path." ) from e app = Flask(__name__) if app.config['DEBUG']: app.config['PROFILE'] = True from werkzeug.middleware.profiler import ProfilerMiddleware app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30]) CORS(app) # This lets the child processes ignore the SIG int signal handler. original_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) pool: ProcessPool = ProcessPool( max_workers=int(multiprocessing.cpu_count() / 2)) app.config['RESTPLUS_VALIDATE'] = True data_store = DataStore(self.data_path) api = Api( app, version='1.0', title='Linear layout API', description= 'Through this API one can request for a linear layout of a graph in graphml format. \n' 'The actual computation of the linear layout is done using SAT solving. ' 'The instances are solved using [lingeling](http://fmv.jku.at/lingeling/)\n' '' 'See https://github.com/linear-layouts/SAT for more information') #: The schema definition of a page page_schema = api.model( 'Page', { 'id': fields.String(required=True, description='The id of this page', example="P1"), 'type': fields.String(description='The type of the page. \n' 'NONE allows all patterns', enum=['QUEUE', 'STACK', 'NONE'], required=True), 'constraint': fields.String( description='Additional constraints for the page', enum=['NONE', 'DISPERSIBLE', 'TREE', 'FOREST']) }) #: The schema definition of a constraint constraint_schema = api.model( 'Constraint', { 'type': fields.String( description=""" EDGES_ON_PAGES: assigns edges to specific pages. The edges are encoded independently from each other arguments: edge ids modifier: page ids to assign the edges to (OR joined) EDGES_SAME_PAGES: assigns edges to the same page. Only implemented up to to four pages arguments: the edge ids modifier: none EDGES_DIFFERENT_PAGES: all edges have to be on different pages. Only works up to as many edges as there are pages arguments: the edge ids modifier none NOT_ALL_IN_SAME_PAGE: not all edges can be on the same page. Only works when at least two pages are available arguments: the edge ids modifier none EDGES_TO_SUB_ARC_ON_PAGES: If any node shares an edge with the nodes named in arguments and is between the two nodes, then this edge is restricted to the pages named in modifier. arguments: the two vertexes to restrict the edges from modifier: the pages to restrict the edges to EDGES_FROM_NODES_ON_PAGES: All edges involving the nodes have to be on the given page. arguments: the vertices to restrict the edges from modifier: the pages to restrict the edges to NODES_PREDECESSOR: one set of nodes are before another set of nodes arguments: the node ids to be before modifier: the node ids to be after TREAT_GRAPH_DIRECTED: Treat the graph according to direction NODES_ABSOLUTE_ORDER: deprecated. see NODES_REQUIRE_ABSOLUTE_ORDER NODES_REQUIRE_ABSOLUTE_ORDER: The given nodes have to be in exactly the given order and no nodes are allowed in between. arguments: the nodes in the required order modifier: none NODES_REQUIRE_PARTIAL_ORDER: The given nodes have to be the given relative order arguments: the nodes in the order modifier: none NODES_FORBID_PARTIAL_ORDER: The given nodes have to be NOT the given relative order. Two nodes flipped already satisfy this constraint. arguments: the nodes in the forbidden order modifier: none NODES_CONSECUTIVE: The given two nodes have to be next to each other in any order. Currently only implemented for 2 Nodes arguments: the two nodes to be made consecutive modifier: none NODES_SET_FIRST: The given node has to be the first in any order. arguments: the node to be the first modifier: none NODES_SET_LAST: The given node has to be the last in any order. arguments: the node to be the last modifier: none EDGES_SAME_PAGES_INCIDENT_NODE: All edges incident to this vertex should be on same page. arguments: the incident node modifier: none EDGES_DIFFERENT_PAGES_INCIDENT_NODE: All edges incident to this vertex should be on different pages. arguments: the incident node modifier: none EDGES_ON_PAGES_INCIDENT_NODE: All edges incident to this vertex should be on mentioned pages. arguments: the incident node modifier: none """, enum=[ "EDGES_ON_PAGES", "EDGES_SAME_PAGES", "EDGES_DIFFERENT_PAGES", "NOT_ALL_IN_SAME_PAGE", "EDGES_TO_SUB_ARC_ON_PAGES", "EDGES_FROM_NODES_ON_PAGES", "NODES_PREDECESSOR", "TREAT_GRAPH_DIRECTED", "NODES_ABSOLUTE_ORDER", "NODES_REQUIRE_ABSOLUTE_ORDER", "NODES_REQUIRE_PARTIAL_ORDER", "NODES_FORBID_PARTIAL_ORDER", "NODES_CONSECUTIVE", "NODES_SET_FIRST", "NODES_SET_LAST", "EDGES_SAME_PAGES_INCIDENT_NODE", "EDGES_DIFFERENT_PAGES_INCIDENT_NODE", "EDGES_ON_PAGES_INCIDENT_NODE" ], example="NODES_PREDECESSOR", required=True), 'arguments': fields.List( fields.String, min_items=1, required=True, description= 'The ids of the elements affected by this constraint', example=["1"]), 'modifier': fields.List(fields.String, description='The ids of the constraint modifier.', example=["0"]), }, ) assigment_schema = api.model( 'Assigment', { 'edge': fields.String(description='The id of the edge', required=True), 'page': fields.String( description='The id of the page the edge is assigned to', required=True) }) error_schema = api.model( 'Error', { 'message': fields.String(description='The error message', required=True, readonly=True) }) # the schema definition for the full linear layout linear_layout_schema = api.model( 'Linear layout', { 'id': fields.Integer(description='The id of the embedding', readonly=True), 'graph': fields.String( description= 'This field contains a graphml definition encoded with base64. ' 'The example value is K3.', required=True, example=self._k3_str_as_example), 'pages': fields.List(fields.Nested(page_schema), min_items=1, required=True, unique=True), 'constraints': fields.List(fields.Nested(constraint_schema)), 'status': fields.String( description= 'The current processing status of the computation', enum=['IN_PROGRESS', 'FINISHED', 'FAILED', 'CANCELLED'], readonly=True), 'assignments': fields.List(fields.Nested(assigment_schema), readonly=True, description='A list of edge to page assignments'), 'vertex_order': fields.List( fields.String, readonly=True, description= 'The order in which the vertices have to be placed on the spine.' ), 'satisfiable': fields.Boolean( readonly=True, description= 'On finished instances this field indicates if the given ' 'problem is satisfiable'), 'rawSolverResult': fields.String( readonly=True, description= 'This field contains the comment lines of the solver which ' 'provides some data on the solved SAT instance'), 'message': fields.String( readonly=True, description= "This field contains currently the error message from " "the background processing"), 'created': fields.DateTime( readonly=True, description='A timestamp when this instance was created'), 'finished': fields.DateTime( readonly=True, description='A timestamp when this instance was solved'), }) list_parser = api.parser() list_parser.add_argument('limit', type=int, help='How many objects should be returned', location='query', default=20) list_parser.add_argument('offset', type=int, help='Where to start counting', location='query', default=0) @api.route('/embeddings') class EmbeddingList(Resource): @api.doc('list_embeddings') @api.response(code=200, description="Success", model=[linear_layout_schema]) @api.response(code=500, description="Server Error", model=error_schema) @api.expect(list_parser) def get(self): """ List all embeddings """ limit = int(request.args.get('limit', 20)) if (limit < 1) or (limit > 50): abort(400, "limit has to be in range [1,50]") offset = int(request.args.get('offset', 0)) if offset < 0: abort(400, "offset has to be not negative") return jsonify(data_store.get_all(limit=limit, offset=offset)) @api.doc('create_embedding') @api.expect(linear_layout_schema) @api.param('async', 'Should the processing be handled asynchronous', location="query", default=False, type=bool) @api.response(code=200, description="Success", model=linear_layout_schema) @api.response(code=500, description="Server Error", model=error_schema) @api.response(code=501, description="Not Implemented", model=error_schema) @api.response(code=400, description="Bad Request", model=error_schema) def post(self): """ Create a new embedding """ entity = request.get_json() # looks weird but is the only reliable way to find out if a string value is a true boolean ;-) # see https://stackoverflow.com/questions/715417/converting-from-a-string-to-boolean-in-python handle_async = request.args.get('async', "", type=str).lower() in yes_list try: entity['created'] = datetime.datetime.now( datetime.timezone.utc).isoformat() b64_graph_str = entity.get('graph') try: graph_str = base64.b64decode(b64_graph_str) node_ids, edges = get_nodes_and_edges_from_graph( graph_str) # node_ids ==> List(str) # edges ==> List(Edge) except Exception as e: app.logger.exception(e) raise BadRequest( "The graph string has to be a base64 encoded graphml string! " "The exact error was: " + str(e)) len_nodes = len(node_ids) # Number of nodes len_edges = len(edges) # Number of edges if len_edges > 1900 or len_nodes > 600: raise BadRequest( "For fairness reasons this API will only handle graphs with less than 300 vertices and 900 " "edges. Your graph has {} vertices and {} edges which exceed the limit." "".format(len_nodes, len_edges)) # Check if self loops are present! We do not support self loops for e in edges: if e.source == e.target: raise BadRequest( "The Implementation only supports graphs where " "every edge has two distinct start and end nodes" ) # ignore double edges # # validate for no double edges # all_edge_endpoints = [{e.source, e.target} for e in edges] # duplicate_edges = get_duplicates(all_edge_endpoints) # if len(duplicate_edges) > 0: # abort(400, # "Multiedges are not allowed. " # "The following edges were recognized as duplicate {}".format(duplicate_edges)) # validate for unique edge ids duplicate_edge_ids = get_duplicates([e.id for e in edges]) if len(duplicate_edge_ids) > 0: abort( 400, "Edge ids have to be unique" "The following ids were recognized as duplicate {}" .format(duplicate_edge_ids)) # validate page id uniqueness page_ids = [p['id'] for p in entity.get('pages')] duplicate_page_ids = get_duplicates(page_ids) if len(duplicate_page_ids) > 0: abort( 400, "Duplicated page ids are not allowed. " "The following id were recognized as duplicate {}". format(duplicate_page_ids)) entity['status'] = 'IN_PROGRESS' entity = data_store.insert_new_element( entity) # entity id is returned here # validate graph not empty if len(page_ids) == 0 or len_edges == 0 or len_nodes == 0: abort( 400, "Please submit a graph with at least one node, edge and page" ) if handle_async: # abort(501, "Async handling is not enabled.") future_result: ProcessFuture = pool.schedule( SolverInterface.solve, (node_ids, edges, entity.get('pages'), entity.get('constraints'), entity['id'])) future_result.add_done_callback( processing_finished_callback) future_result.done() # remove old futures remove_old_jobs() jobs.append(QueueItem(entity.get('id'), future_result)) else: try: entity = handle_solver_result( SolverInterface.solve( node_ids, edges, entity.get('pages'), entity.get('constraints'), entity['id'])) except Exception as e1: error_callback(e1) entity = data_store.get_by_id(entity['id']) return jsonify(entity) except HTTPException as e: raise e except Exception as e: raise InternalServerError( "The error {} \noccured from this body \n{}".format( str(e), request.get_data(as_text=True))) from e @api.route('/embeddings/<string:id>') @api.response(404, 'Embedding not found', model=error_schema) @api.param('id', 'The task identifier') class SingleEmbedding(Resource): @api.doc('get_embedding') @api.response(code=200, description="Success", model=linear_layout_schema) def get(self, id): """ Get an embedding by id """ element = data_store.get_by_id(id) if not element: raise NotFound( "The given id {} was not present in the data store". format(id)) else: return jsonify(element) @api.doc('delete_embedding') @api.response(code=200, description="Success", model=linear_layout_schema) def delete(self, id): """ Cancel the computation for the given id. """ element = data_store.get_by_id(id) if not element: raise NotFound( "The given id {} was not present in the data store". format(id)) cancel_id = str(id) cancel_file_path = 'cancel.txt' # Check if file exists. Create cancel.txt if file doesn't exist if not os.path.exists(cancel_file_path): open(cancel_file_path, 'w').close() cancel_ids = [] with open(cancel_file_path, 'r') as f: csv_reader = csv.reader(f, delimiter=',') cancel_ids = [row[0] for row in csv_reader] if cancel_id not in cancel_ids: with open(cancel_file_path, 'a') as f: csv_writer = csv.writer(f, delimiter=',') csv_writer.writerow([cancel_id]) # cancel_ids.append(cancel_id) # with open(cancel_file_path, 'w') as f: # csv_writer = csv.writer(f, delimiter=',') # for cid in cancel_ids: # csv_writer.writerow([cid]) j_tmp = [j for j in jobs if str(j.id) == str(id)] if len(j_tmp) == 1: j_tmp[0].future.cancel() # element['status'] = 'FAILED' element['status'] = 'CANCELLED' element['message'] = 'The job was cancelled by user' data_store.update_entry(id, element) jobs.remove(j_tmp[0]) return jsonify(element) def processing_finished_callback(res: ProcessFuture): if not res.done() or res.cancelled(): pass else: exception = res.exception() if exception is not None: error_callback(exception) else: result = res.result() handle_solver_result(result) def error_callback(e_param: BaseException): try: raise e_param except IdRelatedException as e: id = e.entity_id entity = data_store.get_by_id(id) if not entity: raise e entity['status'] = 'FAILED' entity['message'] = e.message data_store.update_entry(id, entity) if type(e.cause) is HTTPException: raise e.cause else: raise e def handle_solver_result(result: SolverResult): entity = data_store.get_by_id(result.entity_id) if not entity: raise Exception( "The given id {} was not found in the data store".format( result.entity_id)) entity['status'] = 'FINISHED' entity['satisfiable'] = result.satisfiable entity['assignments'] = result.page_assignments entity['vertex_order'] = result.vertex_order entity['rawSolverResult'] = result.solver_output entity['finished'] = datetime.datetime.now( datetime.timezone.utc).isoformat() entity = data_store.update_entry(result.entity_id, entity) print( "Finished job with id {} in {} s. " "Including waiting time in the queue".format( entity['id'], str(parse(entity['finished']) - parse(entity['created'])))) return entity def signal_handler(sig, frame): data_store.prepare_shutdown() remove_old_jobs() print( "Shutdown request. " "Currently {} Jobs are in queue and will be processed on server start." .format(len(jobs))) try: pool.stop() pool.join(timeout=2) finally: original_sigint_handler() signal.signal(signal.SIGINT, signal_handler) unfinished_jobs = data_store.get_unfinished_jobs() if len(unfinished_jobs) > 0: print("Resuming {} unfinished jobs".format(len(unfinished_jobs))) for job in unfinished_jobs: b64_graph_str = job.get('graph') graph_str = base64.b64decode(b64_graph_str) node_ids, edges = get_nodes_and_edges_from_graph(graph_str) future: ProcessFuture = pool.schedule( SolverInterface.solve, (node_ids, edges, job.get('pages'), job.get('constraints'), job['id'])) future.add_done_callback(processing_finished_callback) jobs.append(QueueItem(job.get('id'), future)) return app
'''__init__.py file''' from flask import Blueprint from flask_restplus import Api from app import app from .home import api as home_api swagger = Blueprint('JENKINS_AUTOMATION_API', __name__, url_prefix='/api') api = Api(swagger, version='2.1', title='JENKINS AUTOMATION API') api.add_namespace(home_api) app.register_blueprint(swagger) parser = api.parser()
ensure_can_edit_user, ensure_can_edit_contact) from fooapi.schemata import ( LimitOffsetSchema, UserSchema, ContactSchema, AccessTokenSchema) from fooapi.models import Contact from fooapi.utils import validation_errors_to_unicode_message api = Api(prefix='/api') # these parsers are here only for the purposes of Swagger UI generation auth_parser = api.parser() auth_parser.add_argument('X-Access-Token', type=str,location='headers') user_parser = api.parser() user_parser.add_argument('name', type=unicode, location='form') user_parser.add_argument('X-Access-Token', type=str,location='headers') contact_parser = api.parser() contact_parser.add_argument('phone_no', type=str, location='form') contact_parser.add_argument('email', type=str, location='form') contact_parser.add_argument('type', type=str, location='form', choices=Contact.NAMES_TO_TYPES.keys()) contact_parser.add_argument('X-Access-Token', type=str, location='headers') list_parser = api.parser() list_parser.add_argument('limit', type=int, location='args')
from werkzeug.datastructures import FileStorage from threading import Thread from settings import BaseConfig from job_model import JobStatus, Job, JobSchema # Extensions initialization # ========================= app = Flask(__name__) api = Api(app, version='1.0', title='Name classificator study API', description='This service using for training name classification model', ) ns = api.namespace('new-jobs', description='Jobs for ML models study') upload_parser = api.parser() upload_parser.add_argument('file', location=BaseConfig.UPLOAD_DIR, type=FileStorage, required=True) # Data layer - Collections # ======================== jobs = [] # Routes # ====== @ns.route('/') class JobList(Resource): # Shows a list of all jobs, and lets you POST to add new jobs def get(self): # List all jobs schema = JobSchema(many=True)
api.abort(422, "date from the request cannot be parsed: {}".format(e)) return dt def check_city(city): if city not in CITIES: api.abort(404, "City {} not found".format(city)) api = Api(title='Jitenshea: Bicycle-sharing data analysis', prefix='/api', doc=False, version='0.1', description="Retrieve some data related to bicycle-sharing data from some cities.") # Parsers station_list_parser = api.parser() station_list_parser.add_argument("limit", required=False, type=int, default=100, dest='limit', location='args', help='Limit') station_list_parser.add_argument("geojson", required=False, default=False, dest='geojson', location='args', help='GeoJSON format?') daily_parser = api.parser() daily_parser.add_argument("date", required=True, dest="date", location="args", help="day of the transactions (YYYY-MM-DD)") daily_parser.add_argument("window", required=False, type=int, default=0, dest="window", location="args", help="How many days?") daily_parser.add_argument("backward", required=False, type=inputs.boolean, default=True, dest="backward", location="args", help="Backward window of days or not?") daily_list_parser = api.parser() daily_list_parser.add_argument("limit", required=False, type=int, default=20,
def check_city(city): if city not in CITIES: api.abort(404, "City {} not found".format(city)) api = Api( title='Jitenshea: Bicycle-sharing data analysis', prefix='/api', doc=False, version='0.1', description= "Retrieve some data related to bicycle-sharing data from some cities.") # Parsers station_list_parser = api.parser() station_list_parser.add_argument("limit", required=False, type=int, default=100, dest='limit', location='args', help='Limit') station_list_parser.add_argument("geojson", required=False, default=False, dest='geojson', location='args', help='GeoJSON format?') daily_parser = api.parser()
return summary app = Flask(__name__) api = Api(app, version='1.0', title='Summary API', description='A simple review summarization API which uses Python\'s sumy library' ) app.config.SWAGGER_UI_DOC_EXPANSION = 'list' ns = api.namespace('sum/v1.0', 'Text Summary v1.0 ') parser = api.parser() parser.add_argument('reviews', required=True, location='json', help='Input Format -> {"reviews":[ {"reviewer_id":"string","reviewee_id":"string","score":"string","feedback":"string"}]}') parser_sum = api.parser() parser_sum.add_argument('sentences', required=True, location='json', help='Input Format -> {"sentences":["sentence1"]') ###### Definition of data model for documentation summary_marshaller = api.model('summary_marshaller',{ 'summary': fields.String(description='Summary of the review') }) message_marshaller = api.model('message_marshaller',{ 'message': fields.String(description='Api call status', required=True) })
from flask_restplus import reqparse import os import sys import server from test import run_test from datetime import datetime from server.routes.way_finder import WayFinder app = Flask(__name__, static_url_path='', static_folder='static', template_folder='templates') app.config['JSON_AS_ASCII'] = False api = Api(app, doc='/api/v1', prefix="/api/v1") api = api.namespace('', description='Сервис картографии для помещений') upload_parser = api.parser() upload_parser.add_argument('file', location='files', type=FileStorage, required=True) engine = create_engine('sqlite:///%s' % 'iamhere.db?charset=utf8', connect_args={'check_same_thread': False}) Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() @api.route('/building/<int:id>') class BuildingAPI(Resource): def get(self, id): return make_response(
from Gender_Classifier import retrainModel, normalize, name_encoding import tensorflow as tf import numpy as np import csv app = Flask(__name__) api = Api(app, version='1.0', title='Gender Classifer API', description='An API that classifies the gender given a first name') ns = api.namespace('api') parser = api.parser() parser.add_argument('Name', required=True, type=str, help='The persons name e.g Mary', location='form', action='append') modelParser = api.parser() modelParser.add_argument('Name', required=True, type=str, help='The Person\'s Name e.g Mary', location='form') modelParser.add_argument('Gender', required=True,
iris=data['complete_code'], name=data['name'], citycode=data['citycode'], city=data['city'], iris_type=data['type']) api = Api(service, title='INSEE/IRIS Geolocalizer', ui=False, prefix='/api', version='0.1', description="Retrieve some data related to the IRIS codes. Look for an IRIS from an address.") api.add_namespace(insee_api) geojson_parser = api.parser() geojson_parser.add_argument("geojson", type=inputs.boolean, default=False, location='args', help='GeoJSON') iris_code_parser = geojson_parser.copy() iris_code_parser.add_argument("limit", required=False, default=10, dest='limit', location='args', help='Limit') address_parser = geojson_parser.copy() address_parser.add_argument("q", required=True, dest='q', location='args', help='Query') coords_parser = geojson_parser.copy() coords_parser.add_argument("lat", required=True, type=float, dest='lat', location='args', help='Latitude') coords_parser.add_argument("lon", required=True, type=float, dest='lon', location='args',
if 'BASE_PATH' not in os.environ: os.environ['BASE_PATH'] = "" bp = Blueprint('diagram', __name__, url_prefix=os.environ['BASE_PATH']) # Initialize API with swagger parameters: api = Api(bp, default=u'GWAS Catalog diagram', default_label=u'GWAS Catalog updated diagram', description='This application filters GWAS Catalog association data to generate diagram.', doc='/documentation/', title = 'API documentation') app.register_blueprint(bp) # Preparing for filter paramters: fiterParams = api.parser() fiterParams.add_argument('pmid', type=int, required=False, help='Pubmed ID of a requested publication.') fiterParams.add_argument('trait', type=str, required=False, help='Trait of ontology term.') fiterParams.add_argument('pvalue', type=str, required=False, help='Upper boundary of the p-value (eg. 1e-8).') fiterParams.add_argument('sample', type=str, required=False, help='Part of the sample description.') fiterParams.add_argument('ancestry', type=str, required=False, help='Broad ancestry description of the samples.') fiterParams.add_argument('catalog_date', type=str, required=False, help='Upper boundary for the catalog publish date (eg. 2014-01-03).') fiterParams.add_argument('parent_term', type=str, required=False, help='Pipe separated list of required parent terms.') fiterParams.add_argument('dataType', type=str, required=False, help='Requested data type: "traits" or "associations".') # Enabling cross-site scripting (might need to be removed later): # cors = CORS(app)s # Parameters for filtering template spreadsheets: # fiterParams = api.model( "Diagram data filter application",{
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) import API_py3.M6 as M6 import API_py3.Log as Log app = Flask(__name__) api = Api(app, version='1.0', title='IRIS API', description='IRIS API', ) CORS(app, resources={r'/*': {'origins': '*'}}) get_req_parser = reqparse.RequestParser(bundle_errors=True) get_req_parser.add_argument('param', type=str, required=True) json_parser = api.parser() json_parser.add_argument('json', type=str, required=True, location='json', help='JSON BODY argument') arg_parser = api.parser() arg_parser.add_argument('json', type=str, required=True, help='URL JSON argument') rows_list = [] fields = [] class global_variable: values = {} def __init__(self, *args, **kwargs):
""" Sign in and get an authorization token. """ try: user = Users.authenticate(api.payload) if user: access_token = create_access_token(identity=user.id) return {"access_token": access_token} else: return 'The credentials provided were invalid', 401 except NoResultFound: return 'No user with those credentials was found', 401 header_parser = api.parser() header_parser.add_argument('Authorization', help='Bearer \{Token\}', location='headers') @products.route("/") @products.doc(responses={200: 'The product feed for the user'}) class Feed(Resource): filters_parser = api.parser() filters_parser.add_argument('country', help='Country to filter by') filters_parser.add_argument('min_price', help='Minimum price to filter by', type=int) filters_parser.add_argument('max_price', help='Maximum price to filter by',
from flask_restplus import Api, fields from werkzeug.exceptions import BadRequest import os import pymongo from pymongo import errors from bson import ObjectId import uuid MONGO_URI = os.getenv('MONGODB_URI') DATABASE = os.getenv('DATABASE') TABLE_USERS = os.getenv('TABLE_USERS') app = Flask(__name__) api = Api(app) JWTValidationParser = api.parser() JWTValidationParser.add_argument('token', location='args', required=True) JWTTokenModel = api.model('JWTToken', { 'token': fields.String(), }) UserModel = api.model('User', { 'id': fields.String(required=True), 'username': fields.String(required=True), 'email': fields.String(), 'password': fields.String(), 'first_name': fields.String(), 'last_name': fields.String() }, mask="id,username,email,first_name,last_name")
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path, 'app-db.sqlite'), ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) api = Api(app, version='1.0', title='LegalMation XMLParser', description="Parses text from xml file") ns = api.namespace('documents', description="Uploaded XML documents.") # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass db.init_app(app) # Fields for swagger document_api = api.model( 'Document', { 'id': fields.Integer(readOnly=True, description='The document unique identifier'), 'filename': fields.String(required=True, description='The document filename'), 'plaintiff': fields.String(required=True, description='The extracted plantiff text'), 'defendants': fields.String(required=True, description='The extracted defendants text') }) upload_parser = api.parser() upload_parser.add_argument('file', location='files', type=FileStorage, required=True) ''' ROUTES ''' @ns.route('/') class DocumentList(Resource): @ns.doc('list_documents') @ns.marshal_list_with(document_api) def get(self): '''List all documents''' all_documents = find_documents() return [dict(row) for row in all_documents] @ns.route('/<int:document_id>') @ns.response(404, 'Document not found') @ns.param('document_id', 'The document unique identifier') class Document(Resource): @ns.doc('get_document') @ns.marshal_with(document_api) def get(self, document_id): '''List one document by id''' document = find_document_by_id(document_id) if document is not None: return dict(document) else: api.abort(404, "Document {} doesn't exist".format(document_id)) @ns.route('/upload') @ns.expect(upload_parser) @ns.response(400, 'Upload failure') class UploadDocument(Resource): @ns.doc('upload_document') @ns.marshal_with(document_api) def post(self): '''Upload an xml file''' if 'file' not in request.files: api.abort(400, 'No file part') file = request.files['file'] if file: try: lm_xml_parser = XmlParser(file) # Parses the xml file and extracts its data parsed_data = lm_xml_parser.extract() # Insert into database and get the newly created id row_id = insert_document(file.filename, parsed_data['plaintiff'], parsed_data['defendants']) # Return the newly inserted document as json object document = find_document_by_id(row_id) return dict(document) except IOError: abort(400, 'Invalid xml file.') return app
for x in document['entries']: if x['country'] == country: return { "collection_id": document['id'], "indicator": document['id'], "country": country, "year": year, "value": x['value'], }, 200 return { "message": "country: " + country + " is invalid", }, 404 queryParser = api.parser() queryParser.add_argument('query') @api.route('/indicators/<string:id>/<int:year>') @api.expect(queryParser) class IndicatorYearCountrySort(Resource): def get(self, id, year): args = queryParser.parse_args() query = args.get('query') print("GET_ 1", id, year, query) # check if id is valid indicatorCollection = db['indicatorCollection']
todo = api.model('Todo', { 'task': fields.String(required=True, description='The task details') }) listed_todo = api.model('ListedTodo', { 'id': fields.String(required=True, description='The todo ID'), 'todo': fields.Nested(todo, description='The Todo') }) def abort_if_todo_doesnt_exist(todo_id): if todo_id not in TODOS: api.abort(404, "Todo {} doesn't exist".format(todo_id)) parser = api.parser() parser.add_argument('task', type=str, required=True, help='The task details', location='form') @ns.route('/<string:todo_id>') @api.doc(responses={404: 'Todo not found'}, params={'todo_id': 'The Todo ID'}) class Todo(Resource): '''Show a single todo item and lets you delete them''' @api.doc(description='todo_id should be in {0}'.format(', '.join(TODOS.keys()))) @api.marshal_with(todo) def get(self, todo_id): '''Fetch a given resource''' abort_if_todo_doesnt_exist(todo_id) return TODOS[todo_id] @api.doc(responses={204: 'Todo deleted'})
authorizations = { 'apikey': { 'type': 'apiKey', 'in': 'header', 'name': 'X-API-KEY' } } app = Flask(__name__) CORS(app) api = Api(app, authorizations=authorizations, title='Connect 4 API') app.config['SECRET_KEY'] = 'secretKey' moves_parser = api.parser() moves_parser.add_argument('col', type=int, help='Columns number of the move (0-6)', location='form') # Checking Tokens def token_required(f): @wraps(f) def decorated(*args, **kwargs): crud = CRUD_Resources() token = None if 'X-API-KEY' in request.headers: token = request.headers['X-API-KEY'] if not token:
@service.route('/') def index(): return render_template("index.html") api = Api( service, title='INSEE/IRIS Geolocalizer', ui=False, version='0.1', description= "Retrieve some data related to the IRIS codes. Look for an IRIS from an address." ) iris_code_parser = api.parser() iris_code_parser.add_argument("limit", required=False, default=10, dest='limit', location='args', help='Limit') coord_parser = api.parser() coord_parser.add_argument("lat", required=True, dest='lat', location='args', help='Latitude') coord_parser.add_argument("lng", required=True,
def register_graphql(namespace: Namespace, api: Api): """Method used to register the GraphQL namespace and endpoint.""" # Create expected headers and payload headers = api.parser() headers.add_argument( 'Authorization', type=str, help= 'Token can be generated from mutation <b>authenticateUser</b>. Then it must be passed with the format: <b>Bearer <i>token</i></b>', location='headers') payload = api.model( 'Payload', { 'query': fields.String(required=True, description='GraphQL query or mutation', example='{allIndicatorTypes{nodes{id,name}}}') }) @namespace.route('/graphql', endpoint='with-parser') @namespace.doc() class GraphQL(Resource): @namespace.expect(headers, payload, validate=True) def post(self): """ Execute GraphQL queries and mutations Use this endpoint to send http request to the GraphQL API. """ payload = request.json try: # Validate http request payload and convert it to GraphQL document graphql_document = validate_graphql_request(payload['query']) # Verify GraphQL mutation can be handled interceptor = Interceptor() mutation_name = interceptor.get_mutation_name(graphql_document) # Surcharge payload before request for some specific mutations if mutation_name: payload['query'] = interceptor.before_request( mutation_name) # Execute request on GraphQL API authorization = headers.parse_args().Authorization status, data = execute_graphql_request(authorization, payload) if status != 200: raise RequestException(status, data) # Execute custom scripts after request for some specific mutations if mutation_name: data = interceptor.after_request(mutation_name, authorization, data) # Return result return make_response(jsonify(data)) except RequestException as exception: return exception.to_response() except APIError as exception: return make_response( jsonify({'message': exception.explanation}), exception.status_code)
city=data['city'], iris_type=data['type']) api = Api( service, title='INSEE/IRIS Geolocalizer', ui=False, prefix='/api', version='0.1', description= "Retrieve some data related to the IRIS codes. Look for an IRIS from an address." ) api.add_namespace(insee_api) geojson_parser = api.parser() geojson_parser.add_argument("geojson", type=inputs.boolean, default=False, location='args', help='GeoJSON') iris_code_parser = geojson_parser.copy() iris_code_parser.add_argument("limit", required=False, default=10, dest='limit', location='args', help='Limit') address_parser = geojson_parser.copy()
app = Flask(__name__) api = Api( app, version='1.0', title='Summary API', description= 'A simple review summarization API which uses Python\'s sumy library') CORS(app) app.config.SWAGGER_UI_DOC_EXPANSION = 'list' ns = api.namespace('sum/v1.0', 'Text Summary v1.0 ') parser = api.parser() parser.add_argument('reviews', required=True, location='json', help='Input Format : ' '<br>{' '<br> "reviews":[{' '<br> "reviewer_id":"string",' '<br> "reviewee_id":"string",' '<br> "score":"string",' '<br> "feedback":"string"' '<br> }]' '<br>}') parser_sum = api.parser() parser_sum.add_argument('sentences',
class OxfsAgent: def __init__(self, host, port): self.host = host self.port = port self.files = [] self.directories = [] self.lock = threading.Lock() def append(self, path, ptye): self.lock.acquire() if 'd' == ptye: self.directories.append(path) else: self.files.append(path) self.lock.release() def steal(self): self.lock.acquire() message = self.dumps() self.directories = [] self.files = [] self.lock.release() return message def dumps(self): return json.dumps({ 'files': self.files, 'directories': self.directories }) def run(self): apiserver = self self.app = Flask(__name__) self.app.wsgi_app = ProxyFix(self.app.wsgi_app) self.api = Api(self.app, version='0.1', title='Oxfs Agent Api', description='The Oxfs Agent Api') fs_namespace = self.api.namespace('fs', description='fs operations') status_model = self.api.model('Status', { 'status': fields.Boolean, 'data': fields.String }) put_args = self.api.parser() put_args.add_argument('path', required=True, help='full path') put_args.add_argument('type', required=True, help='path type') @fs_namespace.route('/path/put') @fs_namespace.expect(put_args) class PutPath(Resource): @fs_namespace.marshal_with(status_model, envelope='data') def put(self): args = put_args.parse_args() apiserver.append(args['path'], args['type']) return {'status': True, 'data': 'success'} fetch_args = self.api.parser() fetch_args.add_argument('clear', required=True, help='clear after fetch') @fs_namespace.route('/path/fetch') @fs_namespace.expect(fetch_args) class GetPath(Resource): @fs_namespace.marshal_with(status_model, envelope='data') def get(self): args = fetch_args.parse_args() if 'yes' == args['clear']: message = apiserver.steal() else: message = apiserver.dumps() return {'status': True, 'data': message} self.app.run(host=self.host, port=self.port)
photo_info = api.model('New_photo', { 'tags': fields.String, 'desc': fields.String, 'geotag_lat': fields.Float, 'geotag_lng': fields.Float, 'taken_date': fields.DateTime('%Y:%m:%d %H:%M:%S'), 'make': fields.String, 'model': fields.String, 'width': fields.String, 'height': fields.String, 'city': fields.String, 'nation': fields.String, 'address': fields.String }) photo_get_parser = api.parser() photo_get_parser.add_argument('mode', type=str, location='args') file_upload_parser = api.parser() file_upload_parser.add_argument('file', location='files', type=FileStorage, required=True) file_upload_parser.add_argument('tags', type=str, location='form') file_upload_parser.add_argument('desc', type=str, location='form') file_upload_parser.add_argument('make', type=str, location='form') file_upload_parser.add_argument('model', type=str, location='form') file_upload_parser.add_argument('width', type=str, location='form') file_upload_parser.add_argument('height', type=str, location='form') file_upload_parser.add_argument('taken_date', type=str, location='form') file_upload_parser.add_argument('geotag_lat', type=str, location='form') file_upload_parser.add_argument('geotag_lng', type=str, location='form') file_upload_parser.add_argument('city', type=str, location='form') file_upload_parser.add_argument('address', type=str, location='form')
title='Data Quality Framework API', version='v1', description= '''API used to configure and trigger the execution of data quality indicators.''', doc='/doc', contact='to be configured') # Api.specs_url = swagger_url # To be activated after we implement https app.register_blueprint(blueprint) # Declare resources name spaces api.namespaces.clear() graphql = api.namespace('GraphQL', path='/v1') health = api.namespace('Health', path='/v1') # Create expected headers and payload headers = api.parser() payload = api.model( "Payload", { "query": fields.String(required=True, description='GraphQL query or mutation', example='{allIndicatorTypes{nodes{id,name}}}') }) # Document default responses responses = { 200: 'Success: The request has succeeded.', 400: 'Bad Request: The request could not be understood by the server or is not compliant with validation rules.', 403: 'Forbidden: You do not have sufficient permissions to access this resource.',
path='/') getPlusPPData = api.namespace('getPlusPPData', description='获取玩家pp+数据。可指定手动进行刷新操作(osu!api)', path='/') getPlayerDataV1 = api.namespace('getPlayerDataV1', description='获取玩家osu!信息。自动进行刷新操作(osu!api)', path='/') getPlayerOsuid = api.namespace('getPlayerOsuid', description='获取osuid(不稳定,非osu!api)', path='/') # pasers parser_token = api.parser().add_argument('X-OtsuToken', location='headers', type=str) parser_osuid = api.parser().add_argument('osuid', location='headers', type=str) parser_username = api.parser().add_argument('username', type=str, required=True, help='玩家用户名') parser_playerKey = api.parser().add_argument('playerKey', required=True, help='玩家名或者玩家id') parser_action = api.parser().add_argument( 'action', required=False, help='一个可选的操作参数,如noHistory:不返回历史数据;simple:简单数据') parser_keyType = api.parser().add_argument( 'keyType', required=False, help='一个可选的参数,指定playKey是为osuid(填id)还是username(填string)')
updated_reports = api.model('UpdatedReport', { "url": fields.Url, "reports": fields.List(fields.Nested(reports)) }) articles = api.model( 'Article', { "url": fields.Url, "date_of_publication": fields.String, "headline": fields.String, "main_text": fields.String, "reports": fields.List(fields.Nested(reports)) }) parser1 = api.parser() parser1.add_argument( 'start_date', help= 'Start date for the articles. Use format YYYY-MM-DDTHH:MM:SS. Eg:2018-01-01T00:00:00', location='args', required=True) parser1.add_argument( 'end_date', help= 'End date for the articles. Use format YYYY-MM-DDTHH:MM:SS Eg:2019-12-31T11:59:59', location='args', required=True) parser1.add_argument('timezone', type=str, choices=('GMT', 'CET'),
from werkzeug.datastructures import FileStorage from classifier import api_controller import cv2 application = Flask(__name__) api = Api(application, version='1.0', title='Facial Recognition API', description=''' Send an image to an endpoint and it will return the same image with rectangles around the faces detected in the image. ''') namespace = api.namespace('/', description='Methods') single_parser = api.parser() single_parser.add_argument('file', location='files', type=FileStorage, required=True) @namespace.route('/recognize-faces') class FacialRecognizer(Resource): """Uses the image provided in POST route to feed into open-cv and detect faces""" @api.doc(parser=single_parser, description='Upload an image with people\'s faces.') def post(self): args = single_parser.parse_args() file_path = api_controller(args)
def test_api_shortcut(self, app): api = Api(app) parser = api.parser() assert isinstance(parser, RequestParser)