- 虚拟环境
- django安装
- 路由
- 路由原理
虚拟环境
不同的项目可能依赖不同版本的包,因此通过虚拟环境进行不同环境的隔离。
pip3 install virtualenv
安装虚拟环境。
virtualenv mysite
创建一个虚拟环境,执行source bin/activate
切换到虚拟环境。
django安装
pip3 install django=1.8.13
安装指定版本的django
pip3 install django
安装最新版本的django
django使用
django-admin startproject myweb
创建django项目。manage.py myweb
默认会有这两个文件。
python manage.py runserver
启动项目,如下
项目默认带一些功能,需要创建数据表python manage.py migrate
自定义路由
新建一个页面。vi myweb/greet.py
内容如下。
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello world")
创建好页面之后,需要进行配置vi myweb/urls.py
from django.conf.urls import include, url
from django.contrib import admin
from myweb.greet import hello # 添加这一行
urlpatterns = [
url(r'^$', hello), # 根页面
url(r'^admin/', include(admin.site.urls)),
url(r'^hello/$', hello),# 添加这一行
]
再次重启python manage.py runserver
就可以通过localhost:8000/hello
访问刚才的页面。
路由原理
在我们执行python manage.py runserver
的时候,查看manage.py
可以找到os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myweb.settings")。
而myweb/settings.py
中有一个ROOT_URLCONF = 'myweb.urls'
对应我们之前修改的URL配置文件。通过这个配置文件,python可以找到不同的请求对应的处理函数。
显示时间
修改视图页面。
from django.http import HttpResponse
import datetime
def hello(request):
return HttpResponse("Hello world")
def time(request):
now = datetime.datetime.now()
html = f"现在是{now}"
return HttpResponse(html)
修改路由配置
from django.conf.urls import include, url
from django.contrib import admin
from myweb.greet import hello,time
urlpatterns = [
url(r'^$', hello),
url(r'^admin/', include(admin.site.urls)),
url(r'^hello/$', hello),
url(r'^time/', time),
]
此时重启python manage.py runserver
,然后访问localhost:time
可以查看到当前的时间。注意,时间确实可以实时更新,但是不准,因为默认是UTC时间。
TIME_ZONE = 'UTC'
改成
# TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Shanghai'
改完之后,重启服务器就可以查看北京时间。
动态路由
比如/hello/xiaoming
和/hello/xiaozhang
,我们可以使用同一个页面,URL匹配使用模糊匹配。
修改视图
from django.http import HttpResponse, Http404 # 这里多引入了一个Http404
import datetime
def hello(request):
return HttpResponse("Hello world")
def time(request):
now = datetime.datetime.now()
html = f"现在是{now}"
return HttpResponse(html)
def time_after(request, offset):
try:
offset = int(offset)
except ValueError:
raise Http404() # 这里抛出异常
now = datetime.datetime.now()
later = now + datetime.timedelta(hours=offset)
html = f"现在时间是{now} <br>{offset}小时候后时间是{later}"
return HttpResponse(html)
修改配置
from django.conf.urls import include, url
from django.contrib import admin
from myweb.greet import hello,time,time_after # 多一个time_after
urlpatterns = [
url(r'^$', hello),
url(r'^admin/', include(admin.site.urls)),
url(r'^hello/$', hello),
url(r'^time/$', time),
url(r'^time/(\d{1,2})/$', time_after), # \d{1,2}表示1位或者2位数字
]
此时访问localhost:8000/time/12
和localhost:8000/time/10
可以查看不同的效果。