`

django.utils._os 中 safe_join 函数 windows下总报ValueError异常

阅读更多
最近无聊在家看看django,在做第七章那个gallery例子的时候,因为我实在windows下鼓弄,在设置图片上传到电脑里那里时,我在setting.py中 将MEDIA_ROOT = 'D:' 设为d盘,然后 model.py中 image=models.ImageField(upload_to='photo')

等我去admin管理页面里添加数据的时候老是报 Attempted access to ‘photo\XXX.jpg’denied

最后一只沿着报错查到了 django.utils._os 中 safe_join 函数
def safe_join(base, *paths):
    """
    Joins one or more path components to the base path component intelligently.
    Returns a normalized, absolute version of the final path.

    The final path must be located inside of the base path component (otherwise
    a ValueError is raised).
    """
    # We need to use normcase to ensure we don't false-negative on case
    # insensitive operating systems (like Windows).
    print 'paths:1',paths
    base = force_unicode(base)
    print 'base:',base
    paths = [force_unicode(p) for p in paths]
    print 'paths2:',paths
    final_path = normcase(abspathu(join(base, *paths)))
    print 'final_path:',final_path
    base_path = normcase(abspathu(base))
    print 'base_path:',base_path
    base_path_len = len(base_path)
    print 'base_path_len:',base_path_len
    print 'final_path[base_path_len:base_path_len+1]:',final_path[base_path_len:base_path_len+1]
    print not final_path.startswith(base_path)
    print final_path[base_path_len:base_path_len+1] not in ('', sep)
    # Ensure final_path starts with base_path and that the next character after
    # the final path is os.sep (or nothing, in which case final_path must be
    # equal to base_path).
    if not final_path.startswith(base_path)\
       or final_path[base_path_len:base_path_len+1] not in ('', sep):
        raise ValueError('the joined path is located outside of the base path'' component')
    return final_path


将所有变量打出来后发现问题出来or final_path[base_path_len:base_path_len+1] not in ('', sep): 这个判断上,sep在windows下是'\\',但是final_path[base_path_len:base_path_len+1]一只是我图片名的第一个字母,所以一直在判断错误,不知道是我自己配置问题还是django的问题,现在吧final_path[base_path_len:base_path_len+1]这个判断注释后,我就上传图片成功了。

最后我用的是python2.5 django1.2.4
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics