首页 > 其他 > 详细

2019.03.24 视图和静态读取

时间:2019-03-24 10:53:07      阅读:118      评论:0      收藏:0      [点我收藏+]

基于函数的视图(FBV)function base views

使用方法

配置URL

from django.conf.urls import url
from django.contrib import admin
import views
urlpatterns = [
  url(r‘^admin/‘, admin.site.urls),
  url(r‘^$‘, views.IndexView.as_view()),
]
?
?

创建视图


#coding=utf-8
from django.http import HttpResponse
from django.views import View
?
class IndexView(View):
  def get(self,request,*args,**kwargs):
      return HttpResponse(‘Get请求‘)
?
?
  def post(self,request,*args,**kwargs):
      return HttpResponse(‘Post请求‘)
?
?
?静态文件读取

底层实现

  1. 项目中创建static文件夹(imgs/css/js)

  2. 配置URL

  3. 创建视图

配置URL

from django.conf.urls import url
from django.contrib import admin
import views
urlpatterns = [
  url(r‘^admin/‘, admin.site.urls),
  url(r‘^hello/.*$‘, views.ReadImg.as_view()),
]
?
?

创建视图


#coding=utf-8
from django.http import HttpResponse, Http404, FileResponse
from django.views import View
import jsonpickle
?
class ReadImg(View):
  def get(self,request,*args,**kwargs):
      import re
      filepath = request.path
      m = re.match(r‘^/hello/(.*)$‘,filepath)
      path = m.group(1)
?
      import os
      filedirs = os.path.join(os.getcwd(),‘static/imgs‘,path)
      print filedirs
      if not os.path.exists(filedirs):
          raise Http404()
?
      response = FileResponse(open(filedirs,‘rb‘),content_type=‘image/png‘)
      return response
?

 

Django读取静态文件方式

  • settings.py文件中设置

STATIC_URL = ‘/static/‘
?
STATICFILES_DIRS = [
  os.path.join(BASE_DIR,‘static/imgs‘),
  os.path.join(BASE_DIR,‘static/css‘),
  os.path.join(BASE_DIR,‘static/js‘),
?
]
?

 

配置URL


from django.conf.urls import url
from django.contrib import admin
import views
urlpatterns = [
  url(r‘^admin/‘, admin.site.urls),
  url(r‘^index.html$‘,views.index_view)
]
?

创建视图


def index_view(request):
  return render(request,‘index.html‘)
?

创建模板


{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
?
  <img src="{% static ‘1.png‘ %}"/>
?
</body>
</html>
?

 

 

 

2019.03.24 视图和静态读取

原文:https://www.cnblogs.com/Py-king/p/10587064.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!