开发者社区> 问答> 正文

如何为在Django中输入正确的文件路径(远程或本地服务器)提供验证检查?

我有一种格式,如果格式正确(无论它位于远程/本地服务器中,即FTP),并且不包含任何特定文件(即**<'file_directory'> \ pic.png**),则应接受文件路径(目录)'。如果路径无效,则不应将其保存到模型中。

我尝试了以下方法:

views.py:

from pathlib import Path as PATH  #using pathlib since it's used on all OS platforms.

def home(request):
    if request.method == 'POST':
        form = PForm(request.POST) 
        if form.is_valid():  
            user_id = request.user.id  
            folder_path = form.cleaned_data['folder_path']

            path = PATH(folder_path)  #using pathlib module to check if the folder_path exists.
            root, extension = os.path.splitext(folder_path)  #checks if extension is seen in folder_path.
            if extension or not path.resolve(strict=True): 
                messages.warning(request, "Path is not valid.")
                return redirect('home')
            else:
                #save the path to the model
    else:
        form = PForm()
    return render(request, 'template/home.html, {'form' : form})

用于检查文件扩展名的验证有效,但是一旦输入无效的目录路径,就会出现此错误:

Exception Type: FileNotFoundError
Exception Value: [WinError 3] The system cannot find the path specified: '<invalid pathname>'  #eg 'var/html/www/pictures'

如何实现更好的验证检查和错误处理方式?

展开
收起
安忆333 2019-11-26 10:51:32 949 0
1 条回答
写回答
取消 提交回答
  • 你可以捕获异常并按照以下方式进行相应处理。

    try:
        path = PATH(folder_path)
        root, extension = os.path.splitext(folder_path)
        ....
    # capture exceptions here (you can add multiple)
    except FileNotFoundError:
        # handle exceptions as needed here
        messages.warning(request, "Path is not valid.")
        return redirect('home')
    
    2019-11-26 10:52:32
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
如何运维千台以上游戏云服务器 立即下载
网站/服务器取证 实践与挑战 立即下载
ECS块储存产品全面解析 立即下载