Front-end MVC design pattern

First, we divided into four Python files, (models.py, views.py, urls.py) and html template file (latest_books.html)

 

# models.py (the database tables)

from django.db import models

class Book(models.Model):

  name = models.CharField(max_length=50)

  pub_date = models.DateField()

 

# views.py (the business logic)

from django.shortcuts import render_to_response

from models import Book

def latest_books(request):

  book_list = Book.objects.order_by('-pub_date')[:10]

  return render_to_response('latest_books.html', {'book_list': book_list})

 

# urls.py (the URL configuration)

from django.conf.urls.defaults import *

import views

urlpatterns = patterns('',

  (r'^latest/$', views.latest_books),

)

 

# latest_books.html (the template)

<html><head><title>Books</title></head>

  <body>

  <h1>Books</h1>

    <ul>{% for book in book_list %}

      <li>{{ book.name }}

           </li>{% endfor %}

    </ul>

  </body>

</html>

 

 

Then, do not care about syntax details; just feel the intentions of the overall design. Here only concerned a few divided files:

  • models.py a Python class file is mainly used to describe the data table. Called model (model). Using this class, you can create a simple Python code, retrieve, update, delete records in the database without having to write a SQL statement and a.
  • views.py file contains the business logic of the page. latest_books () function is called a view.
  • urls.py pointed out what kind of URL called View. In this example, / latest / URL will invoke latest_books () function. In other words, if your domain name is example.com, anyone visit the website http://example.com/latest/ will call latest_books () function.
  • latest_books.html is html template that describes the design of the page is how. The template language with basic logic statements, such as {% for book in book_list%}

Combined, these portions loose follow the pattern known as Model - View - Controller (MVC). Simply put, the MVC is a method of software development, the method (model) and the request logic which define the code and data access (controller) as well as user interface (view) separately.

This design pattern key advantage is that the various components are loosely coupled. In this way, each consisting of Django-driven Web applications have a clear purpose, and can be changed independently without affecting the other parts. For example, an application developer to change the URL to achieve this without affecting the underlying program. Designers can change the style of the HTML page without touching Python code. Database administrators can rename the data table and only need to change a place, without having to find and replace from a lot of files.

Guess you like

Origin www.cnblogs.com/hello-bug/p/11031924.html