存在 Django 和测试本地 URL
我有一个模型需要存储将成为 Django 环境一部分的 URL。如果我存储普通 URL,我会使用 models .URLField
,并使用 verify_exists
确保 URL 确实存在。
然而,这在开发中效果并不好,因为开发服务器是单线程的,它会无限期地挂起,因为它无法同时处理两个请求。
我希望使用 resolve()
,但我很难将该文档页面末尾的函数
myview
调整为不接受请求的版本,因为我想检查给定的本地 URL 是否可以被解决,并在没有引发 404 的情况下从空白会话中调用。
我希望使用 validator 来完成此操作,如下所示:
def validate_local_url(value):
try:
view, args, kwargs = resolve(value)
view(*args, **kwargs)
except Resolver404:
raise ValidationError(u'%s is not a local URL (not a valid URL)' % value)
except Http404:
raise ValidationError(u'%s is not a local URL (does not exist)' % value)
但是,如果没有将有效的 request
对象传递到 kwargs
中,则会失败。如何生成虚拟(空白)请求对象?我尝试过仅使用 django.http.HttpRequest 。
I have a model which needs to store URLs which will be part of the Django environment. If I was storing normal URLs, I'd use models.URLField
, and use verify_exists
to make sure the URL actually exists.
However, this doesn't work that great in development, since the dev server is single-threaded, it hangs indefinitely, since it can't process two requests at once.
I was hoping to do something using resolve()
, but am having difficulty adapting the function myview
at the end of that documentation page to a version which does not take a request, since I want to check that a given local URL can be resolved, and called without a 404 being raised, from a blank session.
I was hoping to do this with a validator, something like this:
def validate_local_url(value):
try:
view, args, kwargs = resolve(value)
view(*args, **kwargs)
except Resolver404:
raise ValidationError(u'%s is not a local URL (not a valid URL)' % value)
except Http404:
raise ValidationError(u'%s is not a local URL (does not exist)' % value)
However, this fails without a valid request
object being passed into kwargs
. How do I generate a dummy (blank) request object? I've tried just using django.http.HttpRequest
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只是一个疯狂的想法,不确定是否有帮助。您是否考虑过命名网址并使用
reverse()< /代码>
?如果 URL 有效,
Reverse
就会起作用;如果 URL 无效,Reverse
就会失败。Just a wild idea, not sure if it will be helpful. Have you considered naming the urls and using
reverse()
?Reverse
will work if the URL is valid and will fail when it is not.您是否喜欢使用 django 测试客户端?
如果是这样,这应该可以做到:
只是,你知道,确保在死刑下
validate_local_url
不能被本地GET
调用。请求,否则有人可以轻松地将您的服务器设置为无限循环:然后:
http://example.com com/infinite_loop/?path_field=infinite_loop
Are you cool with using the django test Client?
If so, this should do it:
Just, you know, make sure under penalty of death that
validate_local_url
can never be called by a localGET
request, otherwise someone can trivially set your server on an infinite loop:And then:
http://example.com/infinite_loop/?path_field=infinite_loop