在没有服务器的情况下运行Django

我有一个小型Django网站mysite。我希望能够在不运行Web服务器的情况下运行Django应用。而不是使用HTTP客户端发出请求,我想编写如下内容:

django.run()
result = django_request('/foo/bar')

因此Django仍将进行URL解析等,只是不通过UWSGI提供服务。这合理吗?

我的最终目标是端到端对我的Web应用程序的端点进行基准测试,但I / O除外。

jiajia2xm 回答:在没有服务器的情况下运行Django

您可以使用Django测试客户端。

在Django shell中尝试以下代码

➜ python manage.py shell
Python 3.6.8 (default,Aug 20 2019,17:12:48) 
Type 'copyright','credits' or 'license' for more information
IPython 7.8.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from django.test import Client

In [2]: c = Client()

In [3]: response = c.get('/blog/')

In [4]: response.status_code
Out[4]: 200

In [5]: response.content
Out[5]: b'\n<!DOCTYPE html>\n<html>\n<head>\n\t<title>My Blog</title>\n\t<link href="/static/css/blog.css" rel="stylesheet">\n</head>\n<body>\n\t<div id="content">\n\t\t\n\t<h1>My Blog</h1>\n\t\n\t\t<h2>\n\t\t\t<a href="/blog/2019/10/16/my-second-post/">\n\t\t\t\tmy second post\n\t\t\t</a>\n\t\t</h2>\n\t\t<p class="date">\n\t\t\tPublished Oct. 16,2019,7:15 a.m. by admin\n\t\t</p>\n\t\t<p>Nice</p>\n\t\n\n\t</div>\n\t<div id="sidebar">\n\t\t<h2>My blog</h2>\n\t\t<p>This is my blog</p>\n\t</div>\n</body>\n</html>'

看看官方文档Test Client

,

您还可以编写自己的management commands,并用类似的方式调用它们

./manage.py my_foo_command --bar=baz --output=baz.txt

(您编写的部分使用Python Argparse解析命令)

本文链接:https://www.f2er.com/3161819.html

大家都在问