Django:在shell中模拟HTTP请求

vwkv1x7d  于 2022-11-26  发布在  Go
关注(0)|答案(3)|浏览(133)

我刚刚了解到,使用Rails可以用几行代码在控制台中模拟HTTP请求。
查看:http://37signals.com/svn/posts/3176-three-quick-rails-console-tips(“深入了解您的应用”部分)。
对 Django 有类似的方法吗?会很方便。

e5njpo68

e5njpo681#

您可以使用RequestFactory,它允许

  • 将用户插入请求中
  • 将上载的文件插入到请求中
  • 将特定参数发送到视图

并且不需要使用requests的附加依赖性。
请注意,您必须同时指定URL和视图类,因此与使用请求相比,它需要额外的代码行。

from django.test import RequestFactory

request_factory = RequestFactory()
my_url = '/my_full/url/here'  # Replace with your URL -- or use reverse
my_request = request_factory.get(my_url)
response = MyClasBasedView.as_view()(my_request)  # Replace with your view
response.render()
print(response)

要设置请求的用户,请在获得响应之前执行类似my_request.user = User.objects.get(id=123)的操作。
要将参数发送到基于类的视图,请执行类似response = MyClasBasedView.as_view()(my_request, parameter_1, parameter_2)的操作

扩展示例

下面是一个结合使用RequestFactory和这些内容的示例

  • HTTP POST(指向url url、功能视图view和数据字典post_data
  • 上传单个文件(路径file_path,名称file_name,表单字段值file_key
  • 为请求分配用户(user
  • 从url传递kwargs字典(url_kwargs

SimpleUploadedFile有助于以对表单有效的方式格式化文件。

from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import RequestFactory

request = RequestFactory().post(url, post_data)
with open(file_path, 'rb') as file_ptr:
    request.FILES[file_key] = SimpleUploadedFile(file_name, file_ptr.read())
    file_ptr.seek(0)  # resets the file pointer after the read
    if user:
        request.user = user
    response = view(request, **url_kwargs)

从Python shell使用RequestFactory

默认情况下,RequestFactory将服务器命名为“testserver,”如果不在测试代码中使用它,可能会导致问题。

DisallowedHost: Invalid HTTP_HOST header: 'testserver'. You may need to add 'testserver' to ALLOWED_HOSTS.

@boatcoder注解中的解决方法说明了如何将默认服务器名称覆盖为“localhost”:

request_factory = RequestFactory(**{"SERVER_NAME": "localhost", "wsgi.url_scheme":"https"}).
bybem2ql

bybem2ql2#

我模拟python命令行请求的方式如下:

模拟请求的简单方法是:

>>> 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。
更新2:对于Django〈1.10,将第一行改为

from django.core.urlresolvers import reverse
nzk0hqpo

nzk0hqpo3#

(See tldr;向下)
这是一个老问题,但只是增加一个答案,以防有人可能感兴趣。
虽然这可能不是最好的(或者说Django)做事方式。但是你可以尝试这样做。
在你的django壳里

>>> import requests
>>> r = requests.get('your_full_url_here')

**解释:**我省略了reverse(),解释是,由于reverse()或多或少地找到了与www.example.com函数关联的urlviews.py,如果愿意,您可以省略reverse(),并将整个url代替。

例如,如果你在django项目中有一个friends应用,并且你想在friends应用中看到list_all()(在www.example.com中views.py)函数,那么你可以这样做。

顶级域名注册权;

>>> import requests
>>> url = 'http://localhost:8000/friends/list_all'
>>> r = requests.get(url)

相关问题