启动django开发服务器(一个内建的轻量级web服务器,开发服务器检测你的代码并自动加载,这样你会很容易修改代码而不用重启服务,该服务器不可用在正式环境,因为在同一时间,该服务器只能可靠的处理一次单个请求,并且没有进行任何类型的安全审计)
python manage.py runserver 0.0.0.0:8080 (这样可以和别人共享同一个开发站点)
python manage.py runserver (默认监听8000端口)
python manage.py runserver 8080(监听指定端口)
C:\Users\Administrator\PycharmProjects\mysite>python manage.py runserver 0.0.0.0:8080 Validating models... 0 errors found Django version 1.3.1, using settings 'mysite.settings' Development server is running at http://0.0.0.0:8080/ Quit the server with CTRL-BREAK.
调用python django-admin.py startproject mysite创建的项目结构如下:
__init__.py #让python把该目录当作一个开发包
manage.py #一种命令行工具,允许你以多种方式与该django项目进行交互
settings.py #该django项目的配置或设置
urls.py #url与视图函数的映射关系,即路由表
####################################################
视图函数如下:
# -*-coding:utf-8-*- from django.http import HttpResponse def hello(request): return HttpResponse('hello world')
urls.py中配置映射关系:
# -*-coding:utf-8-*- from django.conf.urls.defaults import patterns, include, url from views import hello # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', #我们把hello视图函数当作对象处理,而不是调用它,这是python的一个重要特性,函数是一级对象(first-class objects) url(r'^hello/$',hello) )
切记:代码中第一行编码# -*-coding:utf-8-*-不可以省略
映射关系中urlpatterns = patterns('',url(r'^hello/$',hello)),第一个空字符串可以被用来表示一个视图函数的通用前缀
第二个参数表示一个tuple映射关系, url采用正则表达式进行匹配,eg. r'^hello/$' 表示以hello开头且以/结尾的url
运行结果:
##########################视图函数#################################
# -*-coding:utf-8-*- from django.http import HttpResponse, Http404 import datetime def hello(request): return HttpResponse('hello world') def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s</body></html>" % now return HttpResponse(html) def time(request, offset): try: offset = int(offset) except ValueError as e: raise Http404() dt = datetime.datetime.now() + datetime.timedelta(hours=offset) html = html = "<html><body>It is now %s</body></html>" % dt return HttpResponse(html)
#########################url映射#######################
# -*-coding:utf-8-*- from django.conf.urls.defaults import patterns, include, url from views import hello, current_datetime # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', #我们把hello视图函数当作对象处理,而不是调用它,这是python的一个重要特性,函数是一级对象(first-class objects) url(r'^hello/$',hello), url(r'^currentdate/$',current_datetime), url(r'time/\d{1,2}/$',current_datetime), # 正则表达式利用括号从文本中提取数据,传入到视图函数 url(r'time/(\d{1,2})/$',current_datetime) )