Пример #1
0
def dispatch_funcs_to_web_app(funcs,
                              input_trans=None,
                              output_trans=None,
                              name='py2api',
                              debug=0):
    if not isinstance(funcs, (list, tuple)) or callable(funcs):
        funcs = [funcs]
    if input_trans is None:
        input_trans = InputTrans()
    elif isinstance(input_trans, dict):
        input_trans = InputTrans(input_trans)
    if output_trans is None:
        output_trans = OutputTrans(jsonify)

    s = Struct(**{func.__name__: func for func in funcs})

    wrap = WebObjWrapper(
        obj_constructor=s,  # wrap this current module
        obj_constructor_arg_names=[],  # no construction, so no construction args
        permissible_attr=[func.__name__ for func in funcs],
        input_trans=input_trans,
        output_trans=output_trans,
        name='/',
        debug=debug)

    return mk_app(app_name=name, routes=[wrap])
Пример #2
0
Run the web service and try things like:
    http://0.0.0.0:5000/os?attr=path.isdir&s=/
    http://0.0.0.0:5000/os?attr=path.isfile&path=not_existing_file.txt
etc.

"""

import os

from flask import jsonify
from py2api.py2rest.obj_wrap import WebObjWrapper
from py2api.py2rest.input_trans import InputTrans
from py2api.output_trans import OutputTrans
from py2api.py2rest.app_maker import mk_app, dflt_run_app_kwargs

os_path_wrap = WebObjWrapper(
    obj_constructor=
    os,  # if not a callable, the wrapper wraps always the same object
    obj_constructor_arg_names=[],  # no construction, so no construction args
    permissible_attr='path\..*',  # allows all attributes below path.
    input_trans=InputTrans.from_argname_trans_dict({}),  # standard input_trans
    output_trans=OutputTrans(trans_spec=lambda x: jsonify({'_result': x})),
    name='/os',
    debug=0)

app = mk_app(app_name='example', routes=[os_path_wrap])

if __name__ == "__main__":
    app.run(**dflt_run_app_kwargs())
Пример #3
0
        return wrapped_func


    def wf_from_timed_chunk(chunk):
        return [x[1] for x in chunk]


    get_data_chunk_bytes = wrap_output(wfsr_to_wav_bytes)(
        wrap_output(wf_from_timed_chunk)(get_data_chunk))

    input_trans = InputTrans(
        trans_spec={
            _ARGNAME: {  # these argument can all be floats (don't have to be handled differently)
                'n': int,
                'freq': int,
                'sr': int,
                'amplitude': float,
                'phase_in_radians': float,
                'df': pd.DataFrame
            }
        })

    output_trans = OutputTrans(
        trans_spec={
            _ATTR: {
                'test_func': lambda x: jsonify({'_result': x.to_dict()})
            },
            _ELSE: lambda x: jsonify({'_result': x})}
    )

    wrap = WebObjWrapper(obj_constructor=sys.modules[__name__],  # wrap this current module
Пример #4
0
    if op_func is not None:
        return op_func
    else:
        raise ValueError("No such operation: {}".format(op))


input_trans = InputTrans(
    trans_spec={
        _ATTR: {  # the op argument is going to be handled differently according to the calculator type (float or int)
            'fcalc.compute': {
                _ARGNAME: {
                    'op': get_float_operator_func
                }
            },
            'icalc.compute': {
                _ARGNAME: {
                    'op': get_int_operator_func
                }
            },
        },
        _ARGNAME: {  # these argument can all be floats (don't have to be handled differently)
            'x': float,
            'y': float
        }
    })

output_trans = OutputTrans(lambda x: jsonify({'_result': x}))

# wrapper ##############################################################################################################
obj_wrapper = WebObjWrapper(obj_constructor=Controller,
                           obj_constructor_arg_names=['user', 'dflt_greeting'],
Пример #5
0
    from py2api.py2rest.obj_wrap import WebObjWrapper
    from py2api.py2rest.input_trans import InputTrans, _ARGNAME, _ELSE, _ARGS, _JSON, _SOURCE
    from py2api.output_trans import OutputTrans, _ATTR, _VALTYPE
    from py2api.py2rest.app_maker import mk_app, dflt_run_app_kwargs, dispatch_funcs_to_web_app

    import numpy as np
    import pandas as pd

    input_trans = InputTrans({
        _ARGNAME:
        {  # check the name of the argument to decide on how to convert it
            'arr':
            {  # the way we'll convert arr depends on whether it comes from the url (args) or json.
                _SOURCE:
                {  # the conversion function will be chosen according to where arr was (url-args or json)
                    _ARGS: lambda x: np.array(list(map(float, x.split(
                        ',')))),  # convert csv string to numerical array
                    _JSON: lambda x: np.array(x)  # convert to numpy array
                }
            },
            'x':
            int  # convert to int  (this will work regardless of source, since int(10) == int('10') == 10)
        }
    })

    # the output of pong is all over the place: Sometimes a string, sometimes a dict, sometimes a DataFrame.
    # So we need to condition how we convert outputs...

    # Now, we could define a function and pass it on to OutputTrans (see comment at the end of this module).
    # But know that OutputTrans json language accommodate's for type based choices:
    output_trans = OutputTrans({
        _ATTR: {
Пример #6
0
                self.snips = self.snips.tolist()
        return to_jdict(self.get_attr_jdict(self.on_fit_return_attr))


# permissions ##########################################################################################################
slang_inclusion_list = [
    'fit',
]

attr_permissions = {'include': slang_inclusion_list, 'exclude': []}

input_trans = InputTrans(
    trans_spec={
        _ARGNAME: {
            'sr': int,
            'tile_size_frm': int,
            'chk_size_frm': int,
            'n_snips': int,
            'wf': array_or_str
        }
    })

output_trans = OutputTrans({_ELSE: lambda x: jsonify(x)})

# wrapper ##############################################################################################################
slang_lite = WebObjWrapper(
    obj_constructor=TaggedWaveformAnalysisForWS,
    obj_constructor_arg_names=['sr', 'tile_size_frm', 'chk_size_frm'],
    permissible_attr=attr_permissions,
    input_trans=input_trans,
    output_trans=output_trans,
    name='/slang_lite/',