django book 阅读笔记
2015-10-19 23:35
465 查看
一,django是一个十分优秀的python web的框架,那框架的是什么?
假设我们不使用框架来进行编写,我们要用如下的代码进行web脚本:
那我们如果有很多的页面 ,那针对于各种网页来都要编写不同的脚本。这还仅仅是展示的工作,不包括更为复杂的业务逻辑处理。更包含下列的一些问题
1.html页面和代码层混杂,不利于维护
2.每次都要打开connection,复杂
3.针对不同的页面都要重复编写这些复杂的代码,代码没有很好的利用。
web框架的出现,就是为了解决以上的问题:编写简单高复用的代码,让你只关注你的角色部分的内容。
二,MVC的模式
以前在.net 的WEB框架中,有非常经典的MVC的设计模式,Model,View,Controller,每个层都只负责自己应该做的事情。而django的MVC模式包含下列文件:
models.py
urls.py
views.py
以及模版文件template.html
采用django编写后的代码:
models.py 负责数据的交互
views.py 业务处理,返回数据
urls.py 控制层,映射方法
层与层之间采用松散耦合的原则,views.py中的视图方法,至少采用一个参数:request.(小技巧)
假设我们不使用框架来进行编写,我们要用如下的代码进行web脚本:
#!/usr/bin/env python import MySQLdb print "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()
那我们如果有很多的页面 ,那针对于各种网页来都要编写不同的脚本。这还仅仅是展示的工作,不包括更为复杂的业务逻辑处理。更包含下列的一些问题
1.html页面和代码层混杂,不利于维护
2.每次都要打开connection,复杂
3.针对不同的页面都要重复编写这些复杂的代码,代码没有很好的利用。
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) <html><head><title>Books</title></head> <body> <h1>Books</h1> <ul> {% for book in book_list %} <li>{{ book.name }}</li> {% endfor %} </ul> </body></html>
models.py 负责数据的交互
views.py 业务处理,返回数据
urls.py 控制层,映射方法
层与层之间采用松散耦合的原则,views.py中的视图方法,至少采用一个参数:request.(小技巧)
相关文章推荐
- [Django模板系统]用render_to_response()简化views层
- [Django模板系统]在视图中使用模板
- 一个设计师眼中的Google: 宇宙里最值钱的一个偶然
- golang.org 不能访问
- 分治-二叉树重建
- 区间DP-矩阵连乘问题
- LabyrinthAlgorithm
- Google Guava Collections 使用介绍
- Mongo基本操作和命令
- django 使用记录 mac
- django自定义上传文件路径
- Google APAC 2016 University Graduates Test Round C解题报告
- 国内 google depot_tools gclient SSLError hostname 错误解决
- Codeforces 588 A. Duff and Meat
- Django学习笔记(一)
- go git 安装配置与使用 (windows 7 64bit)
- django 画图
- 让Category支持添加属性与成员变量【转载】
- Codeforces 574 A. Bear and Elections
- 寻找中位数