首页 > 解决方案 > 如何使用python在休息响应中显示动态创建的动画gif?

问题描述

我正在项目中动态创建一个 gif。

当调用 url 时,会创建 gif 并且页面加载正常,但问题是由于某种原因在页面内加载动画 gif 给我404 NotFound。

我从 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 -

标签: pythonhtmlrestflaskanimated-gif

解决方案


没关系,只需为烧瓶的文档确认你有静态文件夹的实例,所以我替换了这一行

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/


推荐阅读