论坛首页 编程语言技术论坛

我的第一个Python Web应用

浏览 21849 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (3) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-07-05  

 

本文实现的是通信录的Web应用,在Windows xp环境下开发。

 

1.从官方网站下载Python安装文件,安装后配置环境变量(系统变量path)。

         C:\Program Files\Python25;

         C:\Program Files\Python25\Scripts;

 

2.下载Django,解压。打开命令行,进入刚解压的目录,执行python setup.py install,然后把Django中bin目录的路径添加到环境变量path里面。

 

3.现在打开命令提示符,进入到想要创建应用的目录后键入django-admin.py startproject mysite命令,调用Django的控制台命令新建一个名为mysite的工程,与此同时Django还在新创建的mysite文件夹下生成以下四个分工不同的文件: __init__.py    manage.py    settings.py    urls.py

 

4.在命令提示符下进入工程目录,键入命令manage.py runserver,就可以启动Web服务器来测试新建立的工程。浏览器中输入http://127.0.0.1:8000/ 查看效果(Ctrl+C可停止服务器)。

 

5.在工程建立好之后,接下来就可以编写Django的应用模块。键入命令python manage.py startapp contacts ,命令会在当前工程下生成一个名为article的模块,目录下除了标识Python模块的__init__.py文件,还有额外的两个文件models.py和views.py。

 

6.在传统的Web的开发中,很大的一部分工作量被消耗在数据库中创建需要的数据表和设置表字段上,而Django为此提供了轻量级的解决方案。借助Django内部的对象关系映射机制,可以用Python语言实现对数据库表中的实体进行操作,实体模型的描述需要在文件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,结果不能插入中文

 

from django.contrib import admin #我没有导入这个,虽然能进入Django管理,但数据库表的管理却没有

 

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工程的命令提示符下执行manage.py syncdb指令。Django会根据模型的定义自动完成ORM的数据库映射工作,屏蔽了底层数据库细节和SQL查询的编写。输入yes,创建账户,电子邮件,密码。

 

10.次使用命令manage.py runserver来启动Django自带的Web服务器后,在浏览器中访问地址http://127.0.0.1:8000/admin/ ,使用刚才创建的superuser用户的账号和密码登陆

   发表时间:2011-07-11  
也支持下。国内玩python的人呈上升趋势啊
0 请登录后投票
   发表时间:2011-07-11  
这两天看了下Python语言,之前一直听到Python语言的好,稍稍了解了下,感觉是挺独特的,有印象的就是代码块按缩进区别,类的声明很像是赋值,还有就是实例方法第一个参数必须传递类自身
0 请登录后投票
   发表时间:2011-07-12  
Python 用什么写页面
0 请登录后投票
   发表时间:2011-07-12  
学习不止。。。
1 请登录后投票
   发表时间:2011-07-13  
加油哦。。。人生第一个应用很值得回忆的
0 请登录后投票
   发表时间:2011-07-14  
网易的游戏开发iTown也是python。也在学习中
0 请登录后投票
   发表时间:2011-07-17  
有没有完整的简单的python web项目代码学习?
0 请登录后投票
   发表时间:2011-07-25  
其实你可以试着了解下flask框架
绝对轻量级
可快速部署web
看你怎么定位PYTHON了,
如果拿他做快速响应需求的工具的话
试试flask 吧
0 请登录后投票
   发表时间:2011-08-04  
flask  和 django 有什么区别。
0 请登录后投票
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics