Exemple #1
0
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
Exemple #2
0
        fields.String(required=False,
                      description='Metadata: developer dilution'),
        'metadata_develop_time':
        fields.String(required=False,
                      description='Metadata: development time'),
        'metadata_lab':
        fields.String(required=False, description='Metadata: processing lab'),
        'metadata_lab_address':
        fields.String(required=False,
                      description='Metadata: processing lab address'),
        'metadata_filter':
        fields.String(required=False, description='Metadata: filter name'),
    })

# Parsers
new_session_parser = api.parser()
new_session_parser.add_argument('initial_frame',
                                type=str,
                                location='json',
                                help='Frame name of the first photo')
new_session_parser.add_argument(
    'max_number_of_files',
    type=int,
    default=1,
    location='json',
    help='Maximum number of files to download per photo')
new_session_parser.add_argument(
    'delete_photo_after_download',
    type=bool,
    default=False,
    location='json',
Exemple #3
0
class OxfsApi(object):
    def __init__(self, oxfs_fuse):
        self.oxfs_fuse = oxfs_fuse

    def cleanf(self, path):
        '''clear the file attributes cache, file cache.'''
        self.oxfs_fuse.attributes.remove(path)
        cachefile = self.oxfs_fuse.cachefile(path)
        if os.path.exists(cachefile):
            os.unlink(cachefile)
        return True

    def cleand(self, path):
        '''clear the directories cache, 1st level file cache.'''
        entries = self.oxfs_fuse.directories.fetch(path)
        if entries:
            self.oxfs_fuse.directories.remove(path)
            for name in entries:
                self.cleanf(os.path.join(path, name))
        return True

    def clear(self):
        '''clear all attributes, directories cache.'''
        self.oxfs_fuse.attributes.cache.clear()
        self.oxfs_fuse.directories.cache.clear()
        shutil.rmtree(self.oxfs_fuse.cache_path)
        os.makedirs(self.oxfs_fuse.cache_path)
        return True

    def fetchd(self, path):
        return True, json.dumps(self.oxfs_fuse.directories.fetch(path))

    def run(self, port):
        self.thread = threading.Thread(target=self.start_service,
                                       args=(port, ))
        self.thread.daemon = True
        self.thread.name = 'apiserver'
        self.thread.start()

    def set_flask_env(self):
        name = 'FLASK_ENV'
        if name not in os.environ:
            os.environ[name] = 'development'

    def start_service(self, port):
        apiserver = self
        self.app = Flask(__name__)
        self.app.wsgi_app = ProxyFix(self.app.wsgi_app)
        self.api = Api(self.app,
                       version='1.0',
                       title='Oxfs Api',
                       description='The Oxfs Api')

        # Response model
        fs_namespace = self.api.namespace('fs', description='fs operations')
        status_model = self.api.model('Status', {
            'status': fields.Boolean,
            'data': fields.String
        })

        # Request arguments
        string_args = self.api.parser()
        string_args.add_argument('path', required=True, help='absolute path')

        # Api
        @fs_namespace.route('/reload')
        @fs_namespace.expect(string_args)
        class Reload(Resource):
            @fs_namespace.marshal_with(status_model, envelope='data')
            def post(self):
                args = string_args.parse_args()
                path = apiserver.oxfs_fuse.remotepath(args['path'])
                status = (apiserver.cleanf(path), apiserver.cleand(path))
                return {'status': False not in status, 'data': path}

        @fs_namespace.route('/clear')
        class Clear(Resource):
            @fs_namespace.marshal_with(status_model, envelope='data')
            def delete(self):
                status = apiserver.clear()
                return {'status': True, 'data': 'success'}

        @fs_namespace.route('/directories')
        @fs_namespace.expect(string_args)
        class Directories(Resource):
            @fs_namespace.marshal_with(status_model, envelope='data')
            def get(self):
                args = string_args.parse_args()
                path = apiserver.oxfs_fuse.remotepath(args['path'])
                status, data = apiserver.fetchd(path)
                return {'status': status, 'data': data}

        self.set_flask_env()
        self.app.run(port=port, debug=False)
import CSVHandler as csvh
import FuncUtils as fu
import QueryHandler as qh

import os
import argparse
import json

################# FLASK SERVER #################
app = Flask(__name__, root_path=Const.ROOT_PATH + Const.FLASK_ROOT_PATH)
#app = Flask(__name__, template_folder="web/templates", static_folder="web/static") #ONLY FOR LOCAL USE
api = Api(app)

ns = api.namespace('', description='APIs to communicate with server')

csv_parser = api.parser()
csv_parser.add_argument(Const.FILE, type=file, location=Const.FILE)

query_parser = api.parser()
query_parser.add_argument(Const.ID, type=str)
query_parser.add_argument(Const.FILE, type=str)
query_parser.add_argument(Const.EPSILON, type=float)
query_parser.add_argument(Const.QUERY, type=str)


@app.route('/' + Const.INDEX, methods=['GET'])
def index():
    return render_template(Const.INDEX + '.html')


@ns.route('/' + Const.SEND_CSV)
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):
app.register_blueprint(blueprint)
app.config.SWAGGER_UI_DOC_EXPANSION = 'full'

app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024 * 300 #Around 300 MBs max size
app.config['UPLOAD_EXTENSIONS'] = ['.mp3', '.wav']

rabbitmq_host = os.environ.get("RABBITMQ_HOST")
rabbitmq_user = os.environ.get("RABBITMQ_USER")
rabbitmq_password = os.environ.get("RABBITMQ_PASSWORD")

CONFIG = { 'AMQP_URI': f"amqp://{rabbitmq_user}:{rabbitmq_password}@{rabbitmq_host}",
    'serializer': 'pickle'
  }

upload_parser = api.parser()
upload_parser.add_argument('file', location='files', type=FileStorage, required=True)

requestResult = api.model('RequestResult', {
    'uuid' : fields.FormattedString(uuid.uuid4(),description='An uuid or token that is required to retrieve file after processing'
    ,example=str(uuid.uuid4())),
    'model' : fields.String(description='Selected model: demucs, tasnet, etc',example='Demucs'),
    'status' : fields.String(description='A status of the current request',example="Queued")
})

errorResponse = api.model('ErrorResponse',{ 'message' : fields.String(description='Message describing error') } )

@api.route('/upload', methods=['POST'])
@api.expect(upload_parser)
class Upload(Resource):
  '''Upload a file and receive a token or uuid for further file retrieving after processing'''
Exemple #7
0
        "language": fields.String,
        "genres": fields.List(fields.String(example="genre")),
        "status": fields.String,
        "runtime": fields.Integer,
        "premiered": fields.String,
        "officialSite": fields.String,
        "schedule": fields.String,
        "rating": fields.Nested(rating),
        "weight": fields.Integer,
        "network": fields.String,
        "summary": fields.String,
        '_links': fields.Nested(links)
    })

#app.UseDeveloperExceptionPage();
parser = api.parser()
parser.add_argument(
    'name',
    type=str)  #, help='name of show to search and add', location='args')


@api.response(200, 'OK')
@api.response(400, 'Bad Request')
@api.response(404, 'Not Found')
@api.response(201, 'Created')
@api.param('name', 'tv-show name')
@api.route('/tvshows/import')
class TV1(Resource):
    @api.doc(description="Import a TV-show by its name and store it")
    # import a tv show from tvmaze and either insert into database or update if already exists
    def post(self):
Exemple #8
0
})


# gibt connection-objekt zurück, schaltet foreign keys an und schaut, ob DB existiert
def get_connection(filename):
    if not os.path.exists(filename):
        raise FileNotFoundError('Database not found')

    connection = sqlite3.connect(filename)
    cursor = connection.cursor()
    # foreign keys
    cursor.execute("PRAGMA FOREIGN_KEYS=ON")
    return connection


auth_parser = api.parser()
auth_parser.add_argument('token', type=str, location='headers', required=True)


# gibt True zurück, wenn der im Header mit gesendete Token der eines Admins ist, sonst false
# um diese funktion in einer request zu nutzen, muss diese vorher mit dem decorator
# @api.expect(auth_parser)
# versehen werden
def is_admin(cursor):
    try:
        token = auth_parser.parse_args()['token']

        is_admin_db = cursor.execute(
            'SELECT Ist_Admin FROM Pilot WHERE Token LIKE ?', [token]
        ).fetchone()[0]
Exemple #9
0
logging.StreamHandler(sys.stderr)

# 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)

# List of parameters to be used to filter data:
filterParams = api.parser()
filterParams.add_argument('pmid',
                          type=int,
                          required=False,
                          help='Pubmed ID of a requested publication.')
filterParams.add_argument('trait',
                          type=str,
                          required=False,
                          help='Trait of ontology term.')
filterParams.add_argument('pvalue',
                          type=str,
                          required=False,
                          help='Upper boundary of the p-value (eg. 1e-8).')
filterParams.add_argument('sample',
                          type=str,
                          required=False,
Exemple #10
0
# db = firestore.client()
# interactions = db.collection('interactions')

cred = credentials.Certificate('important.json')
default_app = initialize_app(cred)
db = firestore.client()
firebase_api = db.collection('api')

application = Flask(__name__)
api = Api(application,
          version='1.0',
          title='MNIST Classification',
          description='CNN for Mnist')
ns = api.namespace('Make_School', description='Methods')

single_parser = api.parser()
single_parser.add_argument('file',
                           location='files',
                           type=FileStorage,
                           required=True)

model = load_model('my_model.h5')
graph = tf.get_default_graph()

# Model reconstruction from JSON file
with open('model_architecture.json', 'r') as f:
    model = model_from_json(f.read())

# Load weights into the new model
model.load_weights('model_weights.h5')
Exemple #11
0
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,
                                 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",
Exemple #12
0
import json, github, io, flask_wtf, flask_wtf.file, wtforms, flask_cors
from flask import Flask, Blueprint, send_file, render_template, flash, Markup
from flask_restx import Api, Resource
from keyboard import Keyboard


app = Flask(__name__)
app.config.from_object('config')
flask_cors.CORS(app)
github_api = github.Github(app.config['API_TOKEN'])  
blueprint = Blueprint('api', __name__, url_prefix='/api')
api = Api(
    blueprint, version='1.0', title='KLE-Render API',
    description='Prettier images of Keyboard Layout Editor designs. URLs relative to this page'
)
kle_parser = api.parser()
kle_parser.add_argument(
    'data', required=True, location='json',
    help='Downloaded strict JSON from Raw Data tab of Keyboard Layout Editor'
)
app.register_blueprint(blueprint)


def serve_pil_image(pil_img):
    img_io = io.BytesIO()
    pil_img.save(img_io, 'PNG', compress_level=3)
    img_io.seek(0)
    return send_file(img_io, mimetype='image/png')


@api.route('/<id>')
blueprint = Blueprint('api', __name__)
api = Api(app=blueprint,
          title="DXC RUN 4U API",
          doc="/documentation",
          version=API_VERSION)

ns_auth = api.namespace('Auth', path='/auth', description='Security endpoints')
ns_teams = api.namespace('Teams',
                         path='/teams',
                         description='Team management endpoints')
ns_users = api.namespace('Users',
                         path='/users',
                         description='User management endpoints')
team_id_in_route = '<team_id>'

auth_header_jwt_parser = api.parser()
auth_header_jwt_parser.add_argument(
    'Authorization',
    location='headers',
    required=True,
    help='JWT auth token, format: JWT <access_token>',
    default='JWT <access_token>')

auth_header_jwt_refresh_parser = api.parser()
auth_header_jwt_refresh_parser.add_argument(
    'Authorization',
    location='headers',
    required=True,
    help='JWT refresh token, format: JWT <refresh_token>',
    default='JWT <refresh_token>')
Exemple #14
0
 def test_api_shortcut(self, app):
     api = Api(app)
     parser = api.parser()
     assert isinstance(parser, RequestParser)
Exemple #15
0
app.config["RESTPLUS_MASK_SWAGGER"] = False
app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 0

blueprint = Blueprint("datapoint-extraction-api", __name__, url_prefix="/api")

api = Api(
    blueprint,
    version="1.0",
    title="Extract API",
    description="Extract API",
    doc="/docs",
)

app.register_blueprint(blueprint, url_prefix="/api")

document_parser = api.parser()
document_parser.add_argument("document_type", location="form", required=True)
document_parser.add_argument("title", location="form", required=True)
document_parser.add_argument("file",
                             location="files",
                             type=FileStorage,
                             required=True,
                             help="The Document file is required")


@api.route("/upload/")
class Upload(Resource):
    @api.doc("Create a document")
    @api.expect(document_parser, validate=True)
    def post(self):
        args = document_parser.parse_args()
Exemple #16
0
from flask import Flask, request, send_file, render_template
from flask_restx import Api, Resource, reqparse
import os
from os import path
from werkzeug.utils import secure_filename
from flask_cors import CORS
import tempfile
import pyAesCrypt
import Auth

app = Flask(__name__)
CORS(app)
api = Api(app=app, version='1.0', title='Resources Doc API', validate=True)
token_argument = reqparse.RequestParser()
token_argument.add_argument('token', type=str, required=True)
data_argument = api.parser()
data_argument.add_argument('token', type=str, required=True)
data_argument.add_argument('Data', type=files, required=True)
if not path.exists("./Resources"):
    os.mkdir("./Resources")
bufferSize = 64 * 1024
password = secret = os.getenv('DOC_PASS')


@api.route("/rsc/<string:user_id>")
class ResourcesList(Resource):

    @api.response(200, 'Resources access : Success')
    @api.response(400, 'Resources access : Token validation error')
    @api.expect(token_argument)
    def get(self, user_id):