1. 程式人生 > >2019.03.24 視圖和靜態讀取

2019.03.24 視圖和靜態讀取

itl pos load data har pen rom rgs ati

基於函數的視圖(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 視圖和靜態讀取