前因
之前用@mikus 的随机图片API给我的文章配封面,但是昨天晚上突然发现他崩了……于是我决定给自己建一个随机图片API服务。
图源
从网上找一个免费图库网站,我用的是Pexels ,支持API调用,API的操作文档也挺清晰的,让我这个不会Coding的入都忍不住美美手写了一段Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 import requestsimport urllib.requestimport jsondef save_image_from_url (url, save_path ): try : opener = urllib.request.build_opener() opener.addheaders = [('User-Agent' , 'Mozilla/5.0' )] urllib.request.install_opener(opener) urllib.request.urlretrieve(url, save_path) print (f"Image saved to {save_path} " ) except Exception as e: print (f"Failed to save image from {url} . Error: {e} " ) def save_image_info (photo, save_file ): with open (save_file, 'r' , encoding='utf-8' ) as f: content = json.load(f) content.append(photo) with open (save_file, 'w' , encoding='utf-8' ) as f: json.dump(content, f, ensure_ascii=False , indent=4 ) per_page = 80 page = 1 API_KEY = "<敏感信息删除!>" URL = f"api.pexels.com/v1/search" query = "cyberpunk" color = "pink" size = "large" params = { "query" : query, "per_page" : per_page, "page" : page, "orientation" : "landscape" , "size" : size, } headers = { "Authorization" : API_KEY } base_path = "D:/homepage/hexo" img_path = f"{base_path} /source/_img" def main (): response = requests.get(f"https://{URL} " , headers=headers, params=params) data = response.json() for photo in data['photos' ]: print (photo['src' ][size]) save_image_from_url( photo['src' ][size], f"{img_path} /{photo['id' ]} .jpg" ) save_image_info(photo, f"{img_path} /info.json" ) if __name__ == "__main__" : main()
API
用这个脚本下了一些图片,接下来第二个问题就是怎么做成API了……当然是Vibe
Coding(目移)毕竟我是笨蛋(目移)
源代码就不放了反正是AI生成的,技术框架大概就是Python
Flask+nohup,虽然很简陋但是能run,API的使用可以看这个页面 喵~
页面入口的话在本页面的上方导航栏(移动端是右侧导航栏)里有~
如果只是想获得随机图片的话就直接访问网址,如果想固定图片的话就在查询里加seed参数就好啦!
希望大家用的开心~