使用flask框架写一个简单的图书馆管理系统的demo,数据库使用postgresql——简易版
以下是一个使用Flask框架和PostgreSQL数据库创建的简易图书馆管理系统的核心代码示例。请注意,这个示例并不完整,仅包含了一些核心功能,比如图书的增删改查。
from flask import Flask, render_template, request, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://username:password@localhost/library_system'
db = SQLAlchemy(app)
class Book(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
author = db.Column(db.String(50), nullable=False)
year_published = db.Column(db.Integer, nullable=False)
def __repr__(self):
return f"<Book '{self.title}'>"
@app.route('/')
def index():
books = Book.query.all()
return render_template('index.html', books=books)
@app.route('/add-book', methods=['POST'])
def add_book():
title = request.form['title']
author = request.form['author']
year_published = request.form['year_published']
book = Book(title=title, author=author, year_published=year_published)
db.session.add(book)
db.session.commit()
flash('Book added successfully!')
return redirect(url_for('index'))
@app.route('/delete-book/<int:book_id>')
def delete_book(book_id):
book = Book.query.get_or_404(book_id)
db.session.delete(book)
db.session.commit()
flash('Book deleted successfully!')
return redirect(url_for('index'))
@app.route('/edit-book/<int:book_id>', methods=['POST'])
def edit_book(book_id):
book = Book.query.get_or_404(book_id)
book.title = request.form['title']
book.author = request.form['author']
book.year_published = request.form['year_published']
db.session.commit()
flash('Book updated successfully!')
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
在这个例子中,我们定义了一个Book
模型,并在数据库中创建了相应的表。我们实现了添加、删除和编辑图书的简单功能。这个系统非常基础,主要用于演示如何与数据库交互。在实际应用中,你可能需要添加更多的功能,例如借阅历史、借书提醒、图书类型分类等。
评论已关闭