With the rapid development of the internet, Content Management Systems (CMS) have become an indispensable part of web development. Among them, image management functionality is one of the most common and important modules. Through image management, developers can easily upload, delete, edit, and display images on their website. In this article, we will demonstrate how to use Python to create a simple image management feature in a CMS system, including the necessary code examples.
python -m venv myenv
Next, we implement the image upload functionality. The user selects and uploads an image, which is saved to the local uploads directory. The image title and filename are saved to the database.
@app.route('/upload', methods=['POST']) def upload(): file = request.files.get("image") if file: img = Image.open(file) img.save("uploads/" + file.filename) image = Image(title=request.form.get("title"), filename=file.filename) db.session.add(image) db.session.commit() return "Upload successful!" else: return "Upload failed!"
Now, we implement the image display functionality. Users can view all uploaded images by visiting the /images URL and click on a single image to see its details.
@app.route('/images') def images(): images = Image.query.all() return render_template('images.html', images=images)
@app.route('/image/<int:image_id>') def image_detail(image_id): image = Image.query.get(image_id) return render_template('image_detail.html', image=image)
Finally, we add the image deletion feature. Users can click the "Delete" button on the page to remove a specific image.
@app.route('/delete/<int:image_id>') def delete_image(image_id): image = Image.query.get(image_id) db.session.delete(image) db.session.commit() return redirect('/images')
To enhance the user experience, you can include appropriate HTML and CSS on the front-end and use the Jinja2 template engine to render dynamic content.
With the code examples provided, we’ve demonstrated how to implement the image management functionality in a CMS system using Python and Flask. This is just a simple example, and real-world CMS systems may require additional features and complex logic. We hope this article has inspired developers to explore CMS image management solutions and continue to improve their skills in web development.