Django Views: Dynamic Content

  • views.py
from django.http import HttpResponse
import datetime

def root(request):
    return HttpResponse("Hi, I'm root.")

def hello(request):
    return HttpResponse("Hello world!")

def current_datetime(request):
    now = datetime.datetime.now()
    html = '<html><body>It is now %s.</body></html>' % now
    return HttpResponse(html)

def hours_ahead(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    html = '<html><body>In %s hour(s), it will be %s.</body></html>' % (offset, dt)
    return HttpResponse(html)
  • urls.py
from django.conf.urls import url

from mypro.views import hello, root, current_datetime, hours_ahead

urlpatterns = [
        url(r'^$', root),
        url(r'^hello/$', hello),
        url(r'^time/$', current_datetime),
        url(r'^time/plus/(\d{1,2})/$', hours_ahead),
]
  • result
time
time_plus
  • loose Coupling
 loose coupling is a software-development approach that values the importance 
of making pieces interchangeable. If two pieces of code are loosely coupled, 
then changes made to one of the pieces will have little or no effect on the 
other.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容