当前位置:   article > 正文

Python笔记-Flask结合SQLAlchemy查询MySQL数据库_from flask_sqlalchemy import sqlalchemy

from flask_sqlalchemy import sqlalchemy

这里首先要安装两个库

  1. pip install flask_sqlalchemy
  2. pip install mysqlclient
这里要简单介绍下Flask中分文件(标准结构)
Flask中的架构可分为:

1. 启动文件(负责启动)

2. 核心文件

3. 路由注册文件

如下结构:

 

templates放模板

application.py为核心文件

controller.py放请求控制端

manager.py放启动文件

www.py放路由注册文件

 

程序运行截图如下:

源码如下:

index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <p>Flask 查询数据库</p>
  9. {% for item in result %}
  10. {{item['User']}}
  11. {% endfor %}
  12. </body>
  13. </html>

application.py

  1. from flask import Flask
  2. from flask_sqlalchemy import SQLAlchemy
  3. app = Flask(__name__)
  4. app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://root:XXXXXXX!@122.XX.XXX.141/mysql"
  5. db = SQLAlchemy(app)

controller.py

  1. from flask import Flask,Blueprint,request,make_response,jsonify,render_template
  2. from sqlalchemy import text
  3. from application import db
  4. index_page = Blueprint("index_page", __name__)
  5. @index_page.route("/sql")
  6. def sqlQuery():
  7. context = {}
  8. sql = text("select * from user")
  9. result = db.engine.execute(sql)
  10. context["result"] = result
  11. return render_template("index.html", **context)

manager.py

  1. from application import app
  2. from www import *
  3. if __name__ == "__main__":
  4. app.run(host = "0.0.0.0", debug = "True")

www.py

  1. from application import app
  2. from controller import index_page
  3. app.register_blueprint(index_page, url_prefix = "/it1995")

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/510748
推荐阅读
相关标签
  

闽ICP备14008679号