经过16天的学习,虽然每天只听一节课,也在用真正的实例去操作,只有从这些实例中,文科生才能找到学习的意义,甚至,才能读懂python代码。
我首先想到的就是如何通过python写一个日记本。
要使用 Python 编写一个能在网页上打开的日记本,可以使用 Flask 框架来搭建 Web 应用,结合 SQLite 数据库来存储日记内容。
以下是一个简单的示例代码:
首先,确保你已经安装了 Flask 和 SQLite3。如果没有安装,可以使用以下命令进行安装:
pip install flask
然后,编写 Python 代码如下:
from flask import Flask, render_template, request, redirect, url_for
import sqlite3
app = Flask(__name__)
# 创建数据库和表
def create_database():
conn = sqlite3.connect('diary.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
content TEXT NOT NULL,
date TEXT NOT NULL
)
''')
conn.commit()
conn.close()
# 首页,显示所有日记
@app.route('/')
def index():
conn = sqlite3.connect('diary.db')
cursor = conn.cursor()
cursor.execute('SELECT * FROM entries ORDER BY id DESC')
entries = cursor.fetchall()
conn.close()
return render_template('index.html', entries=entries)
# 新建日记页面
@app.route('/new', methods=['GET', 'POST'])
def new():
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
from datetime import datetime
date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
conn = sqlite3.connect('diary.db')
cursor = conn.cursor()
cursor.execute('INSERT INTO entries (title, content, date) VALUES (?,?,?)', (title, content, date))
conn.commit()
conn.close()
return redirect(url_for('index'))
return render_template('new.html')
# 查看日记详情页面
@app.route('/entry/<int:entry_id>')
def entry(entry_id):
conn = sqlite3.connect('diary.db')
cursor = conn.cursor()
cursor.execute('SELECT * FROM entries WHERE id =?', (entry_id,))
entry = cursor.fetchone()
conn.close()
if entry:
return render_template('entry.html', entry=entry)
else:
return "Entry not found", 404
# 编辑日记页面
@app.route('/edit/<int:entry_id>', methods=['GET', 'POST'])
def edit(entry_id):
conn = sqlite3.connect('diary.db')
cursor = conn.cursor()
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
from datetime import datetime
date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
cursor.execute('UPDATE entries SET title =?, content =?, date =? WHERE id =?',
(title, content, date, entry_id))
conn.commit()
conn.close()
return redirect(url_for('index'))
cursor.execute('SELECT * FROM entries WHERE id =?', (entry_id,))
entry = cursor.fetchone()
conn.close()
if entry:
return render_template('edit.html', entry=entry)
else:
return "Entry not found", 404
# 删除日记
@app.route('/delete/<int:entry_id>')
def delete(entry_id):
conn = sqlite3.connect('diary.db')
cursor = conn.cursor()
cursor.execute('DELETE FROM entries WHERE id =?', (entry_id,))
conn.commit()
conn.close()
return redirect(url_for('index'))
if __name__ == '__main__':
create_database()
app.run(debug=True)
接下来,需要创建 HTML 模板文件来显示页面。在项目目录下创建一个名为templates
的文件夹,并在其中创建以下文件:(这一步至关重要)
index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>我的日记本</title>
<style>
body {
font-family: Arial, sans-serif;
}
.entry {
border: 1px solid #ccc;
padding: 10px;
margin: 10px;
border-radius: 5px;
}
.entry h2 {
margin-top: 0;
}
.entry p {
color: #666;
}
</style>
</head>
<body>
<h1>我的日记本</h1>
<a href="{{ url_for('new') }}">新建日记</a>
{% for entry in entries %}
<div class="entry">
<h2>{{ entry[1] }}</h2>
<p>{{ entry[3] }}</p>
<p>{{ entry[2] }}</p>
<a href="{{ url_for('entry', entry_id=entry[0]) }}">查看详情</a>
<a href="{{ url_for('edit', entry_id=entry[0]) }}">编辑</a>
<a href="{{ url_for('delete', entry_id=entry[0]) }}" onclick="return confirm('确定删除此日记?')">删除</a>
</div>
{% endfor %}
</body>
</html>
new.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>新建日记</title>
<style>
body {
font-family: Arial, sans-serif;
}
form {
width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
form label {
display: block;
margin-bottom: 5px;
}
form input,
form textarea {
width: 100%;
padding: 8px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 3px;
}
form button {
padding: 10px 20px;
background-color: #007BFF;
color: white;
border: none;
border-radius: 3px;
cursor: pointer;
}
form button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<h1>新建日记</h1>
<form method="post">
<label for="title">标题</label>
<input type="text" id="title" name="title" required>
<label for="content">内容</label>
<textarea id="content" name="content" required></textarea>
<button type="submit">保存</button>
</form>
</body>
</html>
entry.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{{ entry[1] }}</title>
<style>
body {
font-family: Arial, sans-serif;
}
.entry {
border: 1px solid #ccc;
padding: 20px;
margin: 20px;
border-radius: 5px;
}
.entry h1 {
margin-top: 0;
}
.entry p {
color: #666;
}
</style>
</head>
<body>
<div class="entry">
<h1>{{ entry[1] }}</h1>
<p>{{ entry[3] }}</p>
<p>{{ entry[2] }}</p>
<a href="{{ url_for('index') }}">返回列表</a>
</div>
</body>
</html>
edit.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>编辑日记</title>
<style>
body {
font-family: Arial, sans-serif;
}
form {
width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
form label {
display: block;
margin-bottom: 5px;
}
form input,
form textarea {
width: 100%;
padding: 8px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 3px;
}
form button {
padding: 10px 20px;
background-color: #007BFF;
color: white;
border: none;
border-radius: 3px;
cursor: pointer;
}
form button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<h1>编辑日记</h1>
<form method="post">
<label for="title">标题</label>
<input type="text" id="title" name="title" value="{{ entry[1] }}" required>
<label for="content">内容</label>
<textarea id="content" name="content" required>{{ entry[2] }}</textarea>
<button type="submit">保存</button>
</form>
</body>
</html>
这个示例代码创建了一个简单的日记本应用,包含新建、查看、编辑和删除日记的功能。运行 Python 脚本后,在浏览器中访问http://127.0.0.1:5000/
即可使用日记本。