看到有人问,发一个我自己在用的。
import json
import random
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
from pathlib import *
import os
IMAGE_LIST = []
def search_dicts_by_key_value(dict_list, key, value):
result = []
for d in dict_list:
if key in d and d[key] == value:
result.append(d)
return result
def search_dicts_by_value(dict_list, value):
result = []
for d in dict_list:
if value in d.values():
result.append(d)
return result
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
# 解析URL中的查询字符串
query = parse_qs(urlparse(self.path).query)
path = self.path
if path.startswith("/random/") :
# 获取参数值
cat = query.get('cat', [''])[0]
format = query.get('format', [''])[0]
image = IMAGE_LIST[random.randint(0, len(IMAGE_LIST) - 1)]
if cat and cat is not None :
cat = "/statics/" + cat
cat_image_list = search_dicts_by_key_value(IMAGE_LIST,'path', cat)
if not cat_image_list:
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(bytes("<html><head><title>Random Image Server</title></head>", "utf-8"))
self.wfile.write(bytes("<body><p>Invalid cat</p>", "utf-8"))
return
image = cat_image_list[random.randint(0, len(cat_image_list) -1)]
print(image)
new_path = '%s%s/%s' % ('', image['path'], image['name'])
if format and format.lower() == 'json':
self.send_response(200)
self.send_header("Content-type", "text/html;charset=utf-8")
self.end_headers()
buf = {"status": 0,
"image": new_path} # 返回文件下载地址(点击下载地址是个get请求)
self.wfile.write(json.dumps(buf).encode())
else:
self.send_response(302)
self.send_header('Location', new_path)
self.end_headers()
else:
# 构造响应
self.send_response(301)
self.send_header('Location', 'https://nai.dog')
self.end_headers()
def init_image_list():
p = os.path.abspath(__file__)
p = os.getcwd()
print('Server path = ',p)
path = Path(p+'/statics')
for file in path.rglob("*.*"):
fp = str(file.parent).replace(p, '')
try:
ext = str(file.name).split('.')[-1].lower()
if ext in ['jpg', 'png', 'webp', 'gif']:
info = {'path':fp,
'name':file.name}
IMAGE_LIST.append(info)
except:
pass
print('Total image counts: ',len(IMAGE_LIST))
if __name__ == '__main__':
# 启动HTTP服务器
print('*' * 100)
print('Random Image Server v1.0 alpha')
print('obaby@mars')
print('https://oba.by')
print('Init server configuration')
init_image_list()
server_address = ('', 10010)
httpd = HTTPServer(server_address, MyHandler)
print('Starting server...')
httpd.serve_forever()
文件放到statics目录下,如果要建分类在下面新建分类文件夹,图片放到子文件夹下即可。支持直接返回图片或者反悔json格式数据。