山のピークのためのスクレイピング気象条件
Aug 20 2020
複雑なアプリを初めて作成しようとしたウェブサイトをDjangoに構築しました。山頂の17の気象条件をスクレイプするアプリです。詳細な天気予報を別のテンプレートで表示したかったので、ほぼ同じように見える17のビューがあります。
4ビューのみ:
class KasprowyWierchForecastView(TemplateView):
"""
class for rendering view of detailed weather forecast for
Kasprowy Wierch peak
"""
template_name = 'mountain_base.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Peak'] = PeakForecast.objects.filter(
name_of_peak='Kasprowy').order_by('date')
print(context['Peak'])
return context
class KoscielecForecastView(TemplateView):
"""
class for rendering view of detailed weather forecast for
Koscielec peak
"""
template_name = 'mountain_base.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Peak'] = PeakForecast.objects.filter(
name_of_peak='Koscielec').order_by('date')
return context
class KrivanForecastView(TemplateView):
"""
class for rendering view of detailed weather forecast for Krivan peak
"""
template_name = 'mountain_base.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Peak'] = PeakForecast.objects.filter(
name_of_peak='Krivan').order_by('date')
return context
class MieguszowieckiForecastView(TemplateView):
"""
class for rendering view of detailed weather forecast for
Mieguszowiecki peak
"""
template_name = 'mountain_base.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Peak'] = PeakForecast.objects.filter(
name_of_peak='Mieguszowiecki').order_by('date')
return context
class MnichForecastView(TemplateView):
"""
class for rendering view of detailed weather forecast for
Mnich peak
"""
template_name = 'mountain_base.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Peak'] = PeakForecast.objects.filter(
name_of_peak='Mnich').order_by('date')
return context
ビュークラスの名前のみとcontext['Peak']
は異なります。残りのコードは冗長です。私の経験は自己学習プロセスのみに基づいているため、修正またはリファクタリングの方法に関する優れた解決策は見つかりませんでした。
回答
2 fabrizzio_gz Aug 20 2020 at 09:34
1つのオプションはTemplateView
、インスタンス属性としてピークの名前を含めるようにクラスを変更し(たとえばpeak_name
)、get_context_data
メソッドにそれを利用させることです。
class TemplateView():
# Class attributes
def __init__(self, peak_name):
# Instance attributes
# ...
self.peak_name = peak_name
# Class methods
# Modification of the get_context_data method
def get_context_data(self, **kwargs):
context['Peak'] = PeakForecast.objects.filter(
name_of_peak=self.peak_name).order_by('date') #<- Modification here
print(context['Peak'])
return context
そして、そのクラスのインスタンスとしてピークビューを生成できます。
krivan_view = TemplateView('Krivan')
krivan_view.get_context_data(arg1='arg1', arg2='arg2')