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 相关文章推荐
使用setup.py安装python包和卸载python包的方法
Nov 27 Python
Python虚拟环境Virtualenv使用教程
May 18 Python
Python程序员面试题 你必须提前准备!(答案及解析)
Jan 23 Python
对Python中创建进程的两种方式以及进程池详解
Jan 14 Python
python定时按日期备份MySQL数据并压缩
Apr 19 Python
Python 操作 ElasticSearch的完整代码
Aug 04 Python
python通过SSH登陆linux并操作的实现
Oct 10 Python
python pygame实现滚动横版射击游戏城市之战
Nov 25 Python
Python3中configparser模块读写ini文件并解析配置的用法详解
Feb 18 Python
基于pygame实现童年掌机打砖块游戏
Feb 25 Python
使用Jupyter notebooks上传文件夹或大量数据到服务器
Apr 14 Python
python实现暗通道去雾算法的示例
Sep 27 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
上海永华YH-R296(华普R-96)12波段立体声收音机的分析和打理
2021/03/02 无线电
?算你??的 PHP 程式大小
2006/12/06 PHP
五个PHP程序员工具
2008/05/26 PHP
ThinkPHP 连接Oracle数据库的详细教程[全]
2012/07/16 PHP
使用php判断浏览器的类型和语言的函数代码
2013/02/28 PHP
Windows下的PHP安装文件线程安全和非线程安全的区别
2014/04/23 PHP
destoon实现不同会员组公司名称显示不同的颜色的方法
2014/08/22 PHP
php验证码的制作思路和实现方法
2015/11/12 PHP
解析WordPress中的post_class与get_post_class函数
2016/01/04 PHP
微信开发之php表单微信中自动提交两次问题解决办法
2017/01/08 PHP
Javascript打印网页部分内容的脚本
2008/11/17 Javascript
javascript this用法小结
2008/12/19 Javascript
不提示直接关闭网页窗口的JS示例代码
2013/12/17 Javascript
js 与 php 通过json数据进行通讯示例
2014/03/26 Javascript
jquery动画效果学习笔记(8种效果)
2015/11/13 Javascript
两种方法解决javascript url post 特殊字符转义 + &amp; #
2016/04/13 Javascript
jquery广告无缝轮播实例
2017/01/05 Javascript
JavaScript订单操作小程序完整版
2017/06/23 Javascript
vue.js路由跳转详解
2017/08/28 Javascript
js实现登录与注册界面
2017/11/01 Javascript
详解Vue 中 extend 、component 、mixins 、extends 的区别
2017/12/20 Javascript
Vue入门之数据绑定(小结)
2018/01/08 Javascript
Python计算一个文件里字数的方法
2015/06/15 Python
详解Django缓存处理中Vary头部的使用
2015/07/24 Python
浅述python中argsort()函数的实例用法
2017/03/30 Python
Python操作Sqlite正确实现方法解析
2020/02/05 Python
Python常用类型转换实现代码实例
2020/07/28 Python
一些常用的HTML5模式(pattern) 总结
2015/07/14 HTML / CSS
压铸汽车模型收藏家:Diecastmodelswholesale.com
2016/12/21 全球购物
阿联酋航空官方网站:Emirates
2017/10/17 全球购物
办公室文员工作职责
2014/01/31 职场文书
村庄环境整治方案
2014/05/15 职场文书
公务员四风问题对照检查材料整改措施
2014/09/26 职场文书
学校领导干部民主生活会整改方案
2014/09/29 职场文书
文案策划岗位职责
2015/02/11 职场文书
产品调价通知函
2015/04/20 职场文书