python小功能
django实现将linux目录和文件名列出来
def index(request): obj=models.USER.objects.all() fileroot = 'd:\machangwei' fli = os.listdir(fileroot) print(fli) dirdic = {} filedic = {} for i in fli: file = os.path.join(fileroot, i) if os.path.isdir(file): dirdic[i] = file print('d:', file) else: filedic[i] = file print('f:', file) return render(request,'index.html',{"obj":obj,'dirdic':dirdic,'filedic':filedic})
<h2>根目录下的目录和文件:</h2> {% for k,v in dirdic.items %} <a href="" srcmcw="{{ v }}">{{ k }}</a><br> {% endfor %} {% for k,v in filedic.items %} <a href="" srcmcw="{{ v }}">{{ k }}</a><br> {% endfor %}
访问结果
将目录和文件名分层展示出来,这里暂没实现,非目录文件的点击操作
def listfile(request): ''' 1、要获取前端传来的fp,当前目录绝对路径,跟据这个参数来os list目录,这里暂且用的是全路径 2、 :param request: :param fname: :return: ''' # print(fname) #venv #print(request.GET) #<QueryDict: {'fp': ['d:\\machangwei\\whl']}> fp=request.GET.get('fp',['m']) #d:\machangwei\venv 当前目录绝对路径 fn=request.GET.get('fn','') #当前目录名字,f子文件名字,这里貌似没用到 # zfp=os.path.join(fp,fn) #当前目录下子文件绝对路径,我们传给后端的是allf,所以这个是错误的,新页面中的fp需要 # 当前目录名字fp拼接当前目录下单个文件的名字 print(request.GET) print('fp:',fp) #fp: d:\machangwei\venv print('fn:',fn) #fn: venv if os.path.isdir(fp): allf=os.listdir(fp) #['Include', 'Lib', 'pip-selfcheck.json', 'pyvenv.cfg', 'Scripts'] #列出当前目录下所有文件 print(allf) return render(request,'listfile.html',{'allf':allf,'fn':fn,'fp':fp})
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>{{ fp }}\{{ f }}目录下的目录和文件:</h2> <p><a href="/index/">返回首页</a></p> {% for f in allf %} <a href="/listfile/?fp={{ fp }}\{{ f }}&fn={{ f }}" name="{{ fp }}/{{ f }}">{{ f }}</a><br> {% endfor %} </body> </html>
效果展示:
上面的不安全,这样随便拼接路径,我就能看到所有系统里的文件了。而不单只是我的froot,d:\machangwei下的文件。应该做个校验,re匹配,不是这个目录的返回没有权限
添加权限认证。最后把froot不展示在地址栏,这里只是研究,就不改了
查看根目录下的文件,还是可以的
添加文件下载功能,如果是目录,就列出目录下文件,如果不是目录,就下载下来
else: file = open('%s'%fp, 'rb') response = HttpResponse(file) response['Content-Type'] = 'application/octet-stream' # 设置头信息,告诉浏览器这是个文件 response['Content-Disposition'] = 'attachment;filename="%s"'%fn return response
文件下载参考:https://www.jb51.net/article/135951.htm