简体   繁体   English

在 Django 中从 urls.py 输出文本

[英]Outputing text from urls.py in Django

Is there any way I can simply output text (not HTML) from urls.py instead of calling a function (in views.py or otherwise)?有什么方法可以简单地从 urls.py 输出文本(不是 HTML)而不是调用函数(在 views.py 或其他方式中)?

urlpatterns = patterns('',
    url(r'^$', "Hello World"),
)

No, definitly.不,肯定的。 A url must map a pattern to a callable, and this callable must accept a HttpRequest as first argument and return a HttpResponse .一个url必须将一个模式映射到一个可调用对象,并且这个可调用对象必须接受一个HttpRequest作为第一个参数并返回一个HttpResponse

The closer thing you could do would be to map the pattern to a lambda (anonymous function), ie:您可以做的更接近的事情是将模式映射到 lambda(匿名函数),即:

from django.http import HttpResponse

urlpatterns = patterns('',
    url(r'^$', lambda request: HttpResponse("Hello World", content_type="text/plain")),
)

but I would definitly not consider this as good practice.但我绝对不会认为这是好的做法。

The url function takes a callable, so something like url函数需要一个可调用的,所以像

rlpatterns = patterns('',
    url(r'^$', lambda req:HttpResponse("Hello World")),
)

would work.会工作。 There is really nothing gained in doing so though, except making your urls.py harder to read.这样做确实没有任何好处,除了让你的 urls.py 更难阅读。

First, you should consider whether you really want this.首先,你应该考虑你是否真的想要这个。 If there is a need for it (I have never had a need to do this, and I've written a fair share of Django apps during the years), you could wrap this into something more compact, eg如果需要它(我从来没有需要这样做,而且这些年来我已经编写了相当多的 Django 应用程序),你可以将它包装成更紧凑的东西,例如

Note that passing a string directly to url treats it as a method name.请注意,将字符串直接传递给url会将其视为方法名称。

def static_text(s):
    return lambda req:HttpResponse(s)

rlpatterns = patterns('',
    url(r'^$', static_text("Hello World")),
)

对于 Django 2.2 及更高版本

path('', lambda request: HttpResponse("Hello World", content_type="text/plain"), name='home'),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM