回顾:上一节,我们已经把OpneAI返回的图片显示到网页界面了,本节我们将添加一个"下载"按钮,单击后,将文件保存到本地。跳转到上一节
1. 先修改Html文件,添加一个button。
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<form action="/" method="post">
<input type="text" name="desc" placeholder="请输入描述信息">
<button>创作图画button>
form>
<div>
{% if result %}
<img src="{{ result }}" alt="">
<div>
<a href="/download?img_url={{result|urlencode}}"><button>下载button>a>
div>
{% endif %}
div>
body>
html>
2. 后端代码修改如下:
from flask import Flask, render_template, request, redirect, url_for, make_response
import openai
import requests
from uuid import uuid1 # 防止文件名重复,或者可以时间戳
api_key = "sk-e4F4owyBicdBYKA9RuuM*" # 此处是自己的API Key
openai.api_key = api_key
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
# 接收POST请求
if request.method == 'POST': # 接收表单处理
desc = request.form['desc']
print(desc)
# 此处为OpenAI的API代码
response = openai.Image.create(
prompt=desc,
n=1,
size="512x512"
)
image_url = response['data'][0]['url']
print(image_url)
return redirect(url_for('index', result=image_url)) # 跳转到当前界面下,并将image_url返回到页面中
# 接收GET请求
elif request.method == 'GET': # 接收表单处理
result = request.args.get("result")
return render_template('index.html', result=result)
@app.route('/download/')
def download():
# 获取url
img_url = request.args.get('img_url') # 获取url地址
res = requests.get(img_url) # 得到一个响应
if res.status_code != 200: # 检查响应,成功时应该是200
return "请求失败!"
# 1. 根据url爬取照片,获取图片二进制文件res = requests.get(url)
response = make_response(res.content) #
# 2. 保存文件,类型为图片
response.headers['Content-Type'] = 'image/png'
response.headers['Content-Disposition'] = f"attachment;filename={uuid1()}.png"
return response
@app.route('/debug')
def debug():
return 'I am Demo.'
if __name__ == '__main__':
app.run(debug=True, port=8888)
3. 运行代码后,效果下图。单击下载按钮后,会随机生成一个名字并下载到本地。
4. 下一节,我们将对界面进行美化,添加CSS。未完待续,敬请期待~