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回调函数的使用方法
Jan 23 Python
python 3.5下xadmin的使用及修复源码bug
May 10 Python
python并发2之使用asyncio处理并发
Dec 21 Python
分享Python切分字符串的一个不错方法
Dec 14 Python
关于python之字典的嵌套,递归调用方法
Jan 21 Python
python切片(获取一个子列表(数组))详解
Aug 09 Python
python实现猜拳小游戏
Apr 05 Python
python线程中的同步问题及解决方法
Aug 29 Python
Python使用socketServer包搭建简易服务器过程详解
Jun 12 Python
解决Keyerror ''acc'' KeyError: ''val_acc''问题
Jun 18 Python
五分钟学会怎么用python做一个简单的贪吃蛇
Jan 12 Python
如何获取numpy array前N个最大值
May 14 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
php中的一个中文字符串截取函数
2007/02/14 PHP
用穿越火线快速入门php面向对象
2012/02/22 PHP
关于php正则匹配汉字的方法介绍
2013/04/25 PHP
php实现TCP端口检测的方法
2015/04/01 PHP
Js四则运算函数代码
2012/07/21 Javascript
jQuery下实现等待指定元素加载完毕(可改成纯js版)
2013/07/11 Javascript
Js 去掉字符串中的空格(实现代码)
2013/11/19 Javascript
Express作者TJ告别Node.js奔向Go
2014/07/14 Javascript
正则表达式优化JSON字符串的技巧
2015/12/24 Javascript
多个js毫秒倒计时同时进行效果
2016/01/05 Javascript
jQuery抛物线运动实现方法(附完整demo源码下载)
2016/01/08 Javascript
javascript HTML+CSS实现经典橙色导航菜单
2016/02/16 Javascript
Node.js中JavaScript操作MySQL的常用方法整理
2016/03/01 Javascript
jQuery Mobile和HTML5开发App推广注册页
2016/11/07 Javascript
浅谈js函数的多种定义方法与区别
2016/11/29 Javascript
vuejs2.0实现分页组件使用$emit进行事件监听数据传递的方法
2017/02/22 Javascript
Vue.js实现移动端短信验证码功能
2017/03/29 Javascript
记一次vue-webpack项目优化实践详解
2019/02/17 Javascript
cordova+vue+webapp使用html5获取地理位置的方法
2019/07/06 Javascript
jquery ui 实现 tab标签功能示例【测试可用】
2019/07/25 jQuery
小程序卡片切换效果组件wxCardSwiper的实现
2020/02/13 Javascript
Python读写unicode文件的方法
2015/07/10 Python
Python 爬虫爬取指定博客的所有文章
2016/02/17 Python
python使用PyCharm进行远程开发和调试
2017/11/02 Python
Python的地形三维可视化Matplotlib和gdal使用实例
2017/12/09 Python
将tensorflow.Variable中的某些元素取出组成一个新的矩阵示例
2020/01/04 Python
python处理RSTP视频流过程解析
2020/01/11 Python
html5使用canvas绘制一张图片
2014/12/15 HTML / CSS
Whittard官方海外旗舰店:英国百年茶叶品牌
2018/02/22 全球购物
意大利制造的西装、衬衫和针对男士量身定制的服装:Lanieri
2018/04/08 全球购物
物业门卫岗位职责
2013/12/28 职场文书
如何写自我评价?自我评价写什么好?
2014/03/14 职场文书
班子成员四风问题自我剖析材料
2014/09/29 职场文书
追悼会答谢词
2015/01/05 职场文书
python实现进度条的多种实现
2021/04/29 Python
Win11 BitLocker 驱动器加密
2022/04/19 数码科技