标签:
#!/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()
# 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_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>
标签:
原文地址:http://blog.csdn.net/p106786860/article/details/50937967