利用Ubuntu实现图床功能

William
2024-05-23 / 0 评论 / 1 阅读 / 正在检测是否收录...

先去 https://discourse.ubuntu.com 注册个账号,图片会被压缩,但不影响质量

from flask import Flask, request, jsonify
import requests
from bs4 import BeautifulSoup
import hashlib

app = Flask(__name__)

# 定义请求头部信息和cookie
headers = {
    "Cookie": "随便注册个账号获取cookie",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"
}

# 获取CSRF令牌
def get_csrf_token():
    url = "https://discourse.ubuntu.com/top?period=weekly"
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, "html.parser")
    csrf_token = soup.find("meta", attrs={"name": "csrf-token"})["content"]
    return csrf_token

# Upload image
def upload_image(file, csrf_token):
    url = "https://discourse.ubuntu.com/uploads.json?client_id=123"
    headers.update({"X-CSRF-Token": csrf_token})

    try:
        # Calculate file's SHA-1 checksum
        sha1 = hashlib.sha1()
        while True:
            data = file.read(65536)  # Read in 64k chunks
            if not data:
                break
            sha1.update(data)
        file.seek(0)  # Reset file pointer after reading

        files = {'file': file}

        data = {
            "upload_type": "composer",
            "pasted": "undefined",
            "name": file.filename,
            "type": file.content_type,
            "sha1_checksum": sha1.hexdigest()
        }

        response = requests.post(url, headers=headers, data=data, files=files)
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        # Log the error or handle it gracefully
        return None

@app.route('/upload', methods=['POST'])
def upload():
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400
    
    csrf_token = get_csrf_token()
    response = upload_image(file, csrf_token)
    
    if 'url' in response:
        return jsonify({"url": response['url']}), 200
    else:
        return jsonify({"error": "URL not found in the response", "response": response}), 400

if __name__ == '__main__':
    app.run(debug=True)

上传方式

curl -X POST -F "file=@/path/to/your/file.jpg" http://localhost:5000/upload

自定义端口

把末尾的app.run(debug=True)
替换成app.run(debug=True, port=8080)

测试图

2024.06.01 好像失效了,图片无法访问了

0

评论 (0)

取消