Python Django 1:

Django:

Django is a prominent member of a new generation of Web frameworks.

Django is simply a collection of libraries written in the Python programming language. To develop
a site using Django, you write Python code that uses these libraries. Learning Django, then, is a matter of
learning how to program in Python and understanding how the Django libraries work.

Web application written using the Common Gateway
Interface (CGI) standard, a popular way to write Web applications circa 1998.

Example code:

#!/usr/bin/python
import MySQLdb

print "Content-Type: text/html"
print
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()


A Web framework provides a
programming infrastructure for your applications, so that you can focus on writing clean, maintainable code
without having to reinvent the wheel. In a nutshell, that’s what Django does.



# models.py (the database tables)
from django.db import models
class Book(models.Model):
name = models.CharField(maxlength=50)
pub_date = models.DateField()

###################################
The models.py file contains a description of the database table, as a Python class. This is called a
model. Using this class, you can create, retrieve, update, and delete records in your database using
simple Python code rather than writing repetitive SQL statements.




# 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})

###################################
The views.py file contains the business logic for the page, in the latest_books() function.
This function is called a view.


# urls.py (the URL configuration)
from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
(r'latest/$', views.latest_books),
)
###################################
The urls.py file specifies which view is called for a given URL pattern. In this case, the URL
/latest/ will be handled by the latest_books() function.

# 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 %}

###################################
The latest_books.html is an HTML template that describes the design of the page.


·

·

·








Comments

Popular posts from this blog

Opencv Python

OpenCv Python Image process: Image