Django学习系列11:在服务器中处理POST请求
2024-09-05 13:19:34
之前的代码还没有为表单指定action=属性,因此提交表单默认返回之前渲染的页面,即“/”,这个由视图函数home_page处理。下面修改这个视图函数,让它能处理POST请求。
这意味着要为视图函数home_page编写一个新的单元测试,打开文件 lists/tests.py
在HomePageTest类中添加一个新方法,在其中添加post请求,在检查返回的HTML中是否有新添加的待办事项文本。
"""向浏览器返回真正的HTML响应,添加一个新的测试方法"""
from django.test import TestCase
from django.urls import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from lists.views import home_page
class HomePageTest(TestCase): [……] def Test_home_page_can_save_a_post_request(self):
request = HttpRequest()
request.method = 'POST'
request.POST['item_text'] = 'A new list item' response = home_page(request)
self.assertIn('A new list item', response.content.decode())
设置配置——执行代码——编写断言是单元测试的典型结构(前三行作用是设置测试的背景;然后在中间添加一行调用要测试的函数;最后编写断言)
可以看出,用到了HttpRequest的几个特殊属性:.methed和.post.(更多内容查看https://docs.djangoproject.com/en/1.7/ref/request-response/)
post我们调用self.client.post,正如您所看到的,它需要一个数据参数,其中包含我们要发送的表单数据。
然后我们检查post请求以呈现的html结束。这给了我们预期的失败:
# python manage.py test
为了让测试通过,在view.py文件中添加一个if语句,为POST请求提供一个不同的代码执行路劲。按照典型的TDD方式,先故意编写一个愚蠢的返回值。
from django.shortcuts import render
from django.http import HttpResponse # Create your views here.在这儿编写视图
def home_page(request):
if request.method == 'POST':
return HttpResponse(request.POST['item_text'])
return render(request, 'home.html')
这样单元测试是通过了,但不是我们想要的,我们希望把POST请求提交的数据添加到首页模板的表格里。
最新文章
- P/Invoke:C#调用C++
- tomcat之Session的管理
- C#获取网页内容的三种方式
- Windows Azure支持七层负载均衡--Application Gateway
- [工作bug]一个weblogic跨应用导致session丢失的bug之旅
- Android Studio解决unspecified on project app resolves to an APK archive which is not supported
- jenkis编译报错:需要class,interface或enum
- linux cache swap 以及 虚拟内存等
- HTTP协议的8种请求类型介绍
- JavaScript 题目(作用域)
- windows部署MongoDB
- HTML页面全屏/退出全屏
- Java8 Lambda和Stream的用法
- applicationContext.xml配置Spring样板
- python编码问题在此终结
- c# 软件绑定网卡mac的实用
- 使用php的curl根据关键词爬取百度搜索结果页
- spring---aop(2)---Spring AOP的JDK动态代理
- 【转】VueJS中学习使用Vuex详解
- 解决Eclipse下启动tomcat报错:/bin/bootstrap.jar which is referenced by the classpath, does not exist.