当前位置: 首页 > article >正文

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()


http://www.kler.cn/a/159915.html

相关文章:

  • 知识库管理系统:企业数字化转型的加速器
  • 编译ffmpeg动态库时设置RPATH为$ORIGIN
  • 解决:WSL2可视化opencv和pyqt冲突:QObject::moveToThread
  • 网络安全-Linux基础(bash脚本)
  • Qt初识简单使用Qt
  • Docker网络和overlay的基础讲解
  • K-Radar:适用于各种天气条件的自动驾驶4D雷达物体检测
  • 图形遍历效率低?试试 R 树
  • 【华为OD题库-043】二维伞的雨滴效应-java
  • 【C++】:set和map
  • PIKA,一个神奇的AI工具
  • 《LeetCode力扣练习》代码随想录——字符串(反转字符串---Java)
  • 学生上课睡觉老师的正确做法
  • 【力扣】——可获得的最大点数(滑动窗口)
  • python炒股自动化(1),量化交易接口区别
  • 绘制折扇-第11届蓝桥杯选拔赛Python真题精选
  • SAP CA01/CA02 创建及更新工艺路线BAPI
  • 大话数据结构-查找-二叉排序树
  • Vue获取Promise then的返回值无效为空
  • 【ML】LSTM应用——预测股票(基于 tensorflow2)
  • [SQL]销售管理数据库的查询操作
  • 代码随想Day24 | 回溯法模板、77. 组合
  • 显示本周日历,左右滑动,日历翻页
  • UDP多人群聊
  • 区块链密码学:基础知识、应用与未来发展
  • c++ atmoic acquire/release