python - 使用编解码器返回 HTML 时 View 中出现 Django FileNotFoundError

标签 python html django http web-deployment

我正在 Django 中创建一个返回静态 HTML 页面的 View ,该 View 的代码如下:

from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render_to_response
import codecs

# Basic HTTP response that returns my html index
# To call this view, map it to a URLconf

def index(request):

    # When a request is called, return my index.html

    html = codecs.open("index.html", "r")
    return HttpResponse(html.read())

当我启动 Django 开发时。服务器并导航到我的应用程序,而不是我期望的 index.html 渲染,我在/myapp/ 处遇到 FileNotFoundError 以及 [错误2]没有这样的文件或目录:'index.html'。我知道 index.html 是与我的 views.py 位于同一目录中的真实文件,并且我还尝试通过打开 debug 进行调试.txt 在同一目录中并返回该内容,但结果相同。当我在同一目录中打开 python shell 并尝试打开同一文件时,它运行顺利。任何见解将不胜感激,因为我完全被难住了。

最佳答案

如果您想从与 view.py 文件相同的目录中打开文件,请使用以下命令:

html = open(os.path.dirname(os.path.realpath(__file__)) + 'index.html', "r")

关于python - 使用编解码器返回 HTML 时 View 中出现 Django FileNotFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40066199/

相关文章:

python - BigQuery Python 客户端 : Creating a Table from Query with a Table Description

python - 为什么 cProfile 会导致函数返回不同的值?

javascript - 如果包含某些内容,请删除 HTML 表标签

python - Django-cas - 登录成功后出现403错误

java - 对于开发人员生产力来说,最好的服务器端 Web 框架是什么?

python - 带有 lxml 的 Xpath 返回空字符串,selenium 工作正常

python - 正则表达式匹配中 [ab] 和 (a|b) 的区别?

CSS - 使 SPAN 延伸到其容器的末端/填充空白区域?

html - 将带有单独音频的静音视频加载到 HTML5 视频标签中

python - 找不到页面 (404) 请求方法 : POST Request URL: http://127. 0.0.1:8000/accounts/signup/signup