Ejemplo n.º 1
0
Archivo: views.py Proyecto: 3taps/geo
def get(request):
    """ Respond to the "/get" URL.

        This API call retrieves a generated tableau from the cache.

        The "/get" API call expects the following (GET or POST) parameters:

            "loc_code"

                The 3taps location code for the location we want to generate a
                tableau for.

            "name"

                The name of the tableau to generate.

            "width", "height"

                The pixel width and height of the tableau to generate.

        If the given tableau is in the cache, we return the cached tableau.
        Otherwise, we generate the tableau on-the-fly, add it to the cache, and
        return it back to the caller.

        Upon completion, we return a JSON-format object with the following
        entries:

            'tableau'

                The cached (or generated) tableau.

            'error'

                If an error occurred, this will be an object with 'code' and
                'message' fields describing what went wrong.
    """
    # Extract our parameters.

    if request.method == "GET":
        params = request.GET
    else:
        params = request.POST

    if "loc_code" not in params:
        return HttpResponse("Missing required 'loc_code' parameter.",
                            mimetype="text/plain")
    else:
        loc_code = params['loc_code']

    if "name" not in params:
        name = "DEFAULT"
    else:
        name = params['name']

    if "width" not in params:
        return HttpResponse("Missing required 'width' parameter.",
                            mimetype="text/plain")
    else:
        try:
            width = int(params['width'])
        except ValueError:
            return HttpResponse("Invalid 'width' parameter.",
                                mimetype="text/plain")

    if "height" not in params:
        return HttpResponse("Missing required 'height' parameter.",
                            mimetype="text/plain")
    else:
        try:
            height = int(params['height'])
        except ValueError:
            return HttpResponse("Invalid 'height' parameter.",
                                mimetype="text/plain")

    # See which tableau the caller is requesting.

    tableau = tableauGenerator.select_tableau(loc_code, name)
    if tableau == None:
        return HttpResponse("There is no tableau for this location.",
                            mimetype="text/plain")

    # If the requested tableau is in the cache, return it back to the caller.

    json_data = tableauCache.get(tableau.id, width, height)
    if json_data != None:
        callback = params.get("callback")
        if callback != None:
            json_data = callback + "(" + json_data + ")" # Add JSONP callback.
        return HttpResponse(json_data, mimetype="application/json")

    # If we get here, the requested tableau isn't in the cache.  Generate it
    # on-the-fly.

    try:
        generated_tableau = tableauGenerator.generate_tableau(tableau,
                                                              width,
                                                              height)
    except:
        # Something went wrong.  Print the traceback into the Django log and
        # return an error back to the caller.
        traceback.print_exc()
        return HttpResponse("Internal exception while generating tableau.",
                            mimetype="text/plain")

    json_data = json.dumps({'tableau' : generated_tableau})

    # Save the generated tableau into the cache.

    tableauCache.save(tableau.id, width, height, json_data)

    # Finally, return the newly-generated tableau back to the caller.

    return HttpResponse(json_data, mimetype="application/json")
Ejemplo n.º 2
0
Archivo: preview.py Proyecto: 3taps/geo
def preview(request):
    """ Respond to the "/preview/" URL.

        We preview the tableau for the given location.
    """
    if not request.user.is_authenticated:
        return HttpResponseRedirect(reverse(settings.ADMIN_HOME_VIEW))

    if request.method == "GET":
        loc_code     = request.GET.get("location")
        tableau_name = request.GET.get("tableau")
    elif request.method == "POST":
        loc_code     = request.POST.get("location")
        tableau_name = request.POST.get("tableau")

        if request.POST.get("finished") != None:
            # Redirect the user back to the main "edit tableau" page.

            try:
                tableau = Tableau.objects.get(location__code=loc_code,
                                              name=tableau_name)
            except Tableau.DoesNotExist:
                return HttpResponseRedirect(
                            reverse("location_editor.views.tableaux",
                                    args=[loc_code]))

            return HttpResponseRedirect(
                            reverse("tableau_editor.views.edit_tableau",
                                    args=[tableau.id]))

    # Prepare the tableau to display.

    max_width  = 800
    max_height = 600

    try:
        tableau = Tableau.objects.get(location__code=loc_code,
                                      name=tableau_name)
    except Tableau.DoesNotExist:
        return HttpResponseRedirect(
                    reverse("location_editor.views.tableaux",
                            args=[loc_code]))

    layout              = tableau.tableaulayout_set.all()[0]
    layout_aspect_ratio = float(layout.width) / float(layout.height)

    if max_width / layout_aspect_ratio > max_height:
        height = max_height
        width  = int(height * layout_aspect_ratio)
    else:
        width  = max_width
        height = int(width / layout_aspect_ratio)

    generated_tableau = tableauGenerator.generate_tableau(tableau,
                                                          width, height)

    shapes = []

    # Add a rectangle to show the tableau's bounds.

    render = generated_tableau['render']

    shapes.append({'type'        : "RECTANGLE",
                   'x'           : 0,
                   'y'           : 0,
                   'width'       : width,
                   'height'      : height,
                   'fillColour'  : render.get('fill_color',     "none"),
                   'fillOpacity' : render.get('fill_opacity',   1.0),
                   'lineColour'  : render.get('border_color',   "none"),
                   'lineSize'    : render.get('border_size',    0.0),
                   'lineOpacity' : render.get('border_opacity', 1.0),
                  })

    # Process the tableau's views.

    for view in generated_tableau['views']:

        # Draw the view's outline.

        render = view['render']

        shapes.append({'type'        : "RECTANGLE",
                       'x'           : view['min_x'],
                       'y'           : view['min_y'],
                       'width'       : view['max_x'] - view['min_x'] + 1,
                       'height'      : view['max_y'] - view['min_y'] + 1,
                       'fillColour'  : render.get('fill_color',     "none"),
                       'fillOpacity' : render.get('fill_opacity',   1.0),
                       'lineColour'  : render.get('border_color',   "none"),
                       'lineSize'    : render.get('border_size',    0.0),
                       'lineOpacity' : render.get('border_opacity', 1.0),
                       })

        # Draw the view's location polygons.

        for location in view['locations']:
            render = location['render']
            for polygon in location['polygons']:
                exterior = []
                for x,y in polygon['exterior']:
                    exterior.append([x, y])
                shapes.append(
                      {'type'        : "POLYGON",
                       'exterior'    : exterior,
                       'fillColour'  : render.get('fill_color',     "none"),
                       'fillOpacity' : render.get('fill_opacity',   1.0),
                       'lineColour'  : render.get('border_color',   "none"),
                       'lineSize'    : render.get('border_size',    0.0),
                       'lineOpacity' : render.get('border_opacity', 1.0),
                      })

    # Display the generated web page.

    menu_html = menus.generate(request, "Tableau Editor",
                               "tableau_editor", "preview")

    return render_to_response("tableau_editor/templates/preview.html",
                              {'menu_html'    : menu_html,
                               'heading'      : "Previewing tableau '" +
                                                tableau_name + "'",
                               'loc_code'     : loc_code,
                               'tableau_name' : tableau_name,
                               'width'        : width,
                               'height'       : height,
                               'shapes'       : shapes,
                              },
                              context_instance=RequestContext(request))
Ejemplo n.º 3
0
Archivo: views.py Proyecto: 3taps/geo
def generate(request):
    """ Respond to the "/generate" URL.

        This is an API call which is called by our daemon process to generate
        and cache a single tableau.  The "/generate" API call expects the
        following (GET or POST) parameters:

            "loc_code"

                The 3taps location code for the location we want to generate a
                tableau for.

            "name"

                The name of the tableau to generate.

            "width", "height"

                The pixel width and height of the tableau to generate.

        Upon completion, we return a single-line string indicating the success
        or otherwise of the request.  If the tableau was successfully
        generated, we return the string "OK".
    """
    # Extract our parameters.

    if request.method == "GET":
        params = request.GET
    else:
        params = request.POST

    if "loc_code" not in params:
        return HttpResponse("Missing required 'loc_code' parameter.",
                            mimetype="text/plain")
    else:
        loc_code = params['loc_code']

    if "name" not in params:
        return HttpResponse("Missing required 'name' parameter.",
                            mimetype="text/plain")
    else:
        name = params['name']

    if "width" not in params:
        return HttpResponse("Missing required 'width' parameter.",
                            mimetype="text/plain")
    else:
        try:
            width = int(params['width'])
        except ValueError:
            return HttpResponse("Invalid 'width' parameter.",
                                mimetype="text/plain")

    if "height" not in params:
        return HttpResponse("Missing required 'height' parameter.",
                            mimetype="text/plain")
    else:
        try:
            height = int(params['height'])
        except ValueError:
            return HttpResponse("Invalid 'height' parameter.",
                                mimetype="text/plain")

    # Ask the tableau generator to select the tableau to use.

    tableau = tableauGenerator.select_tableau(loc_code, name)
    if tableau == None:
        return HttpResponse("There is no tableau for this location.",
                            mimetype="text/plain")

    # Generate the tableau.

    try:
        generated_tableau = tableauGenerator.generate_tableau(tableau,
                                                              width,
                                                              height)
    except:
        # Something went wrong.  Print the traceback into the Django log and
        # return an error back to the caller.
        traceback.print_exc()
        return HttpResponse("Internal exception while generating tableau.",
                            mimetype="text/plain")

    json_data = json.dumps({'tableau' : generated_tableau})

    # Save the generated tableau into the cache.

    tableauCache.save(tableau.id, width, height, json_data)

    # Finally, tell the caller the good news.

    return HttpResponse("OK", mimetype="text/plain")