Python 利用flask搭建一个共享服务器的步骤


Posted in Python onDecember 05, 2020

零、概述

我利用flask搭建了一个简易的共享服务器,分享给大家

一、python代码

import os
import time
from flask import Flask,render_template,url_for,redirect,send_from_directory
# 共享文件夹的根目录
rootdir = r'C:\Users\Administrator\Downloads\zlkt'
 
app = Flask(__name__)
 
@app.route('/doc/')
@app.route('/doc/<subdir>/')
def document(subdir=''):
    if subdir == '':
        # 名字为空,切换到根目录
        os.chdir(rootdir)
    else:
        fullname = rootdir + os.sep + subdir
        #  如果是文件,则下载
        if os.path.isfile(fullname):
            return redirect(url_for('downloader', fullname=fullname))
        #  如果是目录,切换到该目录下面
        else:
            os.chdir(fullname)
    current_dir = os.getcwd()
    current_list = os.listdir(current_dir)
    contents = []
    for i in sorted(current_list):
        fullpath = current_dir + os.sep + i
        # 如果是目录,在后面添加一个sep
        if os.path.isdir(fullpath):
            extra = os.sep
        else:
            extra = ''
        content = {}
        content['filename'] = i + extra
        content['mtime'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.stat(fullpath).st_mtime))
        content['size'] = str(round(os.path.getsize(fullpath) / 1024)) + 'k'
        contents.append(content)
    return render_template('test.html', contents=contents, subdir=subdir, ossep=os.sep)
 
@app.route('/download/<fullname>')
def downloader(fullname):
    filename = fullname.split(os.sep)[-1]
    dirpath = fullname[:-len(filename)]
    return send_from_directory(dirpath, filename, as_attachment=True)
 
if __name__ == '__main__':
    app.run()

二、html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文档管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="external nofollow" 
       integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
       crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css" rel="external nofollow" 
       integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
       crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
       integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
       crossorigin="anonymous"></script>
    <style type="text/css">
         .big-border {
        background: #fff;
        width: 1400px;
        margin: 0 auto;
        padding: 10px;
        }
 
        body {
            background: #f3f3f3;
        }
 
        .page-title {
            text-align: center;
        }  
    </style>
</head>
<body>
  <div class="big-border">
    <h3 class="page-title">文档管理</h3>
    <hr>
    <h4>当前目录 {{ossep+subdir}}</h4>
    <hr>
    <table width="600px">
      <thead>
        <tr>
          <th>文件或目录名</th>
          <th>修改时间</th>
          <th>大小</th>
        </tr>
      </thead>
      <tbody>
        {% if subdir %}
        <tr>
          <td><a href="../" rel="external nofollow" >..{{ossep}}</a></td>
          <td></td>
          <td></td>
        </tr>
        {% endif %}
        {% for i in contents %}
        <tr>
          <td><a href="{{ url_for('document', subdir=subdir+i.filename) }}" rel="external nofollow" >{{ i.filename }}</a></td>
          <td>{{ i.mtime }}</td>
          <td>{{ i.size }}</td>
          </tr>
        {% endfor %}
      </tbody>
    </table>
    <hr>
  </div>
</body>
</html>

三、使用
1. 更改python代码中的rootdir,这里需要填你所共享的文件夹

2. render_template('test.html', ...),我将html命名为test.html,所以这里就是render_template('test.html', ...),你如果命名了其它名字,这里记得改一下

四、最后效果

运行脚本之后,用浏览器打开 http://127.0.0.1:5000/doc/,显示效果如下图

Python 利用flask搭建一个共享服务器的步骤

Python 利用flask搭建一个共享服务器的步骤

最后欢迎大家使用,和我交流。

以上就是Python 利用flask搭建一个共享服务器的步骤的详细内容,更多关于flask搭建服务器的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Python对象的深拷贝和浅拷贝详解
Aug 25 Python
Python中tell()方法的使用详解
May 24 Python
python实现应用程序在右键菜单中添加打开方式功能
Jan 09 Python
Python利用itchat对微信中好友数据实现简单分析的方法
Nov 21 Python
Python编程argparse入门浅析
Feb 07 Python
用Python写一段用户登录的程序代码
Apr 22 Python
用Python下载一个网页保存为本地的HTML文件实例
May 21 Python
Django 使用Ajax进行前后台交互的示例讲解
May 28 Python
Python 删除整个文本中的空格,并实现按行显示
Jul 24 Python
python爬取酷狗音乐排行榜
Feb 20 Python
用python写一个定时提醒程序的实现代码
Jul 22 Python
详解用Python进行时间序列预测的7种方法
Mar 13 Python
快速解决pymongo操作mongodb的时区问题
Dec 05 #Python
pymongo insert_many 批量插入的实例
Dec 05 #Python
python 写一个文件分发小程序
Dec 05 #Python
解决Pymongo insert时会自动添加_id的问题
Dec 05 #Python
用python对oracle进行简单性能测试
Dec 05 #Python
python mongo 向数据中的数组类型新增数据操作
Dec 05 #Python
python自动从arxiv下载paper的示例代码
Dec 05 #Python
You might like
ThinkPHP调试模式与日志记录概述
2014/08/22 PHP
PHP让网站移动访问更加友好方法
2019/02/14 PHP
JQuery 拾色器插件发布-jquery.icolor.js
2010/10/20 Javascript
javascipt基础内容--需要注意的细节
2013/04/10 Javascript
邮箱下拉自动填充选择示例代码附图
2014/04/03 Javascript
引用其它js时如何同时处理多个window.onload事件
2014/09/02 Javascript
JavaScript实现在数组中查找不同顺序排列的字符串
2014/09/26 Javascript
js实现iGoogleDivDrag模块拖动层拖动特效的方法
2015/03/04 Javascript
JavaScript实现基于Cookie的存储类实例
2015/04/10 Javascript
JavaScript转换与解析JSON方法实例详解
2015/11/24 Javascript
简单分析javascript中的函数
2016/09/10 Javascript
JavaScript获取短信验证码(周期性)
2016/12/29 Javascript
浅谈js中startsWith 函数不能在任何浏览器兼容的问题
2017/03/01 Javascript
js获取元素的偏移量offset简单方法(必看)
2017/07/05 Javascript
微信小程序使用form表单获取输入框数据的实例代码
2018/05/17 Javascript
js中的reduce()函数讲解
2019/01/18 Javascript
记一次vue-webpack项目优化实践详解
2019/02/17 Javascript
JS实现判断有效的数独算法示例
2019/02/25 Javascript
vue 使用高德地图vue-amap组件过程解析
2019/09/07 Javascript
python 自动化将markdown文件转成html文件的方法
2016/09/23 Python
Python的语言类型(详解)
2017/06/24 Python
Python学习pygal绘制线图代码分享
2017/12/09 Python
Django使用HttpResponse返回图片并显示的方法
2018/05/22 Python
python获取txt文件词向量过程详解
2019/07/05 Python
Python实用库 PrettyTable 学习笔记
2019/08/06 Python
python 列表推导式使用详解
2019/08/29 Python
python实现交并比IOU教程
2020/04/16 Python
如何在pycharm中安装第三方包
2020/10/27 Python
HTML5 Canvas玩转酷炫大波浪进度图效果实例(附demo)
2016/12/14 HTML / CSS
Berghaus官网:户外服装和设备,防水服
2020/01/17 全球购物
《浅水洼里的小鱼》听课反思
2014/02/28 职场文书
周年庆典主持词
2014/04/02 职场文书
网站客服岗位职责
2014/04/05 职场文书
css实现文章分割线样式的多种方法总结
2021/04/21 HTML / CSS
Python OpenCV之常用滤波器使用详解
2022/04/07 Python
Python内置的数据类型及使用方法
2022/04/13 Python