Django之视图层

JsonResponse方法

  • 首先,如果不使用JsonResponse如何给前端返回json格式字符串
def index_func(request):
    user_list = {'name': '汤姆', 'age': 8}
    # 转换成json字符串,并且不转换为bytes类型,可以输出中文
    json_list = json.dumps(user_list, ensure_ascii=False)
    return HttpResponse(json_list)
  • 使用JsonResponse给前端返回json格式字符串
# 导入模块
from django.http import JsonResponse
def index_func(request):
    user_list = {'name': '汤姆', 'age': 8}
    return JsonResponse(user_list)  # 直接可以输出json格式字符串,但如何输出中文?
  • 通过研究源码,查找如何输出中文到前端
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.'
        )
	# 分析1:它接收一个参数json_dumps_params,当不传值时,这个参数会变为空字典
	# 分析3:如果我们给它传一个字典:{'ensure_ascii': False},那下面取值就是ensure_ascii=False
    if json_dumps_params is None:
        json_dumps_params = {}
    kwargs.setdefault('content_type', 'application/json')
	'''
	分析2:如果要传中文,命令应该为json_list = json.dumps(user_list, ensure_ascii=False)
          转换为源码中的命令则为:data = json.dumps(data, cls=encoder, ensure_ascii=False)
	'''
    data = json.dumps(data, cls=encoder, **json_dumps_params)
    super().__init__(content=data, **kwargs)
  • 所以传输中文方法为使用json_dumps_params={'ensure_ascii': False}参数
from django.http import JsonResponse
def index_func(request):
    user_list = {'name': '汤姆', 'age': 8}
    # 转换成json字符串,并且不转换为bytes类型,可以输出中文
    return JsonResponse(user_list, json_dumps_params={'ensure_ascii': False})

序列化列表

# 序列化列表需要增加safe=False参数
from django.http import JsonResponse
def index_func(request):
    user_list = [1, 2, 3, 4, 5, 6]
    # 转换成json字符串,并且不转换为bytes类型,可以输出中文
    return JsonResponse(user_list, json_dumps_params={'ensure_ascii': False}, safe=False)

request对象获取文件

上传单个文件

  • form表单中如果要上传文件,需要在前端form表单定义参数。
  • 前端定义参数
method="post"
enctype="multipart/form-data"  # 默认为enctype="application/x-www-form-urlencoded"
  • 后端获取文件数据
request.FILES
  • 测试代码如下
  • 前端
<body>
    <div class="container">
        <form action="" class="form-control" method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <p>用户名
                <input type="text" name="username">
            </p>
            <p>密码
                <input type="password" name="password">
            </p>
            <p>hoppy:
                <input type="checkbox" name="hobby" value="basketball">篮球
                <input type="checkbox" name="hobby" value="football">足球
                <input type="checkbox" name="hobby" value="icehockey">冰球
            </p>
            <p>file
                <input type="file" name="file">
            </p>
            <button>提交</button>
        </form>
    </div>
    <div align="center"></div>
</body>
  • 后端
def index_func(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        checkbox = request.POST.getlist('hobby')
        print('username>>>:', username)
        print('password>>>:', password)
        print('checkbox>>>:', checkbox)

        return render(request, 'test1.html')
    return render(request, 'test1.html')

def index_func(request):
    if request.method == 'POST':
        file_obj = request.FILES.get('file')
        with open(file_obj.name, 'wb') as f:
            for line in file_obj:
                f.write(line)
        return render(request, 'test1.html')
    return render(request, 'test1.html')

上传多个文件

  • 前端
<input type="file" name="file" multiple>   # input表单中添加multiple参数
  • 后端
request.FILES.getlist(file)   # 使用getlist方法

将文件保存在本地

def index_func(request):
    if request.method == 'POST':
        for file_obj in request.FILES.getlist('file'):
            with open(f'%s' % file_obj.name, 'wb') as f:
                for line in file_obj:
                    f.write(line)
        return render(request, 'test1.html')
    return render(request, 'test1.html')

FBV与CBV

  • FBV (function based view) 基于函数的视图
def myFunction(request):
    return HttpResponse('Hello World')
  • CBV (class based view) 基于类的视图
# 视图层写法:
# 导入模块
from django import views
# 定义类
class MyCBVTest(views.View):   # 必须继承views.View,注意第二个是大写的V
    # 当请求为get时,自动调用get方法
    def get(self, request):
        return render(request, 'login.html')

    # 当请求为post时,自动调用post方法
    def post(self, request):
        return HttpResponse('I am CBV Post method!')

# 路由层写法:
path('login/', views.MyCBVTest.as_view()),   # 注意最后的as_view()是固定写法
  • 前端
<body>
    <p>I am CBV get method</p>
    <form action="/login/" method="post">
        {% csrf_token %}
        <input type="submit">点我
    </form>
</body>
posted @   树苗叶子  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
点击右上角即可分享
微信分享提示