Django:介绍Django

来源:互联网 发布:外星人源码站 编辑:程序博客网 时间:2024/05/16 01:23
一、介绍Django
     1.Diango一个高效的web框架,以最小代码构建和维护高质量web应用;
     2.减少重复代码,专注于Web应用上关键的东西;
二、框架是什么
     1.不使用框架设计Python网页应用程序,原始直接的办法是使用CGI标准;
     2.首先做一个Python脚本,输出HTML代码,保存成.cgi扩展名的文件,通过浏览器访问此文件;  
#!/usr/bin/env pythonimport MySQLdbprint "Content‐Type: text/html\n"print "<html><head><title>Books</title></head>"print "<body>"print "<h1>Books</h1>"print "<ul>"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>" % row[0]print "</ul>"print "</body></html>"connection.close()
三、MVC设计模式
     1.使用Django来完成以上功能的例子(4个Python文件models.py,views.py,urls.py和htmo模板文件(latest_books.html):
          models.py:主要用一个Python类来描述表,成为模型(model)。运用这个类可以通过简单的Python代码来创建、检索、删除数据库中的记录,而无需一条又一条的执行SQL语句;        
# models.py (the database tables)from django.db import models     class Book(models.Model):     name = models.CharField(max_length=50)     pub_date = models.DateField()     view.py:包含了页面的业务逻辑,latest_books()函数叫做视图;   # views.py (the business logic)from django.shortcuts import render_to_responsefrom 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:指出了什么样的URL调用什么视图,这个例子/latest/URL将会调用latest_books()这个函数。如果你的域名是example.com,任何人浏览网址http://example.com/latest将会调用latest_books()这个函数;   
# urls.py (the URL configuration)from django.conf.urls.defaults import *import views    urlpatterns = patterns('',(r'^latest/$', views.latest_books),)
          latest_books.html:是html模板,描绘了这个页面的设计是如何的;  
# 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>
    2.MVC是一种软件开发的方法,它把代码的定义和数据访问的方法(模型)与请求逻辑(控制器)还有用户接口(视图)分开;
    3.MVC的优势在于各种组件都是松散组合的,每个由Django驱动的Web应用都有明确的目的,可独立更改而不影响其它部分。例如,开发者更改一个应用程序的URL而不用影响到这个程序底层的实现等;
三、Django历史
     1.2003年秋天,堪萨斯州Lawrence城的一个网络开发小组编写,Lawrence Joumal-World报纸的程序员使用Python来编写;
     2.2005年夏天,框架开发完成,用来制作很多个World Online的站点。决定把这个框架发布为一个开源软件;
2 0
原创粉丝点击