Python Flask 框架开发
1. Python 代码示例(使用 Flask 框架)
1.1 安装依赖库
pip install flask flask_sqlalchemy flask_login flask_wtf
1.2 主应用文件 app.py
from flask import Flask, request, jsonify, redirect, url_for, render_template, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, ValidationError, SelectField
from wtforms.validators import DataRequired, Length, EqualTo
import os
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SECRET_KEY'] = os.urandom(24)
db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
role = db.Column(db.String(20), nullable=False, default='user') # 'user' or 'admin'
class Order(db.Model):
id = db.Column(db.Integer, primary_key=True)
order_number = db.Column(db.String(20), unique=True, nullable=False)
status = db.Column(db.String(20), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship('User', backref='orders')
class ElectronicWaybill(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(255), nullable=False)
order_id = db.Column(db.Integer, db.ForeignKey('order.id'), nullable=False)
order = db.relationship('Order', backref='electronic_waybills')
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=4, max=20)])
password = PasswordField('Password', validators=[DataRequired(), Length(min=6, max=60)])
confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
role = SelectField('Role', choices=[('user', 'User'), ('admin', 'Admin')], default='user')
submit = SubmitField('Register')
def validate_username(self, field):
if User.query.filter_by(username=field.data).first():
raise ValidationError('Username is already in use.')
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = User.query.filter_by(username=username).first()
if user and user.password == password:
login_user(user)
return redirect(url_for('dashboard'))
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('login'))
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
user = User(username=form.username.data, password=form.password.data, role=form.role.data)
db.session.add(user)
db.session.commit()
flash('Registration successful. You can now log in.', 'success')
return redirect(url_for('login'))
return render_template('register.html', form=form)
@app.route('/dashboard')
@login_required
def dashboard():
orders = Order.query.filter_by(user_id=current_user.id).all()
order_list = [{'id': order.id, 'order_number': order.order_number, 'status': order.status} for order in orders]
return jsonify({'orders': order_list, 'user_role': current_user.role})
# 其他路由和功能可以根据需求添加
# ...
if __name__ == '__main__':
db.create_all()
app.run(debug=True)
-- 创建 User 表
CREATE TABLE "user" (
id INTEGER NOT NULL,
username VARCHAR(20) NOT NULL,
password VARCHAR(60) NOT NULL,
role VARCHAR(20) NOT NULL DEFAULT 'user',
PRIMARY KEY (id),
UNIQUE (username)
);
-- 创建 Order 表
CREATE TABLE order (
id INTEGER NOT NULL,
order_number VARCHAR(20) NOT NULL,
status VARCHAR(20) NOT NULL,
user_id INTEGER NOT NULL,
PRIMARY KEY (id),
UNIQUE (order_number),
FOREIGN KEY(user_id) REFERENCES "user" (id)
);
-- 创建 ElectronicWaybill 表
CREATE TABLE electronic_waybill (
id INTEGER NOT NULL,
content VARCHAR(255) NOT NULL,
order_id INTEGER NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY(order_id) REFERENCES "order" (id)
);
from your_app import db, User, Order, ElectronicWaybill
# 创建用户
user1 = User(username='user1', password='password1', role='user')
user2 = User(username='user2', password='password2', role='admin')
db.session.add_all([user1, user2])
db.session.commit()
# 创建订单
order1 = Order(order_number='ORD123', status='Processing', user_id=user1.id)
order2 = Order(order_number='ORD456', status='Shipped', user_id=user2.id)
db.session.add_all([order1, order2])
db.session.commit()
# 创建电子面单
waybill1 = ElectronicWaybill(content='Content for order 1', order_id=order1.id)
waybill2 = ElectronicWaybill(content='Content for order 2', order_id=order2.id)
db.session.add_all([waybill1, waybill2])
db.session.commit()