1.views方法
@stu.route('/allstu/') def all_stu(): stus = Student.query.all() return render_template('all_stu.html', stus=stus)2.all_stu.html网页
<ul> {% for stu in stus %} <li> id:{{ stu.s_id }} 姓名:{{ stu.s_name }} <a href="/stu/selectcoursebystu/{{ stu.s_id }}">课程</a> # 点击跳转至学生所选的课程详情 </li> {% endfor %} </ul>3.通过学生查找对应所选课程
@stu.route('/selectcoursebystu/<int:id>/') def select_course_by_stu(id): stu = Student.query.get(id) cous = stu.cou # 注意:cou为学生的一个方法,在课程表中设置 return render_template('stucourse.html', cous=cous, stu=stu)4.stucourse.html页面
{% for cou in cous%} <li> {{ stu.s_name }}所选课程: 课程id:{{ cou.c_id }} 课程名:{{ cou.c_name }} <a href="/stu/deletecoursebyid/{{ stu.s_id }}/{{ cou.c_id }}">删除</a> </li> {% endfor %}5.删除对应课程方法
@stu.route('/deletecoursebyid/<int:s_id>/<int:c_id>') def delete_course_by_id(s_id, c_id): stu = Student.query.get(s_id) cou = Course.query.get(c_id) cou.students.remove(stu) db.session.commit() return redirect(url_for('stu.all_stu'))1.pip install DebugToolbar —— 安装DebugToolbar,用于调试(页面左边增加一栏调试栏)
2.pip install RESTful —— 安装RESTful,用于api接口
3.pip install marshmallow —— 安装棉花糖,序列化数据
1.修改文件结构 新建static静态文件夹 新建template网页文件夹 新建utils文件夹 2.在utils文件夹中 新建init.py / App.py / function.py / setting.py文件
3.manage.py
from flask_script import Manager from utils.APP import create_app # 到处APP中的create_app方法 app = create_app() manager = Manager(app=app) if __name__ == '__main__': manager.run()4.APP.py
from flask import Flask from utils.setting import templates_dir, static_folder=static_dir, SQLALCHEMY_DATABASE_URI from utils.function import init_ext def create_app(): # 创建app对象 app = Flask(__name__, template_folder=templates_dir, static_folder=static_dir) # 连接数据库,从setting中导入SQLALCHEMY_DATABASE_URI app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False init_ext(app) # 从function中导入init_ext方法 return app5.setting.py
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) templates_dir = os.path.join(BASE_DIR, 'templates') static_dir = os.path.join(BASE_DIR, 'static') DATABASE = { 'USER': 'root', 'PASSWORD': '123456', 'HOST': 'localhost', 'PORT': '3306', 'DB': 'mysql', 'DRIVER': 'pymysql', 'NAME': 'flask3' } SQLALCHEMY_DATABASE_URI = get_db(DATABASE) # 在function中导入get_db方法6.function.py
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() # 创建模型使用 def get_db(DATABASE): user = DATABASE.get('USER') password = DATABASE.get('PASSWORD') host = DATABASE.get('HOST') port = DATABASE.get('PORT') name = DATABASE.get('NAME') db = DATABASE.get('DB') driver = DATABASE.get('DRIVER') return '{}+{}://{}:{}@{}:{}/{}'.format(db, driver, user, password, host, port, name) def iinit_ext(app): db.init_app(app=app)