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请求‘)
?
?
?静态文件读取
项目中创建static文件夹(imgs/css/js)
配置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
?
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‘),
?
]
?
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>
?
原文:https://www.cnblogs.com/Py-king/p/10587064.html