赞
踩
原文地址:https://www.cnblogs.com/diaosir/p/6351721.html
主要是要注意引入蓝图的位置一定要是在初始化db之后才行;
下程序结构:
1.建立mysql和app的连接
在config.py中加入以下两项配置:
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:xxxxx@localhost:3306/test?charset=utf8' SQLALCHEMY_TRACK_MODIFICATIONS = True 如此在app/__init__.py中加入 app.config.from_object('config')
db = SQLAlchemy(app)
就可以完成app和数据的关联,并生成一个可以操作app数据库的SQLAlchemy实例db
蓝图的引入要放在初始化DB之后,不然会报错;
完整的app/__init__.py代码如下:
- from flask import Flask, url_for, request, redirect, render_template
- from flask_sqlalchemy import SQLAlchemy
- app = Flask(__name__)
- app.config.from_object('config')
- db = SQLAlchemy(app)
- # 这里引入蓝图的配置
- from app import models,views
接下来就是主要的两个蓝图,以及他们的注册
#app/user.py
- from flask import Blueprint, render_template, redirect,request
- from app import db
- from .models import User
- user = Blueprint('user',__name__)
-
- @user.route('/index')
- def index():
- return render_template('user/index.html')
-
- @user.route('/add/',methods=['GET','POST'])
- def add():
- if request.method == 'POST':
- p_user = request.form.get('username',None)
- p_email = request.form.get('email',None)
- p_password = request.form.get('password',None)
-
- if not p_user or not p_email or not p_password:
- return 'input error'
-
- newobj = User(username=p_user, email=p_email, password=p_password)
- db.session.add(newobj)
- db.session.commit()
- users = User.query.all()
- return render_template('user/add.html',users=users)
- users = User.query.all()
- return render_template('user/add.html',users=users)
-
- @user.route('/show')
- def show():
- return 'user_show'
#app/admin.py
- #admin.py
- from flask import Blueprint,render_template, request, redirect
- from app import db
- from .models import Admin
-
- admin = Blueprint('admin',__name__)
-
- @admin.route('/index')
- def index():
- return render_template('admin/index.html')
-
- @admin.route('/add/',methods=['POST','GET'])
- def add():
- if request.method == 'POST':
- p_admin = request.form.get('username',None)
- p_email = request.form.get('email',None)
- p_password = request.form.get('password',None)
-
- if not p_admin or not p_email or not p_password:
- return 'input error'
-
- newobj = Admin(username=p_admin, email=p_email, password=p_password)
- db.session.add(newobj)
- db.session.commit()
- admins = Admin.query.all()
- return render_template('admin/add.html',admins=admins)
- admins = Admin.query.all()
- return render_template('admin/add.html',admins=admins)
-
- @admin.route('/show')
- def show():
- return 'admin_show'
#app/views.py
- from app import app
- from .admin import admin
- from .user import user
-
- app.register_blueprint(admin,url_prefix='/admin')
- app.register_blueprint(user, url_prefix='/user')
#run.py
- from app import app
- app.run()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。