思考

django是一个十分优秀的python web的框架,那框架的是什么?

假设我们不使用框架来进行编写,我们要用如下的代码进行web脚本:

#!/usr/bin/env python

import MySQLdb

print "Content-Type: text/html\n"
print "Books"
print ""
print "```
<h1>Books</h1>
"
print 
connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db')
cursor = connection.cursor()
cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10")
for row in cursor.fetchall():
    print "<li>%s</li></ul></ul>" % row[0]

connection.close()

那我们如果有很多的页面 ,那针对于各种网页来都要编写不同的脚本。这还仅仅是展示的工作,不包括更为复杂的业务逻辑处理。更包含下列的一些问题

  • html页面和代码层混杂,不利于维护
  • 每次都要打开connection,复杂
  • 针对不同的页面都要重复编写这些复杂的代码,代码没有很好的利用。

web框架的出现,就是为了解决以上的问题:编写简单高复用的代码,让你只关注你的角色部分的内容。

MVC的模式

以前在.net 的WEB框架中,有非常经典的MVC的设计模式,Model,View,Controller,每个层都只负责自己应该做的事情。而django的MVC模式包含下列文件:

models.py

urls.py

views.py

以及模版文件template.html

采用django编写后的代码:

    # 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)Books
    
    ```
    <h1>Books</h1>
    <ul>
    <ul>
    {% for book in book_list %}
        <li>{{ book.name }}</li>
    </ul>
    </ul>
    {% endfor %} 
  • models.py 负责数据的交互
  • views.py 业务处理,返回数据
  • urls.py 控制层,映射方法

层与层之间采用松散耦合的原则,views.py中的视图方法,至少采用一个参数:request