阅读 2802

【玩】68+98 开发图片共享平台

MedusaSorcerer的博客


七月,任何好运都会如【七】而至

标题没有什么新颖或醒目的字样, 68 行 Python 代码和 98 行 HTML 代码, 带你开发一个图片共享的小网站, 当然了, 如果你想开发的更完善, 你可以再现有的基础上进行继续开发。

Python Code

#!/usr/bin/env python
# _*_ Coding: UTF-8 _*_
import os
import re
import socket
import uuid

from flask import Flask, make_response, render_template, redirect, request

app = Flask(__name__, template_folder='./', static_folder="", static_url_path="")


def get_host_ip():
    skt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        skt.connect(('8.8.8.8', 80))
        return skt.getsockname()[0]
    except (Exception,):
        return '127.0.0.1'
    finally:
        skt.close()


@app.route('/')
def index():
    def __get_files(file_path):
        dir_list = os.listdir(file_path)
        if not dir_list: return []
        return sorted(dir_list, key=lambda x: os.path.getmtime(os.path.join(file_path, x)), reverse=True)

    string = ''
    for i, v in enumerate(__get_files(photo_path)):
        if re.search(rf'.+{photo_type}$', v, re.IGNORECASE):
            string += f"""<p align="center"><a href="http://{host_ip}:{port}/{v}" target="_self">{i + 1}. {v}</a></p>"""
    return render_template('index.html', paths=string, host=host_ip, port=port)


@app.route('/<string:filename>', methods=['GET'])
def photo(filename):
    file_dir = rf'{photo_path}/{filename}'
    if os.path.isfile(file_dir) is False: return redirect('/')
    response = make_response(open(file_dir, "rb").read())
    response.headers['Content-Type'] = 'image/png'
    return response


@app.route('/upload', methods=['POST'])
def upload():
    file = request.files.get('photo')
    if re.search(rf'.+{photo_type}$', file.filename, re.IGNORECASE):
        file.save(rf'{photo_path}/{uuid.uuid1()}.{str(file.filename).split(".")[-1]}')
    file.close()
    return redirect('/')


if __name__ == '__main__':
    # Configure
    host_ip = get_host_ip()
    photo_path = r'C:\image'
    host = '0.0.0.0'
    port = 1234
    debug = False
    photo_type = ('gif', 'png', 'svg', 'jpeg', 'jpg')

    print(f' * Homepage: http://{host_ip}:{port}/')
    photo_type = '|'.join([rf'(\.{i})' for i in photo_type])
    app.run(debug=debug, host=host, port=port)
复制代码

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Medusa Image</title>
    <style>
        html, body {
            padding: 0;
            margin: 0;
            overflow-y: hidden;
            height: 100%;
            width: 100%;
        }

        a {
            text-decoration: none;
            color: darkorange;
        }

        a:hover {
            color: #F00;
            background-color: rgba(220, 220, 220, 0.1);
        }

        .base {
            padding-top: 60px;
            height: 90%;
            overflow-y: scroll;
            margin-left: 100px;
        }

        .base::-webkit-scrollbar {
            display: none;
        }

        .from {
            float: right;
            margin-top: 20px;
        }

        #input1 {
            margin-left: -92px;
            position: relative;
            display: inline-block;
            border: 1px solid #7d7878;
            padding: 2px 8px;
            overflow: hidden;
            text-decoration: none;
            line-height: 20px;
            text-align-last: center;
            width: 70px;
            opacity: 0;
        }

        #input2 {
            width: 90px;
            height: 30px;
        }

        .input-file, #input2 {
            background: #7d7878;
            margin: 5px 5px 5px 5px;
            color: bisque;
            border-radius: 10px;
            font-size: 10px;
            text-align: center;
        }

        body {
            background: url("http://pic1.win4000.com/wallpaper/8/58578b04b18a0.jpg") !important;
        }
    </style>
</head>
<body>
<div class="from">
    <form method="post" action="http://{{ host }}:{{ port }}/upload" enctype="multipart/form-data">
        <div class="input-file">
            <span>
                选择图片
            </span>
            <input id="input1" type="file" size="30" name="photo"/>
        </div>
        <input id="input2" type="submit" value="上传图片" class="button-new"/>
    </form>
</div>
<div class="base">
    {{ paths|safe }}
</div>
</body>
</html>
复制代码

说明和配置

注意看颜色标记处

  • photo_path 你需要共享/保存共享的图片文件夹路径
  • host 服务开启的访问模式, 0.0.0.0 会开启局域网访问, 127.0.0.1 将只开启本地访问
  • port 服务开启的端口号
  • debug Debug 模式是否开启的布尔值
  • photo_type 图片格式白名单, 已忽略大小写, 使用的正则匹配

启动

注意, 你保存的 .py.html 文件需要在同一文件夹下。

访问

在启动日志中你可以看到你的主页地址:

* Homepage: http://xxx:1234/
复制代码

你可以直接访问这个地址

完成~

ps: 当前支支持 Google 浏览器哦,没有做兼容

文章分类
代码人生
文章标签