首页 > 解决方案 > Python、django:我编写了一些代码,但我认为执行起来需要时间。蟒蛇慢吗?还是我的代码慢?

问题描述

我想检查和改进我写的代码,因为这需要时间……慢

也许我可以写得更好...

这是views.py中的代码

def price_detail(request):
    if request.method == "POST":
        flight_date = request.POST.get('flight_date')
        direction = request.POST.get('direction')
        suburb = request.POST.get('suburb')
        no_of_passenger = request.POST.get('no_of_passenger')

        def price_cal():
            if direction == 'Drop off To airport':
                return int(suburbs.get(suburb)) + ((int(no_of_passenger) * 10) - 10)
            else:
                return int(suburbs.get(suburb)) + (int(no_of_passenger) * 10)

        price_cal()
        price = str(price_cal())
        p = Post(flight_date=flight_date, direction=direction, suburb=suburb,
                 no_of_passenger=no_of_passenger, fare=price)
        p.save()

        data = {
            'flight_date': flight_date,
            'direction': direction,
            'suburb': suburb,
            'no_of_passenger': no_of_passenger,
            'price': price,

        }

        message = '''
                Flight date: {}
                Direction: {}        
                Suburb: {}
                No of passenger: {}
                Price: {}
                
                '''.format(data['flight_date'], data['direction'],
                           data['suburb'], data['no_of_passenger'], data['price'])
        send_mail(data['flight_date'], message, '', ['sungkam3@gmail.com'])

        return render(request, 'basecamp/price_detail.html',
                      {'flight_date': flight_date, 'direction': direction, 'suburb': suburb,
                       'no_of_passenger': no_of_passenger, 'price': price},
                      )

    else:
        return render(request, 'basecamp/price_detail.html', {})

用户将一些信息放在 html 上并查询价格...视图从模板中获取对象,计算出价格,然后将所有信息保存到数据库中,并将用户查询的详细信息通过电子邮件发送给我。完成所有这些操作后,views.py 将信息发送到其他页面(html)以向用户显示结果。

它工作正常......但问题只是时间......太慢了

是因为 Python 还是我的代码?

标签: pythondjango

解决方案


您的代码很好,问题在于发送电子邮件,发送电子邮件可能需要很多时间。

所以你可以重构你的代码以在不同的线程中发送电子邮件,或者你甚至可以使用 celery。


推荐阅读