In July, any good fortune will follow [seven]

There’s nothing new or eye-catching in the title, 68 lines of Python code and 98 lines of HTML code, and you can develop a small website for image sharing. Of course, if you want to develop it better, you can reproduce it and build on it.

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)
Copy the code

HTML Code

<! DOCTYPEhtml>
<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>Choose picture</span>
            <input id="input1" type="file" size="30" name="photo"/>
        </div>
        <input id="input2" type="submit" value="Upload picture" class="button-new"/>
    </form>
</div>
<div class="base">
    {{ paths|safe }}
</div>
</body>
</html>
Copy the code

Description and Configuration

Pay attention to the color marks

  • photo_pathYou need to share/save the shared image folder path
  • hostThe access mode enabled by the service,0.0.0.0Will enable LAN access,127.0.0.1Only local access will be enabled
  • portPort number on which the service is enabled
  • debugDebug Boolean value of whether the mode is enabled
  • photo_typeImage format whitelist, has ignored case, using the re match

Start the

Be careful what you save.py.htmlThe files must be in the same folder.

access

In the startup log you can see your home page address:

* Homepage: http://xxx:1234/
Copy the code

You can access this address directly

Complete the ~

Ps: the current support for Google Browser oh, not compatible