示例#1
0
文件: views.py 项目: 3taps/geo
def search_by_name(request):
    """ Implement the "/name" API call.
    """
    # Extract our parameters.

    levels = []

    level_param = get_param(request, "level")
    if level_param != None:
        level = name_to_level(level_param)
        if level == None:
            return error_response(
                code=400, message="Unknown level: " + repr(level_param), callback=get_param(request, "callback")
            )
        levels.append(level)
    else:
        levels_param = get_param(request, "levels")
        if levels_param != None:
            for level_name in levels_param.split(","):
                level = name_to_level(level_name)
                if level == None:
                    return error_response(
                        code=400, message="Unknown level: " + repr(level_param), callback=get_param(request, "callback")
                    )
                levels.append(level)

    text = get_param(request, "text")

    if text == None:
        return error_response(code=400, message="Missing 'text' parameter.", callback=get_param(request, "callback"))
    if len(text) < 3:
        return error_response(code=400, message="'text' parameter too short.", callback=get_param(request, "callback"))

    type = get_param(request, "type")

    if type != None:
        type = type.lower()
        if not type in [
            "exact",
            "contains",
            "startswith",
            "endswith",
            "iexact",
            "icontains",
            "istartswith",
            "iendswith",
        ]:
            return error_response(
                code=400, message="Invalid 'type' parameter: " + repr(type), callback=get_param(request, "callback")
            )
    else:
        type = "istartswith"  # Default search type.

    # Perform the appropriate type of name-based search.

    args = {"name__" + str(type): text}
    if len(levels) > 0:
        args["level__in"] = levels

    query = Name.objects.filter(**args).order_by("level__level", "name")
    results = {}

    num_matches = query.count()
    results["numMatches"] = num_matches

    if num_matches <= 20:
        matches = []
        matched_locs = set()  # Used to only include each location once.

        for name in query:
            for loc_name in name.locationname_set.all():
                location = loc_name.location
                if location in matched_locs:
                    # Only include each location once.
                    continue

                matches.append(
                    {
                        "level": level_to_name(location.level),
                        "code": location.code,
                        "foundName": name.name,
                        "locationName": location.name,
                        "displayName": location.display_name,
                        "abbreviation": location.abbreviation,
                        "context": get_context(location),
                    }
                )

                matched_locs.add(location)

        results["locations"] = matches

    # Finally, return the results back to the caller.

    results = json.dumps(results)
    callback = get_param(request, "callback")
    if callback != None:
        results = callback + "(" + results + ")"  # Add JSONP callback.

    return HttpResponse(results, mimetype="application/json")
示例#2
0
文件: views.py 项目: 3taps/geo
def get(request):
    """ Implement the "get" API call.
    """
    locations = get_param(request, "locations")
    if locations == None:
        location = get_param(request, "location")
        if location == None:
            return error_response(code=400,
                                  message="Missing 'locations' or 'location' "
                                         +"parameter.",
                                  callback=get_param(request, "callback"))
        locations = [location]
        has_multi = False
    else:
        try:
            locations = json.loads(locations)
        except:
            return error_response(code=400,
                                  message="Invalid 'locations' parameter.",
                                  callback=get_param(request, "callback"))
        has_multi = True

    results = []
    for loc_code in locations:
        try:
            location = Location.objects.get(code=loc_code)
        except Location.DoesNotExist:
            return error_response(code=400,
                                  message="Missing or invalid location code",
                                  callback=get_param(request, "callback"))

        loc_data = {}
        loc_data['code']         = location.code
        loc_data['level']        = level_to_name(location.level)
        loc_data['name']         = location.name
        loc_data['displayName']  = location.display_name
        loc_data['abbreviation'] = location.abbreviation
        loc_data['minZoomLat']   = float(location.min_zoom_lat)
        loc_data['maxZoomLat']   = float(location.max_zoom_lat)
        loc_data['minZoomLong']  = float(location.min_zoom_long)
        loc_data['maxZoomLong']  = float(location.max_zoom_long)
        loc_data['context']      = get_context(location)

        if location.population != None:
            loc_data['population'] = location.population

        if location.area != None:
            loc_data['area'] = location.area

        if location.averageIncome != None:
            loc_data['averageIncome'] = int(location.averageIncome)

        results.append(loc_data)

    if has_multi:
        results = json.dumps({'locations' : results})
    else:
        results = json.dumps({'location' : results[0]})

    callback = get_param(request, "callback")
    if callback != None:
        results = callback + "(" + results + ")" # Add JSONP callback.

    return HttpResponse(results, mimetype="application/json")