Web application development based on flask - building a cloud disk

0. Preface

This section uses flask to open the download link

OS: Windows 10 Home Edition

Development environment: Pycahrm Community 2022.3

Python interpreter version: Python3.8

Third-party library: flask humanize

1. Implement open download link

We need to place some resources on the website for everyone to download, so we should place different download links according to the different routing items entered.

I handle it like this:

from flask import Flask,send_file

app = Flask(__name__)

@app.route('/download/<filename>')
def download_file(filename):
    # 实际应用中,这里可以进行文件名、文件类型验证等操作
    return send_file("downloads/{}".format(filename), as_attachment=True)


if __name__ == '__main__':
    # 0.0.0.0代表广播地址,同一局域网的用户都能访问
    # 端口号为5000,设置为专用端口(如80)需要管理员身份
    app.run(host = "0.0.0.0", port = 5000)

For example, when a user accesses http://192.168.31.58:5000/download/embedded Linux application development.pdf , the embedded Linux application development.pdf file under the downloads directory will be downloaded:

Visit the following URL:

http://192.168.31.58:5000/download/嵌入式Linux应用程序开发.pdf

or user input

The download is complete.
insert image description here
You have learned how to provide a download link after seeing the above. Just use the render_template() method to redirect.

2. Modified slightly

I now store a lot of software installation packages on my U disk, which is very helpful for me to replace the system or quickly build a development environment on other people's computers.

Now I want to deploy the code to the server so that I can use these files at any time without a USB flash drive.

This can achieve the effect of a Baidu network disk, but there is no speed limit and no VIP

I first organize the software installation package. My installation package files are all placed in the downloads under the project directory :
insert image description here
then I need to use html to present it. In order to be able to automatically update and the interface is beautiful (no), I also use Jinja2 and css:

This is the navigation interface:
index.html

<!doctype html>
<html>
    <head>
        <title>Index</title>
        <style>
          body {
      
      
                  background-color: #f1f1f1;
                  font-family: Arial, sans-serif;
                }

                p {
      
      
                  margin: 0;
                  padding: 15px;
                  background-color: #fff;
                  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
                }

                a {
      
      
                  color: #555;
                  text-decoration: none;
                  transition: color 0.2s ease-in-out;
                }

                a:hover {
      
      
                  color: #000;
                }

                h1 {
      
      
                  text-align: center;
                }

<!--                以下为居中显示布局-->
<!--                p {
      
      -->
<!--                  text-align: center;-->
<!--                }-->

        </style>
    </head>
    <body>
        <h1>IoT_H2的资源包</h1>
        <title>IoT_H2的资源包</title>
        {% for subdir in sub_dirs %}
        <p>
            <a href="{
     
     { url_for('subdir', sub_dir=subdir) }}">
                {
   
   { subdir }}
            </a>
        </p>
        {% endfor %}
    </body>
</html>

This is the interface for downloading resources:
subdir.html

<!DOCTYPE html>
<html>
  <head>
    <title>Files in {
   
   { sub_dir }}</title>
    <style>
      body {
      
      
        font-family: Arial, sans-serif;
        background-color: #f0f0f0;
        margin: 0;
        padding: 0;
      }
      h1 {
      
      
        text-align: center;
        color: #333;
        margin-top: 30px;
      }
      p {
      
      
        margin: 0;
        padding: 10px;
        background-color: #fff;
        border: 1px solid #ddd;
        border-radius: 5px;
        box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1);
        transition: 0.3s;
      }
      p:hover {
      
      
        background-color: #f5f5f5;
        box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.2);
      }
      a {
      
      
        color: #333;
        text-decoration: none;
        transition: 0.3s;
      }
      a:hover {
      
      
        color: #666;
        text-decoration: underline;
      }
    </style>
  </head>
  <body>
    <h1>{
   
   { sub_dir }}</h1>
    <title>IoT_H2的资源包/{
   
   { sub_dir }}</title>

    {% for file in files %}
      <p><a href="{
     
     { url_for('download_file', filename=sub_dir + '/' + file[0]) }}">{
   
   { file[0] + "-----------" + file[1] }}</a></p>
    {% endfor %}

  </body>
</html>

Then there is the main program:
main.py

from flask import Flask, render_template, abort, send_from_directory
import os
import humanize

app = Flask(__name__)


# 获取文件大小函数
def size(file_path):
    file_size = os.path.getsize(file_path)
    # 将文件大小转换为人类可读格式
    file_size_formatted = humanize.naturalsize(file_size)
    # 返回人类可读格式的文件大小
    return file_size_formatted.replace(" ","")

@app.route('/resource')
def index():
    # 需要展示的目录路径
    dir_path = 'downloads'

    # 检查目录路径是否存在
    if not os.path.exists(dir_path):
        abort(404)

    # 读取所有子目录
    sub_dirs = [d for d in os.listdir(dir_path) if os.path.isdir(os.path.join(dir_path, d))]

    return render_template('index.html', sub_dirs=sub_dirs,title = "IoT_H2的资源包")

@app.route('/resource/<sub_dir>')
def subdir(sub_dir):
    # 需要展示的目录路径
    dir_path = os.path.join('downloads', sub_dir)

    # 检查目录路径是否存在
    if not os.path.exists(dir_path):
        abort(404)

    # 读取目录下的所有文件
    files = [[f,size(dir_path + "/" + f)] for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))]

    return render_template('subdir.html', sub_dir=sub_dir, files=files)

@app.route('/download/<path:filename>')
def download_file(filename):
    # 下载链接所对应的资源存放目录
    directory = 'downloads'
    # 返回下载文件,以附件形式下载
    return send_from_directory(directory, filename, as_attachment=True)



if __name__ == '__main__':
    app.run(host="0.0.0.0",port=80)

3. Effect demonstration

This is the main interface, click to enter the secondary classification:
insert image description here

I clicked on the programming class to enter, and downloaded an Anaconda interpreter, 651M, and it took only 3 seconds to download. Here I criticize a certain network disk by name.
insert image description here

4. Cloud server project deployment

Stepping on the pit: Tencent cloud server SFTP has a file size limit
insert image description here

Although I don't like samba, I still do it:
Install samba file sharing service under Linux

But here I recommend using winscp, it's so easy to use!
Learn from this: File transfer tool WinSCP download and installation tutorial
insert image description here
Wait for the transfer to complete

Install flask and humanize

pip install flask
pip install humanize

insert image description here
Then my server started!
Resource pack for IoT_H2

Go see if there is anything you need!
insert image description here

insert image description here

I forgot that the local test is a local area network...even the loopback address to access myself

The slow batch deployed on the cloud server...

Guess you like

Origin blog.csdn.net/qq_53381910/article/details/131254521