예제 #1
0
파일: sr_unit.py 프로젝트: pawanon61/sirepo
def _req(route_name, params, op, raw_response):
    """Make request and parse result

    Args:
        route_name (str): string name of route
        params (dict): parameters to apply to route
        op (func): how to request

    Returns:
        object: parsed JSON result
    """
    from sirepo import simulation_db

    uri = None
    resp = None
    try:
        uri = _uri(route_name, params)
        resp = op(uri)
        if raw_response:
            return resp
        return simulation_db.json_load(resp.data)
    except Exception as e:
        pkdlog('{}: uri={} resp={}', e, uri, resp)
        pkdexc()
        raise
예제 #2
0
def parse_json(assert_sim_type=True):
    from sirepo import simulation_db

    #POSIT: uri_router.call_api
    if hasattr(flask.g,
               'sirepo_call_api_data') and flask.g.sirepo_call_api_data:
        return flask.g.sirepo_call_api_data
    req = flask.request
    if req.mimetype != 'application/json':
        util.raise_bad_request(
            'content-type is not application/json: mimetype={}',
            req.mimetype,
        )
    # Adapted from flask.wrappers.Request.get_json
    # We accept a request charset against the specification as
    # certain clients have been using this in the past.  This
    # fits our general approach of being nice in what we accept
    # and strict in what we send out.
    charset = req.mimetype_params.get('charset')
    data = req.get_data(cache=False)
    res = simulation_db.json_load(data, encoding=charset)
    if assert_sim_type and 'simulationType' in res:
        res.simulationType = sirepo.template.assert_sim_type(
            res.simulationType)
    return res
예제 #3
0
def _run_tests():
    """Runs the SRW "Undulator Radiation" simulation's initialIntensityReport"""
    _validate_auth_state()
    simulation_type = _SIM_TYPE
    res = uri_router.call_api(
        'findByNameWithAuth',
        dict(
            simulation_type=simulation_type,
            application_mode='default',
            simulation_name=_SIM_NAME,
        ),
    )
    m = re.search(r'\/source\/(\w+)"', pkcompat.from_bytes(res.data))
    if not m:
        raise RuntimeError('failed to find sid in resp={}'.format(res.data))
    i = m.group(1)
    d = simulation_db.read_simulation_json(simulation_type, sid=i)
    try:
        d.models.electronBeam.current = d.models.electronBeam.current + (
            random.random() / 10)
    except AttributeError:
        assert _SIM_TYPE == 'myapp', \
            f'{_SIM_TYPE} should be myapp or have models.electronBeam.current'
        pass
    d.simulationId = i
    d.report = _SIM_REPORT
    r = None
    try:
        resp = uri_router.call_api('runSimulation', data=d)
        for _ in range(_MAX_CALLS):
            r = simulation_db.json_load(resp.data)
            pkdlog('resp={}', r)
            if r.state == 'error':
                raise RuntimeError('simulation error: resp={}'.format(r))
            if r.state == 'completed':
                if 'initialIntensityReport' == d.report:
                    min_size = 50
                    if len(r.z_matrix) < min_size or len(
                            r.z_matrix[0]) < min_size:
                        raise RuntimeError(
                            'received bad report output: resp={}', r)
                return
            d = r.nextRequest
            resp = uri_router.call_api('runStatus', data=d)
            time.sleep(_SLEEP)
        raise RuntimeError(
            'simulation timed out: seconds={} resp='.format(
                _MAX_CALLS * _SLEEP, r), )
    finally:
        try:
            uri_router.call_api('runCancel', data=d)
        except Exception:
            pass
예제 #4
0
파일: server.py 프로젝트: mrakitin/sirepo
def _json_input():
    req = flask.request
    if req.mimetype != 'application/json':
        pkdlog('{}: req.mimetype is not application/json', req.mimetype)
        raise werkzeug.Eexceptions.BadRequest('expecting application/json')
    # Adapted from flask.wrappers.Request.get_json
    # We accept a request charset against the specification as
    # certain clients have been using this in the past.  This
    # fits our general approach of being nice in what we accept
    # and strict in what we send out.
    charset = req.mimetype_params.get('charset')
    data = req.get_data(cache=False)
    return simulation_db.json_load(data, encoding=charset)
예제 #5
0
def _req(route_name, params, op):
    """Make request and parse result

    Args:
        route_name (str): string name of route
        params (dict): parameters to apply to route
        op (func): how to request

    Returns:
        object: parsed JSON result
    """
    resp = op(_route(route_name, params))
    return simulation_db.json_load(resp.data)
예제 #6
0
def _json_input():
    req = flask.request
    if req.mimetype != 'application/json':
        pkdlog('{}: req.mimetype is not application/json', req.mimetype)
        raise werkzeug.Exceptions.BadRequest('expecting application/json')
    # Adapted from flask.wrappers.Request.get_json
    # We accept a request charset against the specification as
    # certain clients have been using this in the past.  This
    # fits our general approach of being nice in what we accept
    # and strict in what we send out.
    charset = req.mimetype_params.get('charset')
    data = req.get_data(cache=False)
    return simulation_db.json_load(data, encoding=charset)
예제 #7
0
def parse_json(assert_sim_type=True):
    req = flask.request
    if req.mimetype != 'application/json':
        util.raise_bad_request(
            'content-type is not application/json: mimetype={}',
            req.mimetype,
        )
    # Adapted from flask.wrappers.Request.get_json
    # We accept a request charset against the specification as
    # certain clients have been using this in the past.  This
    # fits our general approach of being nice in what we accept
    # and strict in what we send out.
    charset = req.mimetype_params.get('charset')
    data = req.get_data(cache=False)
    res = simulation_db.json_load(data, encoding=charset)
    if assert_sim_type and 'simulationType' in res:
        res.simulationType = sirepo.template.assert_sim_type(res.simulationType)
    return res
예제 #8
0
파일: status.py 프로젝트: JiayangY/sirepo
def _run_tests():
    """Runs the SRW "Undulator Radiation" simulation's initialIntensityReport"""
    simulation_type = _SIM_TYPE
    res = uri_router.call_api(
        'findByNameWithAuth',
        dict(
            simulation_type=simulation_type,
            application_mode='default',
            simulation_name=_SIM_NAME,
        ),
    )
    m = re.search(r'\/source\/(\w+)"', res.data)
    if not m:
        raise RuntimeError('failed to find sid in resp={}'.format(res.data))
    i = m.group(1)
    d = simulation_db.read_simulation_json(simulation_type, sid=i)
    d.simulationId = i
    d.report = _SIM_REPORT
    r = None
    try:
        uri_router.call_api('runSimulation', data=d)
        for _ in range(_MAX_CALLS):
            time.sleep(_SLEEP)
            resp = uri_router.call_api('runStatus', data=d)
            r = simulation_db.json_load(resp.data)
            if r.state == 'error':
                raise RuntimeError('simulation error: resp={}'.format(r))
            if r.state == 'completed':
                if 'initialIntensityReport' == d.report:
                    min_size = 50
                    if len(r.z_matrix) < min_size or len(
                            r.z_matrix[0]) < min_size:
                        raise RuntimeError(
                            'received bad report output: resp={}', r)
                return
            d = r.nextRequest
        raise RuntimeError(
            'simulation timed out: seconds={} resp='.format(
                _MAX_CALLS * _SLEEP, r), )
    finally:
        try:
            uri_router.call_api('runCancel', data=d)
        except Exception:
            pass
예제 #9
0
def read_json(text, template=None):
    """Read json file and return

    Args:
        text (IO): file to be read
        template (module): expected type

    Returns:
        dict: data
    """
    from sirepo import simulation_db

    # attempt to decode the input as json first, if invalid try python
    data = simulation_db.json_load(text)
    if template:
        assert data.simulationType == template.SIM_TYPE, \
            'simulationType {} invalid, expecting {}'.format(
                data.simulationType,
                template.SIM_TYPE,
            )
    return data
예제 #10
0
파일: importer.py 프로젝트: JiayangY/sirepo
def read_json(text, sim_type=None):
    """Read json file and return

    Args:
        text (IO): file to be read
        sim_type (str): expected type

    Returns:
        dict: data
    """
    from sirepo import simulation_db

    # attempt to decode the input as json first, if invalid try python
    # fixup data in case new structures are need for lib_file ops below
    data = simulation_db.fixup_old_data(simulation_db.json_load(text))[0]
    assert not sim_type or data.simulationType == sim_type, \
        'simulationType={} invalid, expecting={}'.format(
            data.simulationType,
            sim_type,
        )
    return sirepo.http_request.parse_post(req_data=data).req_data
예제 #11
0
파일: importer.py 프로젝트: e-carlin/sirepo
def read_json(text, template=None):
    """Read json file and return

    Args:
        text (IO): file to be read
        template (module): expected type

    Returns:
        dict: data
    """
    from sirepo import simulation_db

    # attempt to decode the input as json first, if invalid try python
    # fixup data in case new structures are need for lib_files() below
    data = simulation_db.fixup_old_data(simulation_db.json_load(text))[0]
    if template:
        assert data.simulationType == template.SIM_TYPE, \
            'simulationType {} invalid, expecting {}'.format(
                data.simulationType,
                template.SIM_TYPE,
            )
    return data
예제 #12
0
파일: importer.py 프로젝트: yeeon/sirepo
def read_json(text, template=None):
    """Read json file and return

    Args:
        text (IO): file to be read
        template (module): expected type

    Returns:
        dict: data
    """
    from sirepo import simulation_db

    # attempt to decode the input as json first, if invalid try python
    # fixup data in case new structures are need for lib_files() below
    data = simulation_db.fixup_old_data(simulation_db.json_load(text))[0]
    if template:
        assert data.simulationType == template.SIM_TYPE, \
            'simulationType {} invalid, expecting {}'.format(
                data.simulationType,
                template.SIM_TYPE,
            )
    return data
예제 #13
0
파일: srunit.py 프로젝트: e-carlin/sirepo
def _req(route_name, params, op, raw_response):
    """Make request and parse result

    Args:
        route_name (str): string name of route
        params (dict): parameters to apply to route
        op (func): how to request

    Returns:
        object: parsed JSON result
    """
    from sirepo import simulation_db

    uri = None
    resp = None
    try:
        uri = _uri(route_name, params)
        resp = op(uri)
        if raw_response:
            return resp
        return simulation_db.json_load(resp.data)
    except Exception as e:
        pkdlog('{}: uri={} resp={}', e, uri, resp)
        raise