With the rapid development of the internet, content management systems (CMS) have become an essential part of web development. Among them, the image management feature is a crucial and common module. With image management functionality, users can easily upload, delete, edit, and display images on their websites. This article will demonstrate how to implement a simple image management feature in a CMS system using Python, providing corresponding code examples.
python -m venv myenv
Next, let's implement the image upload feature. When a user uploads an image from the front-end, the backend receives the image, saves it to the local "uploads" directory, and stores the title and filename in 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!"
Then, we need to implement the image display feature. Users can view all saved images by visiting the /images path, and they can click on an image to view 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, let's implement the image deletion feature. Users can delete a specific image by clicking the "Delete" button on the page.
@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 provide a better user experience, the front-end page should include appropriate HTML and CSS code, and we can use the Jinja2 templating engine to render dynamic content.
<!-- images.html --> {% for image in images %} <div> <a href="{{ url_for('image_detail', image_id=image.id) }}">View details</a> <a href="{{ url_for('delete_image', image_id=image.id) }}">Delete</a> </div> {% endfor %}
<!-- image_detail.html --> <h1>{{ image.title }}</h1>
Through the code examples above, we can see how to implement an image management feature in a CMS system using Python. Although this is just a simple example, it demonstrates the basic usage of the Flask framework, SQLAlchemy database tools, and the PIL image processing library. In real-world development, CMS systems may require additional features and more complex logic, and developers can expand and optimize this basic example further.