Я создаю биллинговую систему. Я хочу, чтобы у каждого клиента была своя собственная база данных подписок. Поэтому, когда мы добавляем нового клиента, база данных его подписок уже создана. Но в базе данных 0 данных, поэтому когда мы нажимаем добавить новую подписку, должна загрузиться форма. Но проблема в том, что всякий раз, когда я нажимаю «Добавить новую подписку», форма не загружается, а всегда загружается «Метод не разрешен
Метод не разрешен для запрошенного URL».
from flask import Flask, render_template, request, redirect, url_for, flash
import sqlite3
import os
app = Flask(__name__)
# Function to connect to the main SQLite database
def connect_db():
return sqlite3.connect('billing_system.db')
# Function to connect to a customer's subscription database
def connect_subscription_db(customer_id):
with connect_db() as db:
cursor = db.cursor()
cursor.execute('SELECT subscription_db FROM customers WHERE id = ?', (customer_id,))
filename = cursor.fetchone()\[0\]
return sqlite3.connect(filename)
# Function to initialize the main database
def init_db():
with connect_db() as db:
cursor = db.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS customers (
id INTEGER PRIMARY KEY,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
phone_number TEXT NOT NULL,
subscription_db TEXT NOT NULL
)
''')
db.commit()
@app.route('/add_customer', methods=\['POST'\])
def add_customer():
first_name = request.form\['first_name'\]
last_name = request.form\['last_name'\]
phone_number = request.form\['phone_number'\]
subscription_db_filename = f'subscriptions\_{first_name}\_{last_name}.db'
with connect_db() as db:
cursor = db.cursor()
cursor.execute('''
INSERT INTO customers (first_name, last_name, phone_number, subscription_db)
VALUES (?, ?, ?, ?)
''', (first_name, last_name, phone_number, subscription_db_filename))
db.commit()
# Create the subscriptions table in the new database file
with connect_subscription_db(cursor.lastrowid) as subscription_db:
subscription_cursor = subscription_db.cursor()
subscription_cursor.execute('''
CREATE TABLE IF NOT EXISTS subscriptions (
id INTEGER PRIMARY KEY,
buyer_name TEXT NOT NULL,
location TEXT NOT NULL,
address TEXT NOT NULL,
bandwidth TEXT NOT NULL,
start_date TEXT NOT NULL,
end_date TEXT NOT NULL,
vendor TEXT NOT NULL,
price TEXT NOT NULL,
schedule TEXT NOT NULL
)
''')
subscription_db.commit()
flash('Customer added successfully', 'success')
return redirect(url_for('customer_page'))
@app.route('/')
@app.route('/customer')
def customer_page():
with connect_db() as db:
cursor = db.cursor()
cursor.execute('SELECT \* FROM customers')
customers = cursor.fetchall()
customer_count = len(customers)
return render_template('customer.html', customers=customers, customer_count=customer_count)
@app.route('/edit_customer/\', methods=\['GET', 'POST'\])
def edit_customer(customer_id):
if request.method == 'GET':
\# Fetch customer information from the database
with connect_db() as db:
cursor = db.cursor()
cursor.execute('SELECT \* FROM customers WHERE id = ?', (customer_id,))
customer = cursor.fetchone()
if not customer:
flash('Customer not found', 'error')
return redirect(url_for('customer_page'))
return render_template('edit_customer.html', customer=customer)
elif request.method == 'POST':
# Update customer information
first_name = request.form['first_name']
last_name = request.form['last_name']
phone_number = request.form['phone_number']
with connect_db() as db:
cursor = db.cursor()
cursor.execute('''
UPDATE customers
SET first_name = ?, last_name = ?, phone_number = ?
WHERE id = ?
''', (first_name, last_name, phone_number, customer_id))
db.commit()
flash('Customer information updated successfully', 'success')
return redirect(url_for('customer_page'))
# Route for viewing customer information
@app.route('/view_customer/\')
def view_customer(customer_id):
\# Fetch customer information from the database
with connect_db() as db:
cursor = db.cursor()
cursor.execute('SELECT \* FROM customers WHERE id = ?', (customer_id,))
customer = cursor.fetchone()
if not customer:
flash('Customer not found', 'error')
return redirect(url_for('customer_page'))
return render_template('customer_info.html', customer=customer)
@app.route('/delete_customer/\')
def delete_customer(customer_id):
with connect_db() as db:
cursor = db.cursor()
cursor.execute('SELECT subscription_db FROM customers WHERE id = ?', (customer_id,))
filename = cursor.fetchone()\[0\]
os.remove(filename)
cursor.execute('DELETE FROM customers WHERE id = ?', (customer_id,))
db.commit()
flash('Customer and associated subscriptions deleted successfully', 'success')
return redirect(url_for('customer_page'))
@app.route('/customer/\/subscriptions')
def view_subscriptions(customer_id):
try:
with connect_subscription_db(customer_id) as subscription_db:
subscription_cursor = subscription_db.cursor()
subscription_cursor.execute('SELECT \* FROM subscriptions')
subscriptions = subscription_cursor.fetchall()
except sqlite3.OperationalError as e:
flash('Error fetching subscriptions: ' + str(e), 'error')
subscriptions = \[\]
with connect_db() as db:
cursor = db.cursor()
cursor.execute('SELECT * FROM customers WHERE id = ?', (customer_id,))
customer = cursor.fetchone()
if not customer:
flash('Customer not found', 'error')
return redirect(url_for('customer_page'))
return render_template('subscriptions.html', customer=customer, subscriptions=subscriptions)
# Route for adding a new subscription
@app.route('/add_subscription/\', methods=\['POST'\])
def add_subscription(customer_id):
if request.method == 'POST':
buyer_name = request.form\['buyer_name'\]
location = request.form\['location'\]
address = request.form\['address'\]
bandwidth = request.form\['bandwidth'\]
schedule = request.form\['schedule'\]
start_date = request.form\['start_date'\]
end_date = request.form\['end_date'\]
vendor = request.form\['vendor'\]
price = request.form\['price'\]
try:
with connect_subscription_db(customer_id) as subscription_db:
subscription_cursor = subscription_db.cursor()
subscription_cursor.execute('''
INSERT INTO subscriptions (buyer_name, location, address, bandwidth, schedule, start_date, end_date, vendor, price)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (buyer_name, location, address, bandwidth, schedule, start_date, end_date, vendor, price))
subscription_db.commit()
except sqlite3.OperationalError as e:
flash('Error adding subscription: ' + str(e), 'error')
flash('Subscription added successfully', 'success')
return redirect(url_for('view_subscriptions', customer_id=customer_id))
if __name__ == '__main__':
init_db()
app.run(debug=True, port=2349)\``
Подробнее здесь: https://stackoverflow.com/questions/783 ... ption-page