用python制作图书管理系统,包含前端用户界面和后端管理员界面的代码
时间: 2023-06-13 19:06:49 浏览: 127
python搭建一个图书管理系统
这是一个基于Python Flask框架的简单图书管理系统的代码示例,包括了一个前端用户界面和一个后端管理员界面。
前端用户界面:
```python
from flask import Flask, render_template, request
import sqlite3
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/search', methods=['POST'])
def search():
book_title = request.form['book_title']
conn = sqlite3.connect('books.db')
c = conn.cursor()
c.execute("SELECT * FROM books WHERE title LIKE ?", ('%'+book_title+'%',))
books = c.fetchall()
conn.close()
return render_template('search.html', books=books)
if __name__ == '__main__':
app.run(debug=True)
```
前端用户界面的HTML模板:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图书搜索</title>
</head>
<body>
<h1>图书搜索</h1>
<form method="post" action="/search">
<label for="book_title">书名:</label>
<input type="text" name="book_title" id="book_title">
<input type="submit" value="搜索">
</form>
</body>
</html>
```
后端管理员界面:
```python
from flask import Flask, render_template, request, redirect
import sqlite3
app = Flask(__name__)
@app.route('/')
def home():
conn = sqlite3.connect('books.db')
c = conn.cursor()
c.execute("SELECT * FROM books")
books = c.fetchall()
conn.close()
return render_template('home.html', books=books)
@app.route('/add', methods=['POST'])
def add_book():
title = request.form['title']
author = request.form['author']
isbn = request.form['isbn']
conn = sqlite3.connect('books.db')
c = conn.cursor()
c.execute("INSERT INTO books (title, author, isbn) VALUES (?, ?, ?)", (title, author, isbn))
conn.commit()
conn.close()
return redirect('/')
@app.route('/delete/<int:id>')
def delete_book(id):
conn = sqlite3.connect('books.db')
c = conn.cursor()
c.execute("DELETE FROM books WHERE id=?", (id,))
conn.commit()
conn.close()
return redirect('/')
if __name__ == '__main__':
app.run(debug=True)
```
后端管理员界面的HTML模板:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图书管理</title>
</head>
<body>
<h1>图书管理</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>书名</th>
<th>作者</th>
<th>ISBN</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for book in books %}
<tr>
<td>{{ book[0] }}</td>
<td>{{ book[1] }}</td>
<td>{{ book[2] }}</td>
<td>{{ book[3] }}</td>
<td><a href="/delete/{{ book[0] }}">删除</a></td>
</tr>
{% endfor %}
</tbody>
</table>
<form method="post" action="/add">
<label for="title">书名:</label>
<input type="text" name="title" id="title"><br>
<label for="author">作者:</label>
<input type="text" name="author" id="author"><br>
<label for="isbn">ISBN:</label>
<input type="text" name="isbn" id="isbn"><br>
<input type="submit" value="添加">
</form>
</body>
</html>
```
注意:以上代码中使用了SQLite3作为数据库,可以根据需要替换为其他数据库。此外,代码中未包含安全措施,请勿用于生产环境。
阅读全文