如何在Python的REST响应中动态显示创建的动画GIF?

2024-05-13 01:10:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在项目中动态创建一个gif。你知道吗

调用url时,会创建gif,页面加载正常,但问题是,由于某种原因,在页面中加载动画gif会使我404找不到。你知道吗

我从get方法中的URL获取参数。 我试过了。你有什么建议吗?你知道吗

def create_image_with_ball(width, height, ball_x, ball_y, ball_size):
    img = Image.new('RGB', (width, height), (255, 255, 255))
    draw = ImageDraw.Draw(img)
    # draw.ellipse takes a 4-tuple (x0, y0, x1, y1) where (x0, y0) is the top-left bound of the box
    # and (x1, y1) is the lower-right bound of the box.
    draw.ellipse((ball_x, ball_y, ball_x + ball_size, ball_y + ball_size), fill='red')
    return img


app = Flask(__name__, template_folder='templates') #../{{ user_image }}


app.config['UPLOAD_FOLDER'] = GIF_FOLDER

@app.route('/')
@app.route('/getpixel')
def get_meth():
    invoice_num = request.args.get('invoice_num')
    frames = []
    x, y = 0, 0
    for i in range(5):
        new_frame = create_image_with_ball(10, 10, x, y, 40)
        frames.append(new_frame)
        x += 40
        y += 40
    frames[0].save('.\gif_created\inv_im_open_'+invoice_num+'.gif', format='GIF', append_images=frames[1:], save_all=True, duration=100, loop=0 )
    #full_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'inv_im_open_'+invoice_num+'.gif')
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'],'inv_im_open_' + invoice_num + '.gif')
    print(app.config['UPLOAD_FOLDER'])
    print(os.path.curdir)
    return 'NO data' if invoice_num is None else render_template("index.html", user_image = full_filename)
app.run(host='0.0.0.0', port=5000)

网页如下所示:

<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
</head>
<body>
    <img src="{{user_image}}" alt="{{ user_image }}">
</body>
</html>

正如我之前所说,页面加载很好,问题是当应用程序加载在目录中创建的gif时。你知道吗

127.0.0.1 - - [13/Sep/2019 09:38:01] "GET /getpixel?invoice_num=2136 HTTP/1.1" 200 -
127.0.0.1 - - [13/Sep/2019 09:38:01] "GET /gif_created/inv_im_open_2136.gif HTTP/1.1" 404 -

Tags: theimageconfigappimgframesinvoicefolder
1条回答
网友
1楼 · 发布于 2024-05-13 01:10:36

没关系,只需为flask的doc realess你有静态文件夹的实例,所以我替换这一行

app = Flask(__name__, template_folder='templates') 

为此:

app = Flask(__name__, template_folder='templates', static_folder ='gif_created')

更多信息请参见: https://flask.palletsprojects.com/en/1.1.x/api/

相关问题 更多 >