Exemplo n.º 1
0
    def __call__(self, environ, start_response):
        try:
            method = environ.get("REQUEST_METHOD", "GET")
            if method.upper() not in self.config["methods"]:
                start_response("405 Method Not Allowed")
                return ["405 Method Not Allowed"]
            accept = environ.get("HTTP_ACCEPT", "*/*")
            negotiated = negotiate(self.config["mime_types"], accept)
            return self.request(environ, start_response, method, negotiated)
        except:
            log.error(
                "%s %s %s exception:\n%s"
                % (
                    environ.get("REMOTE_ADDR"),
                    environ.get("REQUEST_METHOD"),
                    environ.get("DOCUMENT_URI", "/"),
                    format_exc(),
                )
            )
            log.error(
                "%s %s %s environ:\n%s"
                % (
                    environ.get("REMOTE_ADDR"),
                    environ.get("REQUEST_METHOD"),
                    environ.get("DOCUMENT_URI", "/"),
                    pformat(environ),
                )
            )

            start_response("500 Internal Server Error", [("Content-Type", "text/plain; charset=utf-8")])
            if self.opts.debug:
                return [format_exc()]
            else:
                return ["Oops. The admin should look at the logs"]
Exemplo n.º 2
0
    def read(self, id):
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'extras_as_string': True,
                   'schema': self._form_to_db_schema()}
        data_dict = {'id': id}
        split = id.split('@')
        if len(split) == 2:
            data_dict['id'], revision = split
            try:
                date = datetime.datetime(*map(int, re.split('[^\d]', revision)))
                context['revision_date'] = date
            except ValueError:
                context['revision_id'] = revision
        #check if package exists
        try:
            c.pkg_dict = get.package_show(context, data_dict)
            c.pkg = context['package']
        except NotFound:
            abort(404, _('Package not found'))
        except NotAuthorized:
            abort(401, _('Unauthorized to read package %s') % id)
        
        cache_key = self._pkg_cache_key(c.pkg)        
        etag_cache(cache_key)
        
        #set a cookie so we know whether to display the welcome message
        c.hide_welcome_message = bool(request.cookies.get('hide_welcome_message', False))
        response.set_cookie('hide_welcome_message', '1', max_age=3600) #(make cross-site?)

        # used by disqus plugin
        c.current_package_id = c.pkg.id
        
        if config.get('rdf_packages'):
            accept_header = request.headers.get('Accept', '*/*')
            for content_type, exts in negotiate(autoneg_cfg, accept_header):
                if "html" not in exts: 
                    rdf_url = '%s%s.%s' % (config['rdf_packages'], c.pkg.id, exts[0])
                    redirect(rdf_url, code=303)
                break

        PackageSaver().render_package(c.pkg_dict, context)
        return render('package/read.html')
Exemplo n.º 3
0
        c.hide_welcome_message = bool(request.cookies.get('hide_welcome_message', False))
        response.set_cookie('hide_welcome_message', '1', max_age=3600) #(make cross-site?)

        # used by disqus plugin
        c.current_package_id = c.pkg.id

        # Add the package's activity stream (already rendered to HTML) to the
        # template context for the package/read.html template to retrieve
        # later.
        c.package_activity_stream = \
                ckan.logic.action.get.package_activity_list_html(context,
                    {'id': c.current_package_id})

        if config.get('rdf_packages'):
            accept_header = request.headers.get('Accept', '*/*')
            for content_type, exts in negotiate(autoneg_cfg, accept_header):
                if "html" not in exts: 
                    rdf_url = '%s%s.%s' % (config['rdf_packages'], c.pkg.id, exts[0])
                    redirect(rdf_url, code=303)
                break

        PackageSaver().render_package(c.pkg_dict, context)
        return render('package/read.html')

    def comments(self, id):
        package_type = self._get_package_type(id)
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'extras_as_string': True,}

        #check if package exists
        try:
Exemplo n.º 4
0
            abort(404, _('Package not found'))
        except NotAuthorized:
            abort(401, _('Unauthorized to read package %s') % id)

        #set a cookie so we know whether to display the welcome message
        c.hide_welcome_message = bool(
            request.cookies.get('hide_welcome_message', False))
        response.set_cookie('hide_welcome_message', '1',
                            max_age=3600)  #(make cross-site?)

        # used by disqus plugin
        c.current_package_id = c.pkg.id

        if config.get('rdf_packages'):
            accept_header = request.headers.get('Accept', '*/*')
            for content_type, exts in negotiate(autoneg_cfg, accept_header):
                if "html" not in exts:
                    rdf_url = '%s%s.%s' % (config['rdf_packages'], c.pkg.id,
                                           exts[0])
                    redirect(rdf_url, code=303)
                break

        PackageSaver().render_package(c.pkg_dict, context)
        return render('package/read.html')

    def comments(self, id):
        context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author,
            'extras_as_string': True,
Exemplo n.º 5
0
    def on_search(self, request, index):
        if index not in self.indexes:
            raise NotFound("index %s" % index)
        node = self.indexes[index]["node"]

        if "predicate" in request.args:
            predicate = request.args["predicate"]
        else:
            predicate = "nearest"
        if predicate not in ["intersects", "contains", "nearest"]:
            msg = { "message": "predicate must be one of intersects, contains, hearest" }
            raise BadRequest(json.dumps(msg))

        operand = None
        if "wkt" in request.args:
            operand = ogr.CreateGeometryFromWkt(request.args["wkt"])
        elif "bbox" in request.args:
            bbox = request.args["bbox"].split(",")
            try:
                miny, minx, maxy, maxx = [Decimal(x.strip()) for x in bbox]
            except:
                msg = { "message": "invalid bounding box" }
                raise BadRequest(json.dumps(msg))
            bbox = "POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))" % (
                minx, miny, minx, maxy, maxx, maxy, maxx, miny, minx, miny
                )
            operand = ogr.CreateGeometryFromWkt(bbox)
        elif "circle" in request.args:
            spec = request.args["circle"].split(",")
            try:
                y,x,r = [Decimal(x.strip()) for x in spec]
            except:
                msg = { "message": "invalid circle specification" }
                raise BadRequest(json.dumps(msg))
            centre = ogr.CreateGeometryFromWkt("POINT(%s %s)" % (x, y))

            ### radius is given in kilometers. the delta is in
            ### degrees. this approximation works only away
            ### from the poles and for small radii. the magic
            ### number is the radius of the earth in meters
            delta = degrees(float(r) / (6371.0 * cos(radians(x))))
            operand = centre.Buffer(delta)

        if operand is None:
            msg = { "message": "missing or invalid spatial argument (bbox or wkt)" }
            raise BadRequest(json.dumps(msg))

        if operand.GetGeometryType() == ogr.wkbPoint:
            operand = operand.Buffer(0.0001)

        if predicate == "intersects":
            results = node.intersection(operand)
        elif predicate == "contains":
            results = node.contains(operand)
        elif predicate == "nearest":
            try:
                limit = int(request.args["limit"])
            except:
                limit = 10
            results = node.nearest(operand, limit)

        try:
            limit = int(request.args["limit"])
        except:
            limit = 10
        if limit > 1000:
            limit = 1000

        try:
            offset = int(request.args["offset"])
        except:
            offset = 0

        if "type" in request.args or "text" in request.args:
            results = parse_graph(results)
        if "type" in request.args:
            results = filter_types(results, *(URIRef(x) for x in request.args.getlist("type")))
        if "text" in request.args:
            results = filter_text(results, request.args["text"])
        if "type" in request.args or "text" in request.args:
            results = trim_graph(results)
        results = filter_offset(results, offset)
        results = filter_limit(results, limit)

        ancfg = (
            ("text", "turtle", ["turtle"]),
            ("text", "javascript", ["rdf-json"]),
            ("text", "n-triples", ["ntriples"]),
            ("text", "n-quads", ["nquads"]),
            ("application", "rdf+xml", ["xml"]),
            ("application", "json", ["rdf-json"]),
            )

        query = request.args.get("query")
        if query is None:
            data = json.dumps(list(results))
            response = Response(data, mimetype="application/json")
        elif query == "closure":
            accept = request.headers.get("Accept", "*/*")
            candidates = list(negotiate(ancfg, accept))
            if len(candidates) == 0:
                raise NotAcceptable()
            mime_type = candidates[0][0]
            format = candidates[0][1][0]
            cg = ConjunctiveGraph()
            for obj in results:
                ### this shouldn't decode / reencode the json here!
                json_description = json.dumps(obj["json_description"])
                g = Graph(identifier=URIRef(obj["graph"]), store=cg.store)
                RdfJsonParser().parse_json(obj["json_description"], g)
            data = cg.serialize(format=format)
            response = Response(data, mimetype=mime_type)
        else:
            raise BadRequest("no idea what kind of query that is")

        return response