Ejemplo n.º 1
0
def statistic_sheet_add_edit_view(context, request):
    """
    View for adding editing statistics sheets
    """
    post_datas = request.POST or request.json_body
    if 'title' in post_datas:
        schema = SQLAlchemySchemaNode(StatisticSheet, includes=('title',))

        try:
            appstruct = schema.deserialize(request.POST)
        except colander.Invalid:
            logger.exception(u"Erreur à la création de la feuille de \
statistiques")
        else:
            if context.__name__ == 'statistic_sheet':
                sheet = schema.objectify(appstruct, context)
                sheet = request.dbsession.merge(sheet)
            else:
                sheet = schema.objectify(appstruct)
                request.dbsession.add(sheet)
            request.dbsession.flush()
            url = request.route_path('statistic', id=sheet.id)
            return dict(redirect=url)
        logger.debug(u"Invalid datas have been passed")
        raise HTTPClientError()
    logger.debug(u"Missing datas in the request")
    raise HTTPClientError()
Ejemplo n.º 2
0
def modal(request):
    """ Generate the content for the modal data series page """
    urlparts = request.matchdict['params']
    if len(urlparts) != 1:
        return HTTPClientError()

    collection = urlparts[0]
    if collection in templates:
        template = templates[collection]
    else:
        return HTTPClientError()

    page_renderer = get_renderer("../templates/modals/%s" % template)
    modal_body = page_renderer.implementation().macros["modal_body"]

    # should we only load the scripts when the modal is required?
    #modalscripts = [
    #    "modals/modal.js",
    #    "modals/ampicmp_modal.js",
    #]

    return {
        #"title": "Add new data series",
        "modal_body": modal_body,
        #"styles": None,
        #"scripts": modalscripts,
    }
Ejemplo n.º 3
0
    def view_set(self):
        questions = self.request.question_set.questions
        question_ids = [q.id for q in questions]

        template_vars = {
            'page_title': 'Viewing Question Set',
            'username': self.request.username,
            'question_set_description': self.request.question_set.description,
            'question_set_id': self.request.question_set.id,
            'questions': questions,
            'question_choices': forms.get_question_select_options(self.request.route_url('question_creation_form')),
            'csrf_token': self.request.session.get_csrf_token(),
        }
        if question_ids:
            reorder_form = forms.ReorderResourceForm(self.request, question_ids, 'Reorder')
        if self.request.method == 'GET':
            if question_ids:
                template_vars['reorder_form'] = reorder_form
            return template_vars
        elif self.request.method == 'POST' and question_ids:
            try:
                appstruct = reorder_form.validate(self.request.POST)
                self.request.question_set.reorder(appstruct, self.request.db)
                return HTTPOk()
            except ValueError as _:
                return HTTPClientError()
            return HTTPFound(self.request.route_url('profile'))
        else:
            return HTTPClientError()
Ejemplo n.º 4
0
def delete_resource(request, resource_attr):
    try:
        csrf_token = request.POST['csrf_token']
        if not csrf_token == request.session.get_csrf_token():
            return HTTPClientError()
    except Exception as _:
        return HTTPClientError()
    resource = getattr(request, resource_attr)
    request.db.delete(resource)
    request.db.commit()
    return HTTPNoContent()
Ejemplo n.º 5
0
def view_accept_login(request):
    try:
        userid = request.params.get('userid')
        password = request.params.get('password')
        users = WebUsers.objects(userid=userid)
        if(len(users) > 0 and pwd_context.verify(password, users[0].password)):
            print "apparently a match"
            headers = remember(request, userid)
            return HTTPFound(location = request.route_url('home'),
                                 headers =headers)
        else:
            return HTTPClientError("Login failure")
    except Exception as e:
        return HTTPClientError(str(e))
Ejemplo n.º 6
0
def rating(request):
    urlparts = request.matchdict['params']
    if len(urlparts) != 2:
        return HTTPClientError()

    ampy = initAmpy(request)
    if ampy is None:
        print("Failed to start ampy while creating event rating modal")
        return None

    eventid = urlparts[0]
    streamid = urlparts[1]

    # TODO grab some descriptive information that we can display about
    # this modal

    evdeets = ampy.get_single_event(streamid, eventid)

    request.override_renderer = "../templates/modals/eventrating.pt"

    return {
        "title": "Provide Feedback on this Event",
        "evstreamlabel": "TODO",
        "description": evdeets['description'],
        "eventid": eventid,
        "streamid": streamid,
    }
Ejemplo n.º 7
0
def do_search_extracts(request):
    uri = request.GET.get('uri', None)
    if not uri:
        raise HTTPClientError("Please specify a URI")
    view_def = request.GET.get('view') or 'default'
    discussion = request.context
    user_id = authenticated_userid(request)
    if not user_id:
        # Straight from annotator
        token = request.headers.get('X-Annotator-Auth-Token')
        if token:
            token = decode_token(token,
                                 request.registry.settings['session.secret'])
            if token:
                user_id = token['userId']
    user_id = user_id or Everyone
    if not user_has_permission(discussion.id, user_id, P_READ):
        raise HTTPForbidden()
    permissions = [P_READ]

    if not uri:
        raise HTTPBadRequest("Please specify a search uri")
    content = Webpage.get_by(url=uri)
    if content:
        extracts = Extract.default_db.query(Extract).filter_by(
            content=content).all()
        rows = [
            extract.generic_json(view_def, user_id, permissions)
            for extract in extracts
        ]
        return {"total": len(extracts), "rows": rows}
    return {"total": 0, "rows": []}
Ejemplo n.º 8
0
 def get_question_creation_form(self):
     try:
         schema, _ = forms.get_question_creation_schema(self.request.GET)
         action = self.request.route_path('create_question', question_set_id=self.request.GET['question_set_id'])
         form = Form(schema.bind(request=self.request), buttons=('create',), action=action)
         return Response(body=form.render())
     except Exception as _:
         return HTTPClientError()
Ejemplo n.º 9
0
 def test_render_http_client_exception(self, request_):
     from pyramid.httpexceptions import HTTPClientError
     error = HTTPClientError(status_code=400)
     json_error = self.call_fut(error, request_)
     assert json_error.status_code == 400
     assert json_error.json_body == \
            {"status": "error",
             "errors": [{"description": "{0} {1}".format(error.status, error),
                         "name": "GET",
                         "location": "url"}]}
Ejemplo n.º 10
0
def remove_view(request):
    id = request.matchdict['id']
    question = Question(_id=id)
    try:
        log.debug('Removing question with id: "%s"', id)
        question.delete()
    except (NotFoundError, OperationFailure) as e:
        log.debug('Invalid question id: "%s"', id)
        return HTTPClientError('Invalid Request: Question does not exist.')
    return HTTPFound(location=request.route_url('list'))
Ejemplo n.º 11
0
def ask_view(request):
    if request.method == 'POST':
        content = request.POST.get('content')
        if content:
            # save question
            log.debug('Adding question content: "%s"', content)
            question = Question(content=content)
            question.save()
        else:
            # invalid question
            log.debug('Invalid question content: "%s"', content)
            return HTTPClientError(
                'Invalid Request: Question content cannot be empty.')
    return HTTPFound(location=request.route_url('list'))
Ejemplo n.º 12
0
    def api_search_html(self):
        """
        View code

        Performs search request to the DDB API.
        Returns the result as HTML

        Requires:
            - HTTP-GET request
            - HTTP-GET parameter format set to 'html'

        Returns:
            - HTML

        Raises:
            - HttpError
        """
        try:
            params = {}
            params['query'] = self.request.GET['query']
            bbox = self.request.GET['bbox'].split(",")
            bbox = dict(min_y=bbox[1],
                        min_x=bbox[0],
                        max_y=bbox[3],
                        max_x=bbox[2])

            resolution = float(
                self.request.GET['resolution'])  #611.4962261962891
            radius = 20

            request = self._api_search(**params)
            if request and request.ok:
                jresult = request.json()["results"][0]["docs"]
                dict_of_ids = {}
                for d in jresult:
                    dict_of_ids[d['id']] = d['title']

                clusters = self._cluster(bbox=bbox,
                                         resolution=resolution,
                                         radius=radius,
                                         ids=dict_of_ids)
                result = dict(type="FeatureCollection",
                              features=[c.__json__() for c in clusters])
                return result
            else:
                raise HTTPError("Request failed")
        except Exception, e:
            raise HTTPClientError("Request failed")
Ejemplo n.º 13
0
def detail_view(request):
    """
    Directs user to a detailed view of an item
    """
    if 'upc' not in request.matchdict:
        return HTTPClientError()
    upc = request.matchdict['upc']
    user = request.dbsession.query(Account).filter(
        Account.username == request.authenticated_userid).first()
    item = filter(lambda n: n.item.upc == upc, user.pantry_items)
    try:
        product = next(item)
    except StopIteration:
        raise HTTPNotFound

    return {'item': product.item}
Ejemplo n.º 14
0
def _validate_request(route_mapper, request, schema_data, resolver):
    """ Validates a request and raises an HTTPClientError on failure.

    :param request: the request object to validate
    :type request: Pyramid request object passed into a view
    :param schema_data: our mapping from request data to schemas (see
        load_schema)
    :type schema_data: dict
    :param resolver: the request object to validate
    :type resolver: Pyramid request object passed into a view
    """
    try:
        validate_incoming_request(route_mapper, request, schema_data, resolver)
    except jsonschema.exceptions.ValidationError as exc:
        # This will alter our stack trace slightly, but Pyramid knows how
        # to render it. And the real value is in the message anyway.
        raise HTTPClientError(str(exc))
Ejemplo n.º 15
0
def get_org(request):
    log.info("Getting org for request {0}".format(request.GET))
    for k in ('city', 'state', 'name', 'url'):
        if k not in request.GET:
            log.error("Request is missing one of city, state, name or url")
            raise HTTPClientError("Missing required parameter")
    city = request.GET['city']
    state = request.GET['state']
    name = request.GET['name']
    url = request.GET['url']
    # Get or create org for query
    org, created = get_or_create(db, Org, city=city, state=state, name=name, url=url)
    # Geocode if missing lat and/or lng
    if not org.lat or not org.lng:
        org = geocode(org, request.registry.settings)
        # Save changes
        db.flush()
    # Return the org
    return org
Ejemplo n.º 16
0
def find_schema_for_request(schema, request):
    try:
        return schema.schema_and_resolver_for_request(request)
    except PathNotMatchedError as exc:
        raise HTTPClientError(str(exc))
Ejemplo n.º 17
0
 def __init__(self, detail=None, headers=None, comment=None,
              body_template=None, result=None, **kw):
     HTTPClientError.__init__(self, detail=detail, headers=headers,
                              comment=comment, body_template=body_template,
                              **kw)
     self.result = result