创建应用
1.创建应用
python manage.py startapp hello
2.安装应用
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hello',
]
路由
1.什么是路由
当客户端(例如Web浏览器)把请求发送给Web服务器,Web服务器再把请求发送给Flask程序实例。程序实例需要知道对每个URL请求运行哪些代码,所以保存了一个URL到Python函数的映射关系。处理URL和函数之间关系的程序称为路由。
URL配置规则
常用的配置函数
path()函数
re_path()函数
include()函数
指定参数类型
path('hello/news/<int:month>',views.news,name='news_list')
正则表达式类型
re_path(r'^news/(?P<month>0?[1-9]|1[012])/$',views.news_list)
说明如下:
^ 开始
$ 结束
| 选择
[1-9] 1-9的任意字符
[012] 0,1,2三个字符
0?表示0可有可无
?P参数名称
使用include引入
path('hello/',include('hello.urls')),
hello/urls.py文件
from hello import views
app_name = 'hello'
urlpatterns = [
path('index',views.index,name='index'),
]
视图函数
hello/urls.py文件
from hello import views
app_name = 'hello'
urlpatterns = [
path('index',views.index,name='index'),
path('json',views.json_response,name='json_response'),
path('image',views.image_response,name='image_response'),
path('html',views.html_response),
path('html2',views.HtmlTemplate.as_view()),
]
views.py文件
from django.http import HttpResponse, JsonResponse, FileResponse, HttpResponseRedirect
from django.shortcuts import render
# Create your views here.
from django.views.generic import TemplateView
def index(request):
resp = HttpResponse('index',status=201)
resp.status_code = 400
resp['token'] = '123456'
# return resp
return HttpResponseRedirect('/hello/json')
def json_response(request):
info = {
'name':'andy',
'age': 18,
'hobby': {
'运动': '篮球',
'影视': '综艺,电影'
}
}
return JsonResponse(info)
def image_response(request):
import os
file = os.path.join(os.path.dirname(__file__),'daxiong.png')
data = open(file,'rb')
return FileResponse(data)
def html_response(request):
return render(request,'index.html')