Django不认为是文件,而Python认为是文件?


一个view:


 python


 from django.shortcuts import render
from . import gears

# a view.
def index(request):
    context = {
        'slogan': gears.get_slogan(),
    }
    return render(request, 'blog_index.html', context)

gears.py :


 python


 def get_slogan():
    import os.path as p
    path_str = '../configs/slogans.txt'
    print(p.isfile(path_str))    # 控制台输出
    if p.isfile(path_str):
        f = open(path_str)
        slogans_list = []
        for line in f:
            slogans_list.append(line)
        import rondom
        slogan = rondom.choice(slogans_list)
        if slogan:
            return slogan
    return '美女与咖啡,一杯又一杯'

if __name__ == '__main__':
    import os.path as p
    print(p.isfile('../configs/slogans.txt'))    # 在Python的命令行里执行时输出

我通过Python的交互命令行来执行 gears.py 返回的是 True ,但是通过运行网站,在控制台里的输出却是 False ,为什么呢?
在所写的路径里面的确有那个文件。

python python3.x django

tkfkid 9 years, 4 months ago

试试使用绝对路径

triella answered 9 years, 4 months ago


 path_str = '../configs/slogans.txt'

这个是 相对路径 ,使用 django 服务的时候,根据这个相对路径可能找不到你的那个文件。你可以换成 绝对路径

在程序中尽量不要硬编码相对路径。

X-joker answered 9 years, 4 months ago

Your Answer