Outputing text from urls.py in Django

一曲冷凌霜 提交于 2019-12-22 08:23:20

问题


Is there any way I can simply output text (not HTML) from urls.py instead of calling a function (in views.py or otherwise)?

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

回答1:


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.

The closer thing you could do would be to map the pattern to a lambda (anonymous function), ie:

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.




回答2:


The url function takes a callable, so something like

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.

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, e.g.

Note that passing a string directly to url treats it as a method name.

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

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



回答3:


For Django 2.2 and above

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



来源:https://stackoverflow.com/questions/31538793/outputing-text-from-urls-py-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!