我刚刚了解到,使用Rails可以用几行代码在控制台中模拟HTTP请求。
查看:http://37signals.com/svn/posts/3176-three-quick-rails-console-tips(“深入了解您的应用”部分)。
对 Django 有类似的方法吗?会很方便。
我刚刚了解到,使用Rails可以用几行代码在控制台中模拟HTTP请求。
查看:http://37signals.com/svn/posts/3176-three-quick-rails-console-tips(“深入了解您的应用”部分)。
对 Django 有类似的方法吗?会很方便。
3条答案
按热度按时间e5njpo681#
您可以使用
RequestFactory
,它允许并且不需要使用requests的附加依赖性。
请注意,您必须同时指定URL和视图类,因此与使用请求相比,它需要额外的代码行。
要设置请求的用户,请在获得响应之前执行类似
my_request.user = User.objects.get(id=123)
的操作。要将参数发送到基于类的视图,请执行类似
response = MyClasBasedView.as_view()(my_request, parameter_1, parameter_2)
的操作扩展示例
下面是一个结合使用
RequestFactory
和这些内容的示例url
、功能视图view
和数据字典post_data
)file_path
,名称file_name
,表单字段值file_key
)user
)url_kwargs
)SimpleUploadedFile
有助于以对表单有效的方式格式化文件。从Python shell使用RequestFactory
默认情况下,
RequestFactory
将服务器命名为“testserver,”如果不在测试代码中使用它,可能会导致问题。@boatcoder注解中的解决方法说明了如何将默认服务器名称覆盖为“localhost”:
bybem2ql2#
我模拟python命令行请求的方式如下:
模拟请求的简单方法是:
更新:一定要启动django shell(通过
manage.py shell
),而不是经典的python shell。更新2:对于Django〈1.10,将第一行改为
nzk0hqpo3#
(See tldr;向下)
这是一个老问题,但只是增加一个答案,以防有人可能感兴趣。
虽然这可能不是最好的(或者说Django)做事方式。但是你可以尝试这样做。
在你的django壳里
**解释:**我省略了
reverse()
,解释是,由于reverse()
或多或少地找到了与www.example.com函数关联的urlviews.py,如果愿意,您可以省略reverse()
,并将整个url代替。例如,如果你在django项目中有一个friends应用,并且你想在friends应用中看到
list_all()
(在www.example.com中views.py)函数,那么你可以这样做。顶级域名注册权;