from django.http import HttpResponse
def my_view(request):
content = "Hello, world!" # 响应内容
response = HttpResponse(content, status=200, content_type="text/plain")
return response
content
:响应的内容,可以是字符串、字节流或可迭代对象。status
:响应的状态码,默认为 200(OK)。content_type
:响应的内容类型,默认为 “text/html”。from django.http import HttpResponse
def my_view(request):
content = "<html><body><h1>Hello, world!</h1></body></html>"
response = HttpResponse(content, content_type="text/html")
return response
from django.shortcuts import render
def my_view(request):
# 处理逻辑
return render(request, 'template_name.html', context)
from django.shortcuts import render
def index(request):
context = {'name': "bruce", 'age': 18}
return render(request, 'index.html', context)
<p>name: {{ name }}</p>
<p>age: {{ age }}</p>
from django.shortcuts import redirect
def index(request):
return HttpRespinse("index")
def my_view(request):
# 处理逻辑
return redirect('index')
ensure_ascii=False
user_dict = {user_dict = {"username": "秦始皇", "age": 100}
with open("01.json", "w", encoding="utf8") as fp:
json.dump(user_dict, fp=fp)
# {"username": "\u79e6\u59cb\u7687", "age": 100}
}
def index(request):
data = {'name': '秦始皇', 'age': 100}
return JsonResponse(data)
中文可能发生转移,那么接下来研究怎么取消转义
查看源码
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
json_dumps_params=None, **kwargs):
if safe and not isinstance(data, dict):
raise TypeError(
'In order to allow non-dict objects to be serialized set the '
'safe parameter to False.'
)
if json_dumps_params is None:
json_dumps_params = {}
kwargs.setdefault('content_type', 'application/json')
data = json.dumps(data, cls=encoder, **json_dumps_params)
super().__init__(content=data, **kwargs)
分析源码发现使用的还是jason
那么只要想办法把ensure_ascii传入即可
最终发现参数json_dumps_param可以将ensure_ascii=false传进去
所以修改语句
return JsonResponse(user_dict, json_dumps_params={'ensure_ascii': False})
def index(request):
user_list = [11, 212, 32]
return JsonResponse(user_list)
In order to allow non-dict objects to be serialized set the safe parameter to False.
def index(request):
user_list = [11, 212, 32]
return JsonResponse(user_list, safe=False)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
{% load static %}
<script src="{% static 'js/jquery-3.5.1.min.js' %}"></script>
<link rel="stylesheet" href="{% static 'bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
<script src="{% static 'bootstrap-3.4.1-dist/js/bootstrap.min.js' %}"></script>
</head>
<body>
<div class="container">
<div class="row">
<h1 class="text-center">注册界面</h1>
<div class="col-md-6 col-md-offset-3">
<form action="" method="post">
<p>用户名:<input class="form-control" type="text" name="username" placeholder="username"></p>
<p>密码:<input class="form-control" type="password" name="password" placeholder="password"></p>
<p>头像:<input type="file" name="head_jpg"></p>
<p><input type="submit" class="btn btn-block btn-success"></p>
</form>
</div>
</div>
</div>
</body>
</html>
def register(request):
if request.method == "POST":
data = request.POST
print(data)
username = data.get("username")
password = data.get("password")
head_image = data.get("head_image")
print(head_image, type(head_image))
return render(request, 'register.html')
<QueryDict: {'username': [''], 'password': [''], 'head_image': ['53efb9d8079c6e4f904ed602f5c1e4e.png']}>
53efb9d8079c6e4f904ed602f5c1e4e.png <class 'str'>
def register(request):
if request.method == "POST":
files_data = request.FILES
print(files_data)
head_image = files_data.get("head_image")
print(head_image, type(head_image))
return render(request, 'register.html')
<MultiValueDict: {}>
None <class 'NoneType'>
<form action="" method="post" enctype="multipart/form-data">
</form>
<MultiValueDict: {'head_image': [<InMemoryUploadedFile: 53efb9d8079c6e4f904ed602f5c1e4e.png (image/png)>]}>
53efb9d8079c6e4f904ed602f5c1e4e.png <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
获取文件名
获取文件数据
如果只是
with open(保存文件名, mode="wb") as fp:
fp.write(head_image)
将会报错
a bytes-like object is required, not 'InMemoryUploadedFile'
我们需要逐行读取,并且推荐保存文件写法如下
def register(request):
if request.method == "POST":
files_data = request.FILES
# print(files_data)
head_image = files_data.get("head_image")
# print(head_image, type(head_image))
head_image_name = head_image.name
print(head_image_name)
with open(head_image_name, mode="wb") as fp:
for line in head_image.chunks():
fp.write(line)
return render(request, 'register.html')
http://example.com/foo/bar/
/foo/bar/
request.path
来获取丢弃域名后的路径,而使用 request.path_info
来获取原始的、未解析的路径。这在某些情况下非常有用,例如当需要对URL进行一些自定义操作或路由处理时。http://example.com/foo/bar/?page=2
,
/foo/bar/?page=2
。from django.http import render
def login(request, *args, **kwargs):
if request.method = "POST":
# 处理post请求逻辑代码
return render(request, 'login.html')
# 处理get请求逻辑代码
return render(request, 'login.html')
from django.urls import path
from . import views
urlpatterns = [
path('login/', views.login, name='login'),
]
from django.http import render
from django.views import View
class Login(View):
def get(self, request, *args, **kwargs):
# 处理get请求逻辑代码
return render(request, 'login.html')
def post(self, request, *args, **kwargs):
# 处理post请求逻辑代码
return render(request, 'login.html')
from django.urls import path
from . import views
urlpatterns = [
path('login/', views.login.as_view(), name='login'),
]
class View:
# 定义支持的HTTP方法名
http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
# 类View的初始化方法
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
# 理解为类方法
@classonlymethod
def as_view(cls, **initkwargs):
# cls是我们自己创建的类
# as_view如果有参数对其进行检验方法名或者属性名书否冲突
# 如果有前面定义的HTTP列表中的键值那就抛出异常
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError(
'The method name %s is not accepted as a keyword argument '
'to %s().' % (key, cls.__name__)
)
# 检查传入的关键字参数是否为类的属性或方法,不是也会抛出异常
if not hasattr(cls, key):
raise TypeError("%s() received an invalid keyword %r. as_view "
"only accepts arguments that are already "
"attributes of the class." % (cls.__name__, key))
# 这是一个闭包函数,对外部的cls有引用
def view(request, *args, **kwargs):
# cls是自己创建的类,实例化了一个对象self
self = cls(**initkwargs)
# 调用setup方法进行
self.setup(request, *args, **kwargs)
# 检查对象是否有request,没有会报错
if not hasattr(self, 'request'):
raise AttributeError(
"%s instance has no 'request' attribute. Did you override "
"setup() and forget to call super()?" % cls.__name__
)
return self.dispatch(request, *args, **kwargs)
# 对View类的一些属性修改
view.view_class = cls
view.view_initkwargs = initkwargs
update_wrapper(view, cls, updated=())
update_wrapper(view, cls.dispatch, assigned=())
# 返回闭包函数的地址
return view
# 初始化类试图的属性
def setup(self, request, *args, **kwargs):
# 如果定义了类方法且没有定义head方法,那么将head方法复制为get方法
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs
# 检查对象实例此时的method是不是HTTP支持的方法名
def dispatch(self, request, *args, **kwargs):
# 因为method获取的方法名是大写的,所以需要转换为小去列表中比较
# 支持的方法名,就将方法取出复制给handler
# 不支持就触发第三个参数这是HTTP不支持的请求
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
# 返回警告内容为405状态码和HTTP允许的列表
def http_method_not_allowed(self, request, *args, **kwargs):
logger.warning(
'Method Not Allowed (%s): %s', request.method, request.path,
extra={'status_code': 405, 'request': request}
)
return HttpResponseNotAllowed(self._allowed_methods())
# 处理OPtions请求
def options(self, request, *args, **kwargs):
"""Handle responding to requests for the OPTIONS HTTP verb."""
response = HttpResponse()
response.headers['Allow'] = ', '.join(self._allowed_methods())
response.headers['Content-Length'] = '0'
return response
# HTTP支持的列表转大写返回
def _allowed_methods(self):
return [m.upper() for m in self.http_method_names if hasattr(self, m)]
FBV本身是一个函数,那就直接用以前学习的知识就可以
视图层
from django.shortcuts import render
# 装饰器
def outer(func):
def inner(*args, **kwargs):
# 函数执行前逻辑处理
res = func(*args, **kwargs)
# 函数执行后逻辑处理
return res
return inner
@outer
def index(request, *args, **kwargs):
# 逻辑处理
return render(request, 'index.html')
from django.shortcuts import render, HttpResponse, redirect
from django.utils.decorators import method_decorator
# 装饰器
def outer(func):
def inner(*args, **kwargs):
# 函数执行前逻辑处理
start = time.time()
res = func(*args, **kwargs)
# 函数执行后逻辑处理
print(f"用时:{time.time() - start}")
return res
return inner
@method_decorator(outer, 'post')
@method_decorator(outer, 'get')
class Login(View):
# @method_decorator(outer)
def get(self, request):
time.sleep(2)
return render(request, 'login.html')
# @method_decorator(outer)
def post(self, request):
time.sleep(2)
return render(request, 'login.html')
from django.shortcuts import render, HttpResponse, redirect
from django.utils.decorators import method_decorator
class Login(View):
def get(self, request):
time.sleep(2)
return render(request, 'login.html')
def post(self, request):
time.sleep(2)
return render(request, 'login.html')
# @method_decorator(outer)
def dispatch(self, request, *args, **kwargs):
# 函数执行前逻辑处理
start = time.time()
obj = super().dispatch(request, *args, **kwargs)
# 函数执行后逻辑处理
print(f"用时:{time.time() - start}")
return obj
更多【python-Django视图层】相关视频教程:www.yxfzedu.com