帮我生成一个用Python 实现的 web图书管理系统,数据保存在csv文件中,该系统主要包含 以下功能:
1: 在线添加书籍信息功能
2: 在线修改书籍信息功能
3: 在线查询所有书籍信息功能
并且提供好看的CSS 样式,以及js 代码
app.py
from flask import Flask, render_template, request, redirect, url_for
import csv
app = Flask(__name__)
CSV_FILE = 'books.csv'
def read_books():
books = []
try:
with open(CSV_FILE, mode='r', newline='', encoding='utf-8') as file:
reader = csv.DictReader(file)
books = list(reader)
except FileNotFoundError:
pass
return books
def write_books(books):
with open(CSV_FILE, mode='w', newline='', encoding='utf-8') as file:
fieldnames = ['id', 'title', 'author', 'year', 'isbn']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(books)
@app.route('/', methods=['GET', 'POST'])
def index():
books = read_books()
if request.method == 'POST':
new_book = {
'id': str(len(books) + 1),
'title': request.form['title'],
'author': request.form['author'],
'year': request.form['year'],
'isbn': request.form['isbn']
}
books.append(new_book)
write_books(books)
return redirect(url_for('index'))
return render_template('index.html', books=books)
@app.route('/edit/<book_id>', methods=['POST'])
def edit(book_id):
books = read_books()
for book in books:
if book['id'] == book_id:
book['title'] = request.form['title']
book['author'] = request.form['author']
book['year'] = request.form['year']
book['isbn'] = request.form['isbn']
break
write_books(books)
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
books.csv
初始是一个空文件,第一个请求时填充内容。
id,title,author,year,isbn
1,Python编程,张三,2020,
2,JavaScript教程,李四,2019,
3,Flask开发指南,王五,2021,
4,woasd,asdf,2024,asdf
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Book Manager</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Book Manager</h1>
<form action="/" method="post">
<input type="text" name="title" placeholder="Title" required>
<input type="text" name="author" placeholder="Author" required>
<input type="text" name="year" placeholder="Year" required>
<input type="text" name="isbn" placeholder="ISBN" required>
<button type="submit">Add Book</button>
</form>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>ISBN</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for book in books %}
<tr>
<td>{{ book.id }}</td>
<td>{{ book.title }}</td>
<td>{{ book.author }}</td>
<td>{{ book.year }}</td>
<td>{{ book.isbn }}</td>
<td>
<button onclick="editBook('{{ book.id }}')">Edit</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<script src="{{ url_for('static', filename='script.js') }}"></script>
</body>
</html>
style.css
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1 {
color: #333;
}
form, table {
margin-top: 20px;
}
input {
margin: 5px;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
padding: 8px 12px;
background-color: #28a745;
border: none;
color: white;
cursor: pointer;
border-radius: 4px;
}
button:hover {
background-color: #218838;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 10px;
}
th, td {
padding: 12px;
border: 1px solid #ddd;
text-align: left;
}
th {
background-color: #f4f4f4;
}
script.js
function editBook(bookId) {
const row = document.querySelector(`tr:nth-child(${parseInt(bookId) + 1})`);
const title = prompt("Edit Title:", row.cells[1].innerText);
const author = prompt("Edit Author:", row.cells[2].innerText);
const year = prompt("Edit Year:", row.cells[3].innerText);
const isbn = prompt("Edit ISBN:", row.cells[4].innerText);
if (title && author && year && isbn) {
fetch(`/edit/${bookId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `title=${encodeURIComponent(title)}&author=${encodeURIComponent(author)}&year=${encodeURIComponent(year)}&isbn=${encodeURIComponent(isbn)}`
}).then(() => location.reload());
}
}
运行项目
- 确保已安装 Python 和 Flask(如果没有安装 Flask,请运行
pip install flask
)。 - 在终端中导航至项目目录并运行
python app.py
。 - 在浏览器中打开
http://127.0.0.1:5000
,就可以使用该系统了。
这个示例提供了基本的操作功能,你可以根据需要扩展数据库功能、增加更多的字段和验证等。
欢迎来撩 : 汇总all