创建一个具有前端界面的Python-Flask和MySQL项目可以是一项有趣的挑战。假设你已经熟悉了Python的基本语法,HTML的基本知识,以及MySQL的基本操作。为了实践MySQL数据库操作,我们可以创建一个"个人图书馆"程序,用户可以在其中添加、编辑、查看和删除图书。
以下是一个较为详细的步骤指南以及所需的代码示例。
环境搭建
安装Python和pip。
安装Flask:pip install flask
安装MySQL数据库并创建一个新数据库,如library。
安装MySQL连接器:pip install mysql-connector-python
创建数据库
在MySQL中创建一个新表books:
CREATE TABLE books (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author VARCHAR(255) NOT NULL,
isbn VARCHAR(13),
publisher VARCHAR(255)
);
Flask 应用
app.py
from flask import Flask, render_template, request, redirect, url_for
import mysql.connector
app = Flask(__name__)
# Database Configuration
db_config = {
'user': 'root',
'password': 'password',
'host': 'localhost',
'database': 'library'
}
# Initialize MySQL connection
conn = mysql.connector.connect(**db_config)
cursor = conn.cursor(dictionary=True)
@app.route('/')
def index():
cursor.execute("SELECT * FROM books")
books = cursor.fetchall()
return render_template('index.html', books=books)
@app.route('/add', methods=['GET', 'POST'])
def add_book():
if request.method == 'POST':
title = request.form['title']
author = request.form['author']
isbn = request.form['isbn']
publisher = request.form['publisher']
cursor.execute("INSERT INTO books (title, author, isbn, publisher) VALUES (%s, %s, %s, %s)",
(title, author, isbn, publisher))
conn.commit()
return redirect(url_for('index'))
return render_template('add_book.html')
@app.route('/edit/<int:book_id>', methods=['GET', 'POST'])
def edit_book(book_id):
cursor.execute("SELECT * FROM books WHERE id = %s", (book_id,))
book = cursor.fetchone()
if request.method == 'POST':
title = request.form['title']
author = request.form['author']
isbn = request.form['isbn']
publisher = request.form['publisher']
cursor.execute("UPDATE books SET title = %s, author = %s, isbn = %s, publisher = %s WHERE id = %s",
(title, author, isbn, publisher, book_id))
conn.commit()
return redirect(url_for('index'))
return render_template('edit_book.html', book=book)
@app.route('/delete/<int:book_id>', methods=['POST'])
def delete_book(book_id):
cursor.execute("DELETE FROM books WHERE id = %s", (book_id,))
conn.commit()
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Personal Library</title>
</head>
<body>
<h1>Personal Library</h1>
<a href="{{ url_for('add_book') }}">Add a Book</a>
<table border="1">
<tr>
<th>Title</th>
<th>Author</th>
<th>ISBN</th>
<th>Publisher</th>
<th>Actions</th>
</tr>
{% for book in books %}
<tr>
<td>{{ book.title }}</td>
<td>{{ book.author }}</td>
<td>{{ book.isbn }}</td>
<td>{{ book.publisher }}</td>
<td>
<a href="{{ url_for('edit_book', book_id=book.id) }}">Edit</a>
<form action="{{ url_for('delete_book', book_id=book.id) }}" method="post">
<input type="submit" value="Delete">
</form>
</td>
</tr>
{% endfor %}
</table>
</body>
</html>
templates/add_book.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Book</title>
</head>
<body>
<h1>Add a New Book</h1>
<form action="{{ url_for('add_book') }}" method="post">
<label for="title">Title:</label>
<input type="text" name="title" id="title" required><br>
<label for="author">Author:</label>
<input type="text" name="author" id="author" required><br>
<label for="isbn">ISBN:</label>
<input type="text" name="isbn" id="isbn"><br>
<label for="publisher">Publisher:</label>
<input type="text" name="publisher" id="publisher"><br>
<input type="submit" value="Add Book">
</form>
<a href="{{ url_for('index') }}">Back to list</a>
</body>
</html>
templates/edit_book.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Book</title>
</head>
<body>
<h1>Edit Book</h1>
<form action="{{ url_for('edit_book', book_id=book.id) }}" method="post">
<label for="title">Title:</label>
<input type="text" name="title" id="title" value="{{ book.title }}" required><br>
<label for="author">Author:</label>
<input type="text" name="author" id="author" value="{{ book.author }}" required><br>
<label for="isbn">ISBN:</label>
<input type="text" name="isbn" id="isbn" value="{{ book.isbn }}"><br>
<label for="publisher">Publisher:</label>
<input type="text" name="publisher" id="publisher" value="{{ book.publisher }}"><br>
<input type="submit" value="Update Book">
</form>
<a href="{{ url_for('index') }}">Back to list</a>
</body>
</html>
这个项目提供了一个很好的起点来练习使用Python与MySQL数据库交互,同时也包括使用Flask来创建一个简单的web应用。你可以根据自己的需要对这个项目进行扩展,比如添加用户认证、使用Ajax来增强用户体验、或者使用Bootstrap来改进前端界面等。
确保你的数据库配置正确,所有依赖项已经安装,并且数据库服务器正在运行。然后,通过运行app.py文件来启动Flask服务器,应用将在本地开发服务器上运行。在浏览器中访问http://localhost:5000/来查看你的应用。
将Flask应用打包并发布为生产环境,通常需要一些额外的步骤。以下是这个过程的大致步骤:
准备部署
移除调试模式: 在app.py中的app.run(debug=True)修改为app.run()
使用WSGI服务器:Flask自带的服务器不适合用于生产环境。通常会选择一个WSGI服务器,比如gunicorn或uWSGI,来运行应用。
安装gunicorn:
pip install gunicorn
运行gunicorn服务器(在你的应用目录下):
gunicorn -w 4 app:app
-w 4表示使用4个工作进程,app:app表示app.py文件中的Flask实例。
使用环境变量:不要在代码中硬编码配置信息,如数据库密码和密钥。使用环境变量来存储这些敏感信息。
打包应用
创建一个requirements.txt文件,列出所有的依赖项。这可以通过pip freeze > requirements.txt命令完成。
在代码根目录下创建一个文件夹,比如deploy/,将所有代码以及requirements.txt文件复制到这个文件夹中。
发布应用
将打包好的应用上传到你的服务器。这可以通过FTP、SCP或者其他文件传输方法完成。
在服务器上安装Python和所有必要的依赖包。使用pip install -r requirements.txt来安装依赖。
配置服务器环境。这包括设置环境变量、安装和配置web服务器,如Nginx,以及设置WSGI服务器。
使用Nginx作为反向代理
安装Nginx:根据你的服务器操作系统,使用对应的包管理器进行安装。
配置Nginx,使其作为反向代理,将HTTP请求代理到WSGI服务器。以下是一个简单的Nginx配置示例:
server {
listen 80;
server_name your_server_domain_or_IP;
location / {
proxy_pass http://127.0.0.1:8000; # 假设gunicorn运行在8000端口上
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
重新加载Nginx配置:sudo nginx -s reload
启动应用
启动WSGI服务器(如果使用gunicorn,则像之前一样运行gunicorn -w 4 app:app命令)。
确保Nginx服务正在运行。
现在你的Flask应用应该可以通过服务器的域名或IP地址访问了。值得注意的是,这里只是一个基本的部署指南,根据你的具体需求和环境,步骤可能会有所不同。在生产环境中还需要考虑安全性、性能和稳定性等因素。此外,可能还需要使用Supervisor或systemd等工具来管理和监控应用的进程。
Gunicorn:
Gunicorn是Unix系统上的一个流行的Python WSGI HTTP服务器。它简单、快速、轻量,并且易于使用。可以通过pip安装:
pip install gunicorn
然后使用gunicorn来运行你的应用:
gunicorn -w 4 myapp:app
其中-w 4指定了工作进程数为4(你可以根据你的核心数来调整这个数字),myapp是你的Flask应用文件名(不包含.py扩展名),app是你的Flask实例名称。
uWSGI:
uWSGI是另一个流行的WSGI服务器,它支持多种语言和协议、高度可配置,也可以通过pip安装:
pip install uwsgi
运行uWSGI服务器:
uwsgi --http :8000 --module myapp:app --master --processes 4 --threads 2
这里–http :8000指定监听端口,–module myapp:app指定应用的位置,–master开启主进程,–processes 4和–threads 2分别为进程数和线程数。
Apache with mod_wsgi:
Apache是一个非常流行的web服务器,mod_wsgi是一个Apache模块,可以用来托管Python应用。配置比较复杂,但是在很多共享主机环境中很常见。
NGINX with uWSGI or Gunicorn:
NGINX是一个高性能的HTTP和反向代理服务器,通常与uWSGI或Gunicorn结合使用来服务Python应用。
选择合适的WSGI服务器取决于你的需求、偏好以及你的服务器环境。在设置WSGI服务器之后,你通常还需要设置一个前端服务器(比如NGINX或Apache)来处理静态文件和作为反向代理,来转发请求到你的WSGI服务器。
在你的生产服务器上配置WSGI和前端服务器之后,你的Flask应用将能够以更安全、更稳定、并且能够更好地处理并发请求的方式运行。