python - Django:在网站上显示txt文件的内容

标签 python django python-2.7

我的 views.py 中有这个

def read_file(request):
    f = open('path/text.txt', 'r')
    file_contents = f.read()
    print (file_contents)
    f.close()
    return render(request, "index.html", context)

网址.py:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^impala/$', views.people, name='impala'),
]

我在网站上没有看到任何内容(text.txt 文件包含信息)。 我也没有在终端中看到任何输出,也没有错误。

最佳答案

如果您的 views.py 中有函数 read_file,请将您的 urls.py 调整为:

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^test/$', views.read_file, name='test'),
    url(r'^impala/$', views.people, name='impala'),
]

修复基于函数的 View :

from django.http import HttpResponse

def read_file(request):
    f = open('path/text.txt', 'r')
    file_content = f.read()
    f.close()
    return HttpResponse(file_content, content_type="text/plain")

启动您的开发服务器并访问 localhost:port/test。您应该会看到 test.txt 的内容。

如果您想将文本文件的内容传递给您的template.html,请将其添加到context 变量并在您的模板中使用{{ file_content }} 访问它。 .

def read_file(request):
    f = open('path/text.txt', 'r')
    file_content = f.read()
    f.close()
    context = {'file_content': file_content}
    return render(request, "index.html", context)

请记住,出于性能原因,像 nginxapache 这样的网络服务器通常会负责提供静态文件。

关于python - Django:在网站上显示txt文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49016255/

相关文章:

python - 列表与数据框的交叉连接(笛卡尔积)

python - Windows 上的 Git clean-filter python 脚本

java - 在 Ant 上为 Django 设置 Cassandra 失败 : Unable to find a javac compiler;

python - 如何在 python 中获取通过 AJAX 发布的值数组?

python - PostgreSQL: "database does not exist"

python - 来自while循环的语法错误

python - 用QWebEngineView显示html时如何获取verticalScrollBar的最大值和当前值

Python sh 导入导致 PyDev 中出现 Unresolved 导入错误

python - 如何确定模块名称是否是 python 标准库的一部分

python - : `if x.isupper() and not in y` 行语法错误