Web前端之路进击的Python程序员

从3000行缩减到1000行,用django类代替视图函数

2018-10-23  本文已影响97人  zhaoolee

项目完成后, 我迫不及待的进行了项目优化

第一步: 改写路由映射, 通过路由, 把 语言参数传进去

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^zh-cn/index$', views.zh_cn_index, name="zh_cn_index"),
    url(r'^zh-hk/index$', views.zh_hk_index, name="zh_hk_index"),
    url(r'^en/index$', views.en_index, name="en_index")
]
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^zh-cn/index$', views.Index.as_view(lang = "zh-cn"), name="zh_cn_index"),
    url(r'^zh-hk/index$', views.Index.as_view(lang = "zh-hk"), name="zh_hk_index"),
    url(r'^en/index$', views.Index.as_view(lang = "en"), name="en_index")
]

第二步: 将多个类似的函数转换为单个类

from django.shortcuts import render

# 中文版
def zh_cn_index(request):
    return render(request, 'pc/cn/index.html', locals())
# 繁体版
def zh_hk_index(request):
    return render(request, 'pc/hk/index_hk_amp.html', locals())
# 英文版
def en_index(request):
    return render(request, 'pc/en/index_en_amp.html', locals())
from django.shortcuts import render
from django.views.generic import ListView

class Index(ListView):
    lang = ""
    def get(self, request):
        lang = self.lang
        if (lang == "zh-cn"):
            return render(request, 'pc/cn/index.html', locals())
        if (lang == "zh-hk"):
            return render(request, 'pc/hk/index_hk.html', locals())
        if (lang == "en"):
            return render(request, 'pc/en/index_en.html', locals())

用类取代三个重复的函数, 好处有以下三点



小结:

上一篇 下一篇

猜你喜欢

热点阅读