什么AWS服务可以帮助加速缓慢的Django视图函数

时间:2018-02-07 19:08:44

标签: django postgresql amazon-web-services amazon-ec2

我有一个带有Postgres数据库的Django应用程序,因为数据库有数百万条记录,所以它有点远离我的客户端。话虽如此,有一些视图函数可以进行多次数据库查询,因此,它的速度很慢。这是我的一个视图函数的示例它有点混乱,因为我正在玩寻找查询优化的东西,我的道歉。

def get_filters(request):
    try:
        post_data = request.body.decode("utf-8")
        post_data = json.loads(post_data)
    except Exception as e:
        logging.error('There was an issue getting filter post data')
        logging.error(e)

        return HttpResponse(
            json.dumps({'filters': {'makes': [], 'models': [], 'years': [], 'transmissions': [], 'fuel_types': []}}),
            content_type='application/json')

    dealer = post_data['dealer'] if 'dealer' in post_data else None
    make_ids = post_data['make_ids'] if 'make_ids' in post_data else []
    model_ids = post_data['model_ids'] if 'model_ids' in post_data else []
    years = post_data['years'] if 'years' in post_data else []
    condition = post_data['condition'] if 'condition' in post_data else None
    price_min = post_data['price_min'] if 'price_min' in post_data else 0
    price_max = post_data['price_max'] if 'price_max' in post_data else 10000000

    # Catch Critical Error Where There Is No Dealer
    if not dealer:
        logging.error('Unable to find a Dealer')
        return HttpResponse(
            json.dumps({'filters': {'makes': [], 'models': [], 'years': [], 'transmissions': [], 'fuel_types': []}}),
            content_type='application/json')
    else:
        try:
            dealer = Dealer.objects.get(id=dealer)
        except Exception as e:
            logging.error(e)
            return HttpResponse(
                json.dumps({'filters': {'makes': [], 'models': [], 'years': [], 'transmissions': [], 'fuel_types': []}}),
                content_type='application/json')


    current_year = datetime.datetime.now().year
    start_year = current_year - 30

    # First get the make filters
    vehicles = Vehicle.objects.filter(dealer=dealer)

    if years:
        vehicles = vehicles.filter(year__in=years)

    filtered_make_names = vehicles.values_list('vehicle_make__name', flat=True)
    filtered_makes = VehicleMake.objects.filter(name__in=filtered_make_names)

    makes_map = [{
            'name': make.name,
            'count': vehicles.filter(vehicle_make=make, dealer=dealer).count(),
            'id': make.id
        } for make in filtered_makes
    ]

    # Second get the model filters

    filtered_model_names = vehicles.values_list('vehicle_model__name', flat=True)
    filtered_models = VehicleMake.objects.filter(name__in=filtered_model_names)

    dealer_models = VehicleModel.objects.filter(
        name__in=filtered_models)

    new_dealer_models = VehicleModel.objects.filter(name__in=vehicles.values_list('vehicle_model__name', flat=True))


    if len(make_ids) > 0:
        dealer_models = dealer_models.filter(make__id__in=make_ids)

    # Get the actual filters
    year_map = [{
        'year': yr,
        'count': Vehicle.objects.filter(year=yr, dealer=dealer).count()
    } for yr in range(start_year, current_year) if Vehicle.objects.filter(year=yr, dealer=dealer).count() > 0][::-1]

    models_map = [{
        'name': model.name,
        'count': Vehicle.objects.filter(vehicle_model=model, dealer=dealer).count(),
        'id': model.id
    } for model in dealer_models]

    filter_map = {
        "makes": makes_map,
        "models": models_map,
        "years": year_map,
        "transmissions": [],
        "fuel_types": []
    }

    return HttpResponse(json.dumps({'filters': filter_map}), content_type='application/json')

我想启动AWS EC2实例,并将我的代码从我现在的服务器迁移到那里,并想知道我可以与哪些AWS服务一起使用以使这些视图功能更快,为什么?自动缩放是否有助于此,或者当CPU达到某一点时,自动缩放是否会启动?

1 个答案:

答案 0 :(得分:3)

您需要弄清楚瓶颈是在您的数据库层还是在您的网络层中。

如果瓶颈是数据库层,那么它自己的服务器上的更大的数据库实例或引入缓存层(例如memcache或redis )可能是适当的(django有这两个插件)

如果瓶颈是您的网站,而不是负载均衡器的组合,运行您网站的多个ec2实例以及自动缩放组可能是合适的。

但首先,你真的需要弄清楚瓶颈在哪里,这样你就不会花时间和金钱来优化错误的东西。