1.了解Web基本的开发
使用Python开发Web,最简单,原始和直接的办法是使用CGI标准现在从应用角度解释它是如何工作: 首先做一个Python脚本,输出HTML代码,然后保存成.cgi扩展名的文件,通过浏览器访问此文件。
以下用mongo连接数据库
import pymongo
print("Content-Type: text/html\n")
print("<html><head><title>Books</title></head>")
print("<body>")
print("<h1>Books</h1>")
print("<ul>") client=pymongo.MongoClient("127.0.0.1",port=27017) db=client.book collection=db.text cursor=collection.find() for row in cursor: print ("<li>%s</li>" % row['book']) print("</ul>") print("</body></html>") client.close()
打印出内容如下
Content-Type: text/html
<html><head><title>Books</title></head>
<body>
<h1>Books</h1>
<ul>
<li>book1</li>
<li>book2</li>
</ul>
这就是一个cgi,上传到服务器,然后通过浏览器访问此文件。
2.MVC 设计模式
模型-视图-控制器(MVC)
下面就是通过使用Django来完成以上功能的例子: 首先,我们分成4个Python的文件,(models.py ,views.py , urls.py ) 和html模板文件 (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>
-
models.py 文件主要用一个 Python 类来描述数据表。 称为 模型(model) 。 运用这个类,你可以通过简单的 Python 的代码来创建、检索、更新、删除 数据库中的记录而无需写一条又一条的SQL语句。
-
views.py文件包含了页面的业务逻辑。 latest_books()函数叫做视图。
-
urls.py 指出了什么样的 URL 调用什么的视图。 在这个例子中 /latest/ URL 将会调用 latest_books()这个函数。 换句话说,如果你的域名是example.com,任何人浏览网址http://example.com/latest/将会调用latest_books()这个函数。
-
latest_books.html 是 html 模板,它描述了这个页面的设计是如何的。 使用带基本逻辑声明的模板语言,如{% for book in book_list %}
MVC 是一种软件开发的方法,它把代码的定义和数据访问的方法(模型)与请求逻辑 (控制器)还有用户接口(视图)分开来完成,这让程序员不用反复的做一些底层的东西,能有效提高写代码的效率,也提供了模型各个块中的的独立性,修改了一个地方无须把整个架构都修改。
文章由djangobook2整理而成