注册时Method Not Allowed The method is not allowed for the requested URL.修改并给我完整代码
时间: 2024-11-27 08:12:12 浏览: 21
在您的代码中,`register` 视图函数使用了 `sqlite3` 库来处理数据库操作,但其他地方使用的却是 `mysql.connector`。这会导致不一致的问题。为了统一数据库操作,建议全部使用同一个数据库库。这里我们选择使用 `mysql.connector` 来进行所有数据库操作。
另外,您提到的“注册时 Method Not Allowed”通常是由于请求方法不匹配导致的。检查 `register` 视图函数中的请求方法配置,确保它们与表单提交的方法一致。
以下是修正后的完整代码:
```python
from flask import Flask, render_template, request, redirect, url_for, flash, session
import mysql.connector
import bcrypt
import logging
app = Flask(__name__)
app.secret_key = 'your_secret_key'
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# 数据库连接
def connect_db():
conn = mysql.connector.connect(
host='localhost',
port=3306,
user='root',
password='123456',
database='pet_weight_management'
)
return conn
# 初始化数据库
def init_db():
conn = connect_db()
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS pets (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
pet_name VARCHAR(255) NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS pet_weights (
id INT AUTO_INCREMENT PRIMARY KEY,
pet_id INT NOT NULL,
weight DECIMAL(10, 2) NOT NULL,
recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (pet_id) REFERENCES pets (id) ON DELETE CASCADE
)
''')
conn.commit()
conn.close()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
conn = connect_db()
cursor = conn.cursor()
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
try:
cursor.execute('INSERT INTO users (username, password) VALUES (%s, %s)', (username, hashed_password))
conn.commit()
flash("注册成功!", 'success')
logging.info("用户 %s 注册成功!", username)
return redirect(url_for('login'))
except mysql.connector.IntegrityError:
flash("用户名已存在!", 'warning')
logging.warning("用户名 %s 已存在!", username)
finally:
conn.close()
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request
阅读全文