尝试读取djang中的文本文件

2024-10-02 10:22:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法从view.py读取文件的内容

下面是我的代码:

def home_view (request, *args, **kwargs):
    ksh_test_result=AutomationTestResult.objects.values('tatr2tafmc__jobcommand', 'ksh_completion','ftp_log_abs_path','aftp_log_abs_path').distinct()
    ksh_drilldown_data=AutomationTestResult.objects.all()
    for ksh in ksh_test_result:
        ftp_log_file[ksh.tatr2tafmc__jobcommand]=open(ksh.ftp_log_abs_path, 'r').read()
        aftp_log_file[ksh.tatr2tafmc__jobcommand]=open(ksh.aftp_log_abs_path, 'r').read()
    print(ftp_log_file)
    print(aftp_log_file)
    context={
        "ksh_list" : ksh_test_result,
        "ksh_drilldown" : ksh_drilldown_data,
        "ftp_log" : ftp_log_file,
        "aftp_log" : aftp_log_file
    }
    return render(request, "home.html", context)

我正在从数据库读取文件的路径。 当我运行这个代码时,我得到以下错误代码

Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
Internal Server Error: /
Traceback (most recent call last):
  File "/home/nmehta/Projects/GATI/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/nmehta/Projects/GATI/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/nmehta/Projects/GATI/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/nmehta/Projects/GATI/src/KTA/dashboard/views.py", line 11, in home_view
    ftp_log_file[ksh.tatr2tafmc__jobcommand]=open(ksh.ftp_log_abs_path, 'r').read()
AttributeError: 'dict' object has no attribute 'ftp_log_abs_path'
[20/Nov/2019 14:31:27] "GET / HTTP/1.1" 500 65923

Tags: pathinpyloghomeresponserequestftp
1条回答
网友
1楼 · 发布于 2024-10-02 10:22:04

因为您使用values()方法,所以需要将ksh.ftp_log_abs_path更改为ksh['ftp_log_abs_path']values()返回一个查询集,其中字典不是模型实例

如果选中此方法的docs

values() ... Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.

代码的另一个问题是在for循环中读取文件。如果只有一个文件,请使用get_object_or_404()get()Queryset方法

相关问题 更多 >

    热门问题