我有一种格式,如果格式正确(无论它位于远程/本地服务器中,即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'
如何实现更好的验证检查和错误处理方式?
你可以捕获异常并按照以下方式进行相应处理。
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')
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。