django book 阅读笔记
一,django是一个十分优秀的python web的框架,那框架的是什么?
假设我们不使用框架来进行编写,我们要用如下的代码进行web脚本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #!/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编写后的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | # 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.(小技巧)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?