Django:在Shell中模拟HTTP请求 [英] Django: simulate HTTP requests in shell

查看:175
本文介绍了Django:在Shell中模拟HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚了解到,使用Rails可以用几行代码在控制台中模拟HTTP请求.

I just learnt that with Rails is possible to simulate HTTP requests in the console with few lines of code.

签出: http://37signals.com/svn/posts/3176-three-quick-rails-console-tips (深入应用程序"一节).

Check out: http://37signals.com/svn/posts/3176-three-quick-rails-console-tips (section "Dive into your app").

使用Django是否有类似的方法?会很方便.

Is there a similar way to do that with Django? Would be handy.

推荐答案

我如何模拟来自python命令行的请求是:

How I simulate requests from the python command line is:

  • Use the excellent requests library
  • Use the django reverse function

模拟请求的简单方法是:

A simple way of simulating requests is:

>>> from django.urls import reverse
>>> import requests
>>> r = requests.get(reverse('app.views.your_view'))
>>> r.text
(prints output)
>>> r.status_code
200

更新:确保启动django shell(通过manage.py shell),而不是经典的python shell.

Update: be sure to launch the django shell (via manage.py shell), not a classic python shell.

更新2:对于Django< 1.10,将第一行更改为

Update 2: For Django <1.10, change the first line to

from django.core.urlresolvers import reverse 

这篇关于Django:在Shell中模拟HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆