コード例 #1
0
ファイル: default.py プロジェクト: ab5y/suqram
def followees(request):
    user = request.user
    if user is None:
        raise HTTPForbidden
    if request.method == 'GET':
        followees = FollowRecordService.by_follower_id(user.id, request)
        return list_to_json(followees, 'followees')
    if request.method == 'POST':
        data = json.loads(json.dumps(request.json))
        if 'followee_id' in data:
            follow = Follow(follower_id=user.id, followee_id=int(data['followee_id']))
            
            with transaction.manager:
                zope.sqlalchemy.register(request.dbsession, transaction_manager=transaction.manager)
                request.dbsession.add(follow)
            
            responseCreated = HTTPCreated()
            responseCreated.body = "followed"
            return responseCreated
    
    if request.method == 'DELETE':
        data = json.loads(json.dumps(request.json))
        if 'followee_id' in data:
            with transaction.manager:
                zope.sqlalchemy.register(request.dbsession, transaction_manager=transaction.manager)
                request.dbsession.query(Follow).filter_by(followee_id=int(data['followee_id'])).filter_by(follower_id=user.id).delete()
                transaction.commit()
            responseDeleted = HTTPOk()
            responseDeleted.body = "unfollowed"
            return responseDeleted
コード例 #2
0
ファイル: views.py プロジェクト: abhinavanurag18/ichnaea
def process_batch(request, data, errors):
    nickname = request.headers.get('X-Nickname', u'')
    upload_items = flatten_items(data)
    errors = process_upload(nickname, upload_items)

    if errors is SENTINEL:
        return HTTPServiceUnavailable()

    if errors:
        get_stats_client().incr('geosubmit.upload.errors', len(errors))

    result = HTTPOk()
    result.content_type = 'application/json'
    result.body = '{}'
    return result
コード例 #3
0
ファイル: views.py プロジェクト: thebent/ichnaea
def geosubmit_view(request, api_key):
    submitter = GeoSubmitter(request, api_key)

    # may raise HTTP error
    request_data = submitter.preprocess()

    try:
        submitter.insert_measures(request_data)
    except ConnectionError:  # pragma: no cover
        return HTTPServiceUnavailable()

    try:
        submitter.submit(request_data)
    except ConnectionError:  # pragma: no cover
        # secondary pipeline is considered non-essential for now
        pass

    result = HTTPOk()
    result.content_type = 'application/json'
    result.body = '{}'
    return result
コード例 #4
0
ファイル: views.py プロジェクト: onelogin/python3-saml
def metadata(request):
    req = prepare_pyramid_request(request)
    auth = init_saml_auth(req)
    settings = auth.get_settings()
    metadata = settings.get_sp_metadata()
    errors = settings.validate_metadata(metadata)

    if len(errors) == 0:
        resp = HTTPOk(body=metadata, headers={'Content-Type': 'text/xml'})
    else:
        resp = HTTPInternalServerError(body=', '.join(errors))
    return resp
コード例 #5
0
ファイル: views.py プロジェクト: tiagokrebs/zapizza-backend
    def confirm(self):
        json_body = self.request.json_body
        if 'token' not in json_body:
            msg = 'Token não informado'
            res = dumps(dict(error=dict(code=409, message=msg)),
                        ensure_ascii=False)
            return HTTPConflict(body=res,
                                content_type='application/json; charset=UTF-8')
        token = json_body['token']
        token_data = confirm_token(request=self.request,
                                   token=token,
                                   audience='registro')
        if token_data:
            aud = token_data['aud']
            email = token_data['email']
            user = User.by_email(email)
            if self.current_user and aud == 'registro' and self.current_user.email == user.email:
                # usuário já registrado direcionado para home
                if self.current_user.register_confirm:
                    msg = 'Usuário já está confirmado'
                    res = dumps(dict(data=dict(code=200, message=msg)),
                                ensure_ascii=False)
                    return HTTPOk(
                        body=res,
                        content_type='application/json; charset=UTF-8')

                # registra usuário e direciona para home
                self.current_user.register_confirm = datetime.utcnow()
                msg = 'Usuário confirmado com sucesso'
                res = dumps(dict(data=dict(code=200, message=msg)),
                            ensure_ascii=False)
                return HTTPOk(body=res,
                              content_type='application/json; charset=UTF-8')

        # retorna token invalido
        msg = 'Token inválido'
        res = dumps(dict(error=dict(code=409, message=msg)),
                    ensure_ascii=False)
        return HTTPConflict(body=res,
                            content_type='application/json; charset=UTF-8')
コード例 #6
0
ファイル: processes.py プロジェクト: 00mjk/weaver
def get_processes(request):
    """
    List registered processes (GetCapabilities). Optionally list both local and provider processes.
    """
    detail = asbool(request.params.get("detail", True))
    try:
        # get local processes and filter according to schema validity
        # (previously deployed process schemas can become invalid because of modified schema definitions
        processes, invalid_processes = get_processes_filtered_by_valid_schemas(
            request)
        if invalid_processes:
            raise HTTPServiceUnavailable(
                "Previously deployed processes are causing invalid schema integrity errors. "
                "Manual cleanup of following processes is required: {}".format(
                    invalid_processes))
        response_body = {
            "processes":
            processes if detail else [get_any_id(p) for p in processes]
        }

        # if 'EMS' and '?providers=True', also fetch each provider's processes
        settings = get_settings(request)
        if get_weaver_configuration(settings) == WEAVER_CONFIGURATION_EMS:
            queries = parse_request_query(request)
            if "providers" in queries and asbool(
                    queries["providers"][0]) is True:
                prov_url = "{host}/providers".format(host=request.host_url)
                providers_response = request_extra("GET",
                                                   prov_url,
                                                   settings=settings,
                                                   headers=request.headers,
                                                   cookies=request.cookies)
                providers = providers_response.json()
                response_body.update({"providers": providers})
                for i, provider in enumerate(providers):
                    provider_id = get_any_id(provider)
                    proc_url = "{host}/providers/{prov}/processes".format(
                        host=request.host_url, prov=provider_id)
                    response = request_extra("GET",
                                             proc_url,
                                             settings=settings,
                                             headers=request.headers,
                                             cookies=request.cookies)
                    processes = response.json().get("processes", [])
                    response_body["providers"][i].update({
                        "processes":
                        processes
                        if detail else [get_any_id(p) for p in processes]
                    })
        return HTTPOk(json=response_body)
    except colander.Invalid as ex:
        raise HTTPBadRequest("Invalid schema: [{!s}]".format(ex))
コード例 #7
0
ファイル: studio.py プロジェクト: tws0002/stalker_pyramid
def update_studio(request):
    """updates the studio
    """

    studio_id = request.params.get('studio_id')
    studio = Studio.query.filter_by(id=studio_id).first()

    name = request.params.get('name', None)
    dwh = request.params.get('dwh', None)
    wh_mon_start = get_time(request, 'mon_start')
    wh_mon_end   = get_time(request, 'mon_end')
    wh_tue_start = get_time(request, 'tue_start')
    wh_tue_end   = get_time(request, 'tue_end')
    wh_wed_start = get_time(request, 'wed_start')
    wh_wed_end   = get_time(request, 'wed_end')
    wh_thu_start = get_time(request, 'thu_start')
    wh_thu_end   = get_time(request, 'thu_end')
    wh_fri_start = get_time(request, 'fri_start')
    wh_fri_end   = get_time(request, 'fri_end')
    wh_sat_start = get_time(request, 'sat_start')
    wh_sat_end   = get_time(request, 'sat_end')
    wh_sun_start = get_time(request, 'sun_start')
    wh_sun_end   = get_time(request, 'sun_end')

    if studio and name and dwh:
        # update new studio

        studio.name=name
        studio.daily_working_hours=int(dwh)

        wh = WorkingHours()

        def set_wh_for_day(day, start, end):
            if start != end:
                wh[day] = [[start.seconds/60, end.seconds/60]]
            else:
                wh[day] = []

        set_wh_for_day('mon', wh_mon_start, wh_mon_end)
        set_wh_for_day('tue', wh_tue_start, wh_tue_end)
        set_wh_for_day('wed', wh_wed_start, wh_wed_end)
        set_wh_for_day('thu', wh_thu_start, wh_thu_end)
        set_wh_for_day('fri', wh_fri_start, wh_fri_end)
        set_wh_for_day('sat', wh_sat_start, wh_sat_end)
        set_wh_for_day('sun', wh_sun_start, wh_sun_end)

        studio.working_hours = wh

        DBSession.add(studio)
        # Commit will be handled by the zope transaction extension

    return HTTPOk()
コード例 #8
0
def process_update_request(request):
    if request.method == 'POST':
        try:
            response = process_gps_updates(request)
            return HTTPOk(body_template=response)
        except GpsUpdateError as e:
            logger.error("Gps update couldn't be processed: " + e.msg)
            if e.code == 403:
                return HTTPForbidden(detail=e.msg)
            return HTTPBadRequest(detail=e.msg)
    msg = "Gps update requested with wrong method."
    logger.warning(msg)
    return HTTPMethodNotAllowed(detail=msg)
コード例 #9
0
ファイル: jobs.py プロジェクト: crim-ca/weaver
def get_job_inputs(request):
    # type: (Request) -> HTTPException
    """
    Retrieve the inputs of a job.
    """
    job = get_job(request)
    inputs = dict(inputs=[
        dict(id=get_any_id(_input), value=get_any_value(_input))
        for _input in job.inputs
    ])
    inputs.update({"links": job.links(request, self_link="inputs")})
    inputs = sd.JobInputsSchema().deserialize(inputs)
    return HTTPOk(json=inputs)
コード例 #10
0
ファイル: deployment_views.py プロジェクト: dockerian/pyapi
    def status(self):
        """
        Get the status of a package deployment
        """
        logger.debug("======= status =======")

        try:
            deployment_id = self.__get_deployment_id_in_request()
            if (not deployment_id):
                return self.index()

            result = get_status(deployment_id)
            logger.debug(result)
            if result['status'] == 200 and result['data']:
                detail = result['data']
                status = '{0}'.format(detail['deploy_status'])
                dest_url = '{0}'.format(detail['destination'])
                contents = json.dumps(result['data'], sort_keys=True)
                response = HTTPOk()
                response.headers = {
                    'Content-Type': 'application/json; charset=UTF-8',
                    'Deployment-Status': status,
                    'Location': dest_url
                }
                response.body = contents
                return response
            elif result['status'] == 404:
                detail = 'No deployment found for {0}'.format(deployment_id)
                return HTTPNotFound(detail=detail)
            else:
                detail = 'Failed to get deployment status for {0}'.format(
                    deployment_id)
                return HTTPInternalServerError(detail=detail)

        except Exception as e:
            tb_info = traceback.format_exc()
            msg = 'Exception on getting deployment status.\n'.format(tb_info)
            logger.exception(msg)
            return HTTPInternalServerError(detail=tb_info)
コード例 #11
0
ファイル: shot.py プロジェクト: tws0002/stalker_pyramid
def create_shot(request):
    """runs when adding a new shot
    """
    logged_in_user = get_logged_in_user(request)

    name = request.params.get('name')
    code = request.params.get('code')

    status_id = request.params.get('status_id')
    status = Status.query.filter_by(id=status_id).first()

    project_id = request.params.get('project_id')
    project = Project.query.filter_by(id=project_id).first()
    logger.debug('project_id   : %s' % project_id)

    if name and code and status and project:
        # get descriptions
        description = request.params.get('description')

        sequence_id = request.params['sequence_id']
        sequence = Sequence.query.filter_by(id=sequence_id).first()

        # get the status_list
        status_list = StatusList.query.filter_by(
            target_entity_type='Shot').first()

        # there should be a status_list
        # TODO: you should think about how much possible this is
        if status_list is None:
            return HTTPServerError(detail='No StatusList found')

        new_shot = Shot(name=name,
                        code=code,
                        description=description,
                        sequence=sequence,
                        status_list=status_list,
                        status=status,
                        created_by=logged_in_user,
                        project=project)

        DBSession.add(new_shot)

    else:
        logger.debug('there are missing parameters')
        logger.debug('name      : %s' % name)
        logger.debug('code      : %s' % code)
        logger.debug('status    : %s' % status)
        logger.debug('project   : %s' % project)
        HTTPServerError()

    return HTTPOk()
コード例 #12
0
ファイル: api.py プロジェクト: taron-ai/ccvpn2
def api_public_gateways(request):
    domain = request.registry.settings.get('net_domain', '')
    q = DBSession.query(Gateway)

    show_disabled = request.GET.get('show_disabled')

    country = request.GET.get('country')
    hostname = request.GET.get('hostname')

    if country:
        q = q.filter(Gateway.country == country)

    if hostname:
        if '-' in hostname:
            hn_country, hn_name = hostname.split('-', 1)
            q = q.filter(Gateway.country == hn_country)
            q = q.filter(Gateway.name == hn_name)
        elif country:
            q = q.filter(Gateway.name == hostname)
        else:
            return HTTPOk(body=json.dumps([]), content_type="application/json")

    if not show_disabled:
        q = q.filter(Gateway.enabled == True)

    def out(g):
        return {
            'hostname': g.country + '-' + g.name,
            'fqdn': g.country + '-' + g.name + '.' + domain,
            'country': g.country,
            'bandwidth': g.bps,
            'ipv4': g.ipv4,
            'ipv6': g.ipv6,
            'enabled': g.enabled,
        }

    r = [out(g) for g in q.all()]
    return HTTPOk(body=json.dumps(r), content_type="application/json")
コード例 #13
0
ファイル: __init__.py プロジェクト: austinpgraham/Hamburger
 def __call__(self):
     if self.auth_user is None:
         return HTTPForbidden()
     new_obj = self.request.json
     key = getattr(self.context, self.context.__key__, None)
     result = self.context.update_from_external(new_obj, self.request)
     if result is not None:
         raise exception_response(422, body=str({'error': result}))
     if key is not None and ICollection.providedBy(self.context.__parent__):
         parent = self.context.__parent__
         parent.pop(key)
         new_key = getattr(self.context, self.context.__key__)
         parent[new_key] = self.context
     return HTTPOk()
コード例 #14
0
def api_conformance(request):  # noqa: F811
    # type: (Request) -> HTTPException
    """Weaver specification conformance information."""
    # TODO: follow updates with https://github.com/geopython/pygeoapi/issues/198
    conformance = {"conformsTo": [
        "http://www.opengis.net/spec/wfs-1/3.0/req/core",
        "http://www.opengis.net/spec/wfs-1/3.0/req/oas30",
        # "http://www.opengis.net/spec/wfs-1/3.0/req/html",
        "http://www.opengis.net/spec/wfs-1/3.0/req/geojson",
        "http://www.opengis.net/spec/WPS/2.0/req/service/binding/rest-json/core",
        "http://www.opengis.net/spec/WPS/2.0/req/service/binding/rest-json/oas30",
        # "http://www.opengis.net/spec/WPS/2.0/req/service/binding/rest-json/html"
    ]}
    return HTTPOk(json=conformance)
コード例 #15
0
ファイル: views.py プロジェクト: tiagokrebs/zapizza-backend
    def endereco_add(self):
        json_body = self.request.json_body

        """
        A fim de evitar o carregamento de objeto Cliente + filhos
        e o uso de relationship com lazy load nos modelos
        cliente_id é obtido de cliHashid e adicionado ao objeto
        Endereco deserializado através de EnderecoSchema mais tarde
        """
        cliente_hash_id = self.request.matchdict.get('cliHashid')
        cliente_id = get_decoded_id('clientes', cliente_hash_id, self.current_user.empresa_id)

        schema = EnderecoSchema(many=False, strict=True)
        schema.context['cliente_id'] = cliente_id
        schema.context['endereco'] = self.context
        try:
            endereco = schema.load(json_body)
        except ValidationError as err:
            errors = err.messages

            error_list = []
            for k, v in errors.items():
                error_list.append({'field': k, 'message': v})

            msg = 'Dados inválidos'
            res = dumps(dict(
                error=dict(
                    code=400,
                    message=msg,
                    errors=error_list)),
                ensure_ascii=False)
            return HTTPBadRequest(body=res, content_type='application/json; charset=UTF-8')

        # com a deserialização ok a inserção é permitida
        t = endereco.data
        t.cliente_id = cliente_id
        Session.add(t)
        Session.flush()
        Session.refresh(t)
        t.hash_id = generate_hash('enderecos', [self.current_user.empresa_id, t.id])

        # objeto de retorno precisa ser serializado
        result = schema.dump(endereco.data)

        res = dumps(dict(
            data=dict(
                code=200,
                endereco=result.data)),
            ensure_ascii=False)
        return HTTPOk(body=res, content_type='application/json; charset=UTF-8')
コード例 #16
0
ファイル: team.py プロジェクト: woliveira0101/intranet-open
class Team(ApiView):
    def get(self):
        team_id = self.request.matchdict.get('team_id')
        team = Team_m.query.get(team_id)
        if team:
            return team.to_dict()
        else:
            raise HTTPNotFound()

    @has_perm('can_edit_teams')
    def put(self):
        team_id = self.request.matchdict.get('team_id')
        team = Team_m.query.get(team_id)
        if not team:
            raise HTTPNotFound()

        try:
            json_team = self.request.json_body
        except ValueError:
            raise HTTPBadRequest('Expect json')

        team_schema = TeamUpdateSchema()
        try:
            team_des = team_schema.deserialize(json_team)
        except colander.Invalid, e:
            errors = e.asdict()
            raise HTTPBadRequest(errors)

        team.name = team_des.get('name') or team.name

        if 'users' in team_des:
            new_users = team_des['users']
            old_users = DBSession.query(TeamMember.user_id).filter(TeamMember.team_id==team.id).all()
            users_delete = list(set(old_users) - set(new_users))
            users_add = list(set(new_users) - set(old_users))

            if users_delete:
                TeamMember.query.filter(TeamMember.team_id==team.id)\
                                .filter(TeamMember.user_id.in_(users_delete))\
                                .delete(synchronize_session=False)

            if users_add:
                DBSession.add_all([TeamMember(user_id=u_id, team_id=team.id) for u_id in users_add])

        if team_des.get('swap_with_preview'):
            preview = Preview(self.request)
            if not preview.swap_avatar(type='teams', id=team.id):
                raise HTTPBadRequest('No preview to swap')

        return HTTPOk("OK")
コード例 #17
0
def get_job_outputs(request):
    # type: (PyramidRequest) -> AnyResponseType
    """
    Retrieve the output values resulting from a job execution.
    """
    job = get_job(request)
    raise_job_dismissed(job, request)
    raise_job_bad_status(job, request)
    schema = get_schema_query(request.params.get("schema"))
    results, _ = get_results(job, request, schema=schema, link_references=False)
    outputs = {"outputs": results}
    outputs.update({"links": job.links(request, self_link="outputs")})
    outputs = sd.JobOutputsBody().deserialize(outputs)
    return HTTPOk(json=outputs)
コード例 #18
0
ファイル: processes.py プロジェクト: crim-ca/weaver
def get_local_process(request):
    """
    Get a registered local process information (DescribeProcess).
    """
    try:
        process = get_process(request=request)
        process["inputs"] = opensearch.replace_inputs_describe_process(
            process.inputs, process.payload)
        schema = request.params.get("schema")
        offering = process.offering(schema)
        return HTTPOk(json=offering)
    # FIXME: handle colander invalid directly in tween (https://github.com/crim-ca/weaver/issues/112)
    except colander.Invalid as ex:
        raise HTTPBadRequest("Invalid schema: [{!s}]\nValue: [{!s}]".format(
            ex, ex.value))
コード例 #19
0
ファイル: views.py プロジェクト: ucla/PushHubSearch
def update_deletions(context, request):
    """Receive a UID from the request vars and remove the associated
    object from the deleted feed.
    """
    uid = request.POST.get('uid')
    if not uid:
        return
    solr_uri = request.registry.settings.get('push.solr_uri', None)
    if solr_uri is None:
        raise AttributeError(u'A push.solr_uri is required')
    from mysolr import Solr
    solr = Solr(solr_uri)
    logger.debug('Remove deleted status')
    remove_deleted_status(uid, context.shared, solr)
    return HTTPOk(body="Item no longer marked as deleted")
コード例 #20
0
 def filter_output(self, environ, start_response,
                   status, headers, app_iter):
     if self.__detect_flex(environ):
         # All the fuzz is just for Flex/Flash clients.
         # Wrap start response to pass HTTP OK back to Flash. Also, we
         # need to have access to the status later.
         environ['flexfilter.status'] = status
         wrap_start_response = \
           lambda status, headers: start_response(HTTPOk().status, headers)
         return Filter.filter_output(self, environ, wrap_start_response,
                                     status, headers, app_iter)
     else:
         #unfiltered response for non flash clients
         start_response(status, headers)
         return app_iter
コード例 #21
0
def get_providers(request):
    """
    Lists registered providers.
    """
    detail = asbool(request.params.get("detail", True))
    check = asbool(request.params.get("check", True))
    ignore = asbool(request.params.get("ignore", True))
    reachable_services = get_provider_services(request, check=check, ignore=ignore)
    providers = []
    for service in reachable_services:
        summary = service.summary(request, fetch=check, ignore=ignore) if detail else service.name
        if summary:
            providers.append(summary)
    data = {"checked": check, "providers": providers}
    return HTTPOk(json=sd.ProvidersBodySchema().deserialize(data))
コード例 #22
0
def process(context, request):
    """
    Dispatches mapping pipeline for the target project
    """

    source_project_name = request.matchdict['project']
    target_project_name = 'drsc'
    jobid = six.text_type(str(uuid.uuid4()))

    tasks.apply_mappings.apply_async(
        args=[jobid, source_project_name, target_project_name],
        task_id=jobid
    )

    return HTTPOk()
コード例 #23
0
    def delete(self):
        board_id = self.request.matchdict.get('board_id')
        board = m.SprintBoard.query.get(board_id)

        if not board:
            raise HTTPNotFound()

        can_delete = (board.user_id == self.request.user.id)

        if not can_delete:
            raise HTTPForbidden

        DBSession.delete(board)

        return HTTPOk('OK')
コード例 #24
0
ファイル: specimen.py プロジェクト: mstroehle/occams_lims
def add(context, request):
    db_session = request.db_session
    Form = build_add_form(context, request)
    form = Form(request.POST)

    if (request.method == 'POST' and
            check_csrf_token(request) and
            form.validate()):
        state = (
            db_session.query(models.SpecimenState)
            .filter_by(name=u'pending-draw')
            .one())
        patient = (
            db_session.query(studies.Patient)
            .filter_by(pid=form.pid.data)
            .one())
        cycle = db_session.query(studies.Cycle).get(form.cycle_id.data)
        type_ = \
            db_session.query(models.SpecimenType) \
            .get(form.specimen_type_id.data)
        try:
            visit = (
                db_session.query(studies.Visit)
                .filter(studies.Visit.patient_id == patient.id)
                .filter(studies.Visit.cycles.any(id=form.cycle_id.data))
                .one())
        except (orm.exc.MultipleResultsFound, orm.exc.NoResultFound) as e:
            collect_date = None
        else:
            collect_date = visit.visit_date
        db_session.add(models.Specimen(
            patient=patient,
            cycle=cycle,
            specimen_type=type_,
            state=state,
            collect_date=collect_date,
            location=context,
            tubes=type_.default_tubes))
        db_session.flush()
        request.session.flash(
            _(u'Specimen added for ${pid}', mapping={'pid': form.pid.data}),
            'success')
        url = request.current_route_path(_route_name='lims.specimen')
        return HTTPOk(json={'__next__': url})

    return {
        'form': form
    }
コード例 #25
0
ファイル: views.py プロジェクト: tiagokrebs/zapizza-backend
    def login(self):
        request = self.request
        json_body = self.request.json_body

        if 'username' not in json_body:
            msg = 'Username não informado'
            res = dumps(dict(error=dict(code=409, message=msg)),
                        ensure_ascii=False)
            return HTTPConflict(body=res,
                                content_type='application/json; charset=UTF-8')
        username = json_body['username']

        if 'password' not in json_body:
            msg = 'Password não informado'
            res = dumps(dict(error=dict(code=409, message=msg)),
                        ensure_ascii=False)
            return HTTPConflict(body=res,
                                content_type='application/json; charset=UTF-8')
        password = json_body['password']

        user = User.by_username_email(username)
        if user and user.password == password:
            headers = remember(request, user.username)
            msg = 'Login efetuado com sucesso'
            token_data = {'aud': 'idToken', 'username': user.username}
            token = generate_token(request=self.request, data=token_data)
            if user.register_confirm:
                confirmed = True
            else:
                confirmed = False
            res = dumps(dict(data=dict(code=200,
                                       message=msg,
                                       userId=user.username,
                                       idToken=token.decode('utf-8'),
                                       expiresIn=3600,
                                       emailConfirmed=confirmed,
                                       firstName=user.first_name,
                                       lastName=user.last_name)),
                        ensure_ascii=False)
            return HTTPOk(headers=headers,
                          body=res,
                          content_type='application/json; charset=UTF-8')

        msg = 'Username ou senha inválidos'
        res = dumps(dict(error=dict(code=409, message=msg)),
                    ensure_ascii=False)
        return HTTPConflict(body=res,
                            content_type='application/json; charset=UTF-8')
コード例 #26
0
ファイル: checkout.py プロジェクト: mstroehle/occams_lims
def checkout_update(context, request):
    db_session = request.db_session
    vals = filter_aliquot(context, request, state='pending-checkout')

    available_locations = [
        (l.id, l.title)
        for l in db_session.query(models.Location).order_by('title')
    ]

    class CheckoutForm(wtforms.Form):
        location_id = wtforms.SelectField(
            _('Lab Location'),
            description=_('The location of the aliquot'),
            choices=available_locations,
            coerce=int,
            validators=[wtforms.validators.DataRequired()])
        sent_date = DateField(_(u'Sent Date'),
                              description=_(u'Date sent for analysis.'),
                              validators=[
                                  wtforms.validators.Optional(),
                                  DateRange(min=date(1900, 1, 1))
                              ])
        sent_name = wtforms.StringField(
            _(u'Sent Name '),
            description=_(u'The name of the aliquot\'s receiver.'),
            validators=[wtforms.validators.Optional()])
        sent_notes = wtforms.TextAreaField(
            _(u'Sent Notes '),
            description=_(u'Notes about this aliquot\'s destination'),
            validators=[wtforms.validators.Optional()])

    form = CheckoutForm(request.POST, location_id=context.id)

    if request.method == 'POST' and check_csrf_token(request):

        if 'save' in request.POST and form.validate():
            for sample in vals['full_query']:
                apply_changes(form, sample)
            request.session.flash(_(u'Changed saved'), 'success')
            return HTTPOk(
                json={
                    '__next__':
                    request.current_route_path(_route_name='lims.checkout')
                })

    vals.update({'form': form})

    return vals
コード例 #27
0
ファイル: views.py プロジェクト: ucla/PushHubSearch
 def __call__(self):
     #  If the request isn't an RSS feed, bail out
     if self.request.content_type not in ALLOWED_CONTENT:
         body_msg = (
             "The content-type of the request must be one of the "
             "following: %s"
         ) % ", ".join(ALLOWED_CONTENT)
         return HTTPBadRequest(body=body_msg)
     # Create / update
     self._process_items()
     # Index in Solr
     self._update_index()
     # Return a 200 with details on what happened in the body
     self.messages.append("%s items created." % self.create_count)
     self.messages.append("%s items updated." % self.update_count)
     return HTTPOk(body=" ".join(self.messages))
コード例 #28
0
def delete_json(context, request):
    check_csrf_token(request)
    dbsession = request.dbsession
    exists = (
        dbsession.query(sa.literal(True))
        .filter(
            dbsession.query(models.PatientReference)
            .filter_by(reference_type=context)
            .exists())
        .scalar())
    if exists:
        raise HTTPBadRequest(
            body=_(u'This reference number still has data associated with it'))
    dbsession.delete(context)
    dbsession.flush()
    return HTTPOk()
コード例 #29
0
def get_job_inputs(request):
    # type: (PyramidRequest) -> AnyResponseType
    """
    Retrieve the inputs values and outputs definitions of a job.
    """
    job = get_job(request)
    schema = get_schema_query(request.params.get("schema"), strict=False)
    job_inputs = job.inputs
    job_outputs = job.outputs
    if schema:
        job_inputs = convert_input_values_schema(job_inputs, schema)
        job_outputs = convert_output_params_schema(job_outputs, schema)
    body = {"inputs": job_inputs, "outputs": job_outputs}
    body.update({"links": job.links(request, self_link="inputs")})
    body = sd.JobInputsBody().deserialize(body)
    return HTTPOk(json=body)
コード例 #30
0
ファイル: providers.py プロジェクト: crim-ca/weaver
def get_provider_processes(request):
    # type: (PyramidRequest) -> AnyViewResponse
    """
    Retrieve available provider processes (GetCapabilities).
    """
    detail = asbool(request.params.get("detail", True))
    provider_id = request.matchdict.get("provider_id")
    store = get_db(request).get_store(StoreServices)
    service = store.fetch_by_name(provider_id)
    processes = service.processes(request)
    processes = [p.summary() if detail else p.id for p in processes]
    links = get_process_list_links(request,
                                   paging={},
                                   total=None,
                                   provider=service)
    return HTTPOk(json={"processes": processes, "links": links})
コード例 #31
0
ファイル: views.py プロジェクト: tiagokrebs/zapizza-backend
    def endereco_get(self):
        endereco = self.context
        schema = EnderecoSchema(many=False, strict=True)
        result = schema.dump(endereco)

        if endereco:
            res = dumps(dict(
                data=dict(
                    code=200,
                    endereco=result.data)),
                ensure_ascii=False)
            return HTTPOk(body=res, content_type='application/json; charset=UTF-8')

        msg = 'Nenhum registro encontrado'
        res = dumps(dict(error=dict(code=404, message=msg)), ensure_ascii=False)
        return HTTPNotFound(body=res, content_type='application/json; charset=UTF-8')
コード例 #32
0
    def registration(self):
        request = self.request

        nome = request.params.get('nome', None)
        cognome = request.params.get('cognome', None)
        password = request.params.get('password', None)
        username = request.params.get('username', None)

        logger.info('REGISTRATION INPUT sono: {nome}, {cognome}, {password}, {username}'.format(nome=nome,
                                                                                               cognome=cognome,
                                                                                               password=password,
                                                                                               username=username))

        if nome is not None and nome != '':
            if cognome is not None and cognome != '':
                if password is not None and password != '':
                    if username is not None and username != '':
                        # controller
                        result = AuthenticationController.registration(request.dbsession, nome, cognome, password,
                                                                       username)
                        logger.info('REGISTRATION OUTPUT é: {}'.format(json.dumps(result)))

                        if result['code'] == self.success_request:
                            logger.info('REGISTRATION COMPLETATA!')
                            return HTTPOk(body='Registrazione completata con successo!')
                        elif result['code'] == self.not_acceptable_request:
                            logger.error('REGISTRATION FALLITA: {}'.format(result['message']))
                            return HTTPNotAcceptable(body=result['message'])
                        elif result['code'] == self.conflict_request:
                            logger.error('REGISTRATION FALLITA: {}'.format(result['message']))
                            return HTTPConflict(body=result['message'])
                        else:
                            logger.error('REGISTRATION FALLITA: errore inaspettato.')
                            logger.error('{}'.format(result['message']))
                            return HTTPInternalServerError(body='Errore inaspettato. Ci scusiamo per il disagio!')
                    else:
                        logger.error('REGISTRATION FALLITA perché manca il parametro USERNAME')
                        return HTTPNotAcceptable('Manca lo USERNAME! Controlla.')
                else:
                    logger.error('REGISTRATION FALLITA perché manca il parametro PASSWORD')
                    return HTTPNotAcceptable('Manca la PASSWORD! Controlla.')
            else:
                logger.error('REGISTRATION FALLITA perché manca il parametro COGNOME')
                return HTTPNotAcceptable('Manca il COGNOME! Controlla.')
        else:
            logger.error('REGISTRATION FALLITA perché manca il parametro NOME')
            return HTTPNotAcceptable('Manca il NOME! Controlla.')
コード例 #33
0
ファイル: controller.py プロジェクト: eternalharvest/eye
def start(request):
	#
	# NIC の 情報を取得
	#
	interface = 'lo0'
        if 'interface' in request.GET:
		interface = request.GET['interface']

	#
	# NIC の 情報取得
	#
	bacnet_address = None
	try:
		#
		# NIC から IPv4 アドレスの取得
		#
		iface_data = netifaces.ifaddresses(interface)
		ipv4 = iface_data.get(netifaces.AF_INET)
		if not ipv4 == None:
			prefix = IPAddress(ipv4[0]['netmask']).netmask_bits()
			bacnet_address = '%s/%d' %(ipv4[0]['addr'], prefix)
	#
	# NIC の情報が見つからなかった場合の処理
	#
	except ValueError:
		return HTTPBadRequest()

	#
	# BACnet アドレスが定義されていない場合
	#
	if bacnet_address == None:
		return HTTPBadRequest()

	#
	# BACnet Daemon が 起動しているか確認
	#
	if request.registry.bacnetd == None:
		#
		# BACnet Daemon の 起動
		#
		request.registry.bacnetd = BACnetd(bacnet_address)
		request.registry.bacnetd.start()

	#
	# BACnet Daemon 起動結果を返す
	#
	return HTTPOk()
コード例 #34
0
ファイル: views.py プロジェクト: aliendb/ichnaea
 def success(self):
     response = HTTPOk()
     response.content_type = 'application/json'
     response.body = '{}'
     return response