创建应用

1.创建应用

  1. python manage.py startapp hello

2.安装应用

  1. INSTALLED_APPS = [
  2. 'django.contrib.admin',
  3. 'django.contrib.auth',
  4. 'django.contrib.contenttypes',
  5. 'django.contrib.sessions',
  6. 'django.contrib.messages',
  7. 'django.contrib.staticfiles',
  8. 'hello',
  9. ]

路由

1.什么是路由

当客户端(例如Web浏览器)把请求发送给Web服务器,Web服务器再把请求发送给Flask程序实例。程序实例需要知道对每个URL请求运行哪些代码,所以保存了一个URL到Python函数的映射关系。处理URL和函数之间关系的程序称为路由。

image.png

URL配置规则


常用的配置函数

path()函数
re_path()函数
include()函数

指定参数类型

  1. path('hello/news/<int:month>',views.news,name='news_list')

正则表达式类型

  1. re_path(r'^news/(?P<month>0?[1-9]|1[012])/$',views.news_list)

说明如下:

  1. ^ 开始
  2. $ 结束
  3. | 选择
  4. [1-9] 1-9的任意字符
  5. [012] 0,1,2三个字符
  6. 0?表示0可有可无
  7. ?P参数名称

使用include引入

  1. path('hello/',include('hello.urls')),

hello/urls.py文件

  1. from hello import views
  2. app_name = 'hello'
  3. urlpatterns = [
  4. path('index',views.index,name='index'),
  5. ]

视图函数

hello/urls.py文件

  1. from hello import views
  2. app_name = 'hello'
  3. urlpatterns = [
  4. path('index',views.index,name='index'),
  5. path('json',views.json_response,name='json_response'),
  6. path('image',views.image_response,name='image_response'),
  7. path('html',views.html_response),
  8. path('html2',views.HtmlTemplate.as_view()),
  9. ]

views.py文件

  1. from django.http import HttpResponse, JsonResponse, FileResponse, HttpResponseRedirect
  2. from django.shortcuts import render
  3. # Create your views here.
  4. from django.views.generic import TemplateView
  5. def index(request):
  6. resp = HttpResponse('index',status=201)
  7. resp.status_code = 400
  8. resp['token'] = '123456'
  9. # return resp
  10. return HttpResponseRedirect('/hello/json')
  11. def json_response(request):
  12. info = {
  13. 'name':'andy',
  14. 'age': 18,
  15. 'hobby': {
  16. '运动': '篮球',
  17. '影视': '综艺,电影'
  18. }
  19. }
  20. return JsonResponse(info)
  21. def image_response(request):
  22. import os
  23. file = os.path.join(os.path.dirname(__file__),'daxiong.png')
  24. data = open(file,'rb')
  25. return FileResponse(data)
  26. def html_response(request):
  27. return render(request,'index.html')