python实现第一个web_我的第一个Python Web应用
本文實(shí)現(xiàn)的是通信錄的Web應(yīng)用,在Windows xp環(huán)境下開發(fā)。
1.從官方網(wǎng)站下載Python安裝文件,安裝后配置環(huán)境變量(系統(tǒng)變量path)。
C:\Program Files\Python25;
C:\Program Files\Python25\Scripts;
2.下載Django,解壓。打開命令行,進(jìn)入剛解壓的目錄,執(zhí)行python setup.py install,然后把Django中bin目錄的路徑添加到環(huán)境變量path里面。
3.現(xiàn)在打開命令提示符,進(jìn)入到想要?jiǎng)?chuàng)建應(yīng)用的目錄后鍵入django-admin.py startproject mysite命令,調(diào)用Django的控制臺(tái)命令新建一個(gè)名為mysite的工程,與此同時(shí)Django還在新創(chuàng)建的mysite文件夾下生成以下四個(gè)分工不同的文件: __init__.py? ? manage.py??? settings.py ?? urls.py
。
4.在命令提示符下進(jìn)入工程目錄,鍵入命令manage.py runserver,就可以啟動(dòng)Web服務(wù)器來測試新建立的工程。瀏覽器中輸入http://127.0.0.1:8000/ 查看效果(Ctrl+C可停止服務(wù)器)。
5.在工程建立好之后,接下來就可以編寫Django的應(yīng)用模塊。鍵入命令python manage.py startapp contacts ,命令會(huì)在當(dāng)前工程下生成一個(gè)名為article的模塊,目錄下除了標(biāo)識(shí)Python模塊的__init__.py文件,還有額外的兩個(gè)文件models.py和views.py。
6.在傳統(tǒng)的Web的開發(fā)中,很大的一部分工作量被消耗在數(shù)據(jù)庫中創(chuàng)建需要的數(shù)據(jù)表和設(shè)置表字段上,而Django為此提供了輕量級(jí)的解決方案。借助Django內(nèi)部的對(duì)象關(guān)系映射機(jī)制,可以用Python語言實(shí)現(xiàn)對(duì)數(shù)據(jù)庫表中的實(shí)體進(jìn)行操作,實(shí)體模型的描述需要在文件models.py中配置。
from django.db import models
from django.contrib import admin
class Area(models.Model):
areaname = models.CharField(max_length=20)
def __str__(self):
return self.areaname.encode('utf-8')
class Meta:
ordering = ['areaname']
class Admin:
pass
class Dept(models.Model):
deptname = models.CharField(max_length=20)
def __str__(self):
return self.deptname.encode('utf-8')
class Meta:
ordering = ['deptname']
class Admin:
pass
class Employee(models.Model):
employee_area = models.ForeignKey(Area)
employee_dept = models.ForeignKey(Dept)
name = models.CharField(max_length=20)
english_name = models.CharField(max_length=40)
tel = models.CharField(max_length=20)
cell_phone = models.CharField(max_length=20)
email = models.CharField(max_length=40)
def __str__(self):
return self.name.encode('utf-8')
class Meta:
ordering = ['employee_area', 'employee_dept', 'name']
class Admin:
pass
admin.site.register([Area,Dept,Employee])
return self.name.encode('utf-8') #開始我寫的return self.name,結(jié)果不能插入中文
from django.contrib import admin #我沒有導(dǎo)入這個(gè),雖然能進(jìn)入Django管理,但數(shù)據(jù)庫表的管理卻沒有
7.修改setting.py
# Django settings for firstproject project.
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
SITE_PATH = os.path.dirname(os.path.abspath(__file__)) #System Path
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'sqlite3',
# Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'F:/firstproject/contacts.db',
# Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'zh-CN'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '95*^$#d8s3z79x@6l$10)g=#_6*u7(j4bsx+m7djf$!+qw+8w0'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'firstproject.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
'firstproject.contacts',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
#My note display Chinese
FILE_CHARSET='gb18030'
DEFAULT_CHARSET='utf-8'
8.修改urls.py
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^firstproject/', include('firstproject.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
)
9.在News工程的命令提示符下執(zhí)行manage.py
syncdb指令。Django會(huì)根據(jù)模型的定義自動(dòng)完成ORM的數(shù)據(jù)庫映射工作,屏蔽了底層數(shù)據(jù)庫細(xì)節(jié)和SQL查詢的編寫。輸入yes,創(chuàng)建賬戶,電子郵件,密碼。
10.次使用命令manage.py runserver來啟動(dòng)Django自帶的Web服務(wù)器后,在瀏覽器中訪問地址http://127.0.0.1:8000/admin/
,使用剛才創(chuàng)建的superuser用戶的賬號(hào)和密碼登陸
總結(jié)
以上是生活随笔為你收集整理的python实现第一个web_我的第一个Python Web应用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python format函数实例_py
- 下一篇: fastjson jar包_Fastjs