安装软件:
pip install sqlalchemy
pip install flask_sqlalchemy
pip install mysqlclient
mvc模式搭建项目与数据连接:
视图函数:indexCounter
from flask import Flask,Blueprint,render_template from sqlalchemy import text from application import db index_page = Blueprint("index_page",__name__) @index_page.route("/me/") def template(): context={} context['user'] = { "nickname":"编程浪子","qq":"9980","home_page":"http://www.54php.cn" } context['num_list'] = [ 1,2,3,4,5] #sql query sql = text("select * from `user`") result = db.engine.execute(sql) context['result'] = result return render_template("index.html",**context)
配置文件:
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://root:@127.0.0.1/mysql" db = SQLAlchemy(app)
注册文件:
from application import app from indexContoller import index_page app.register_blueprint(index_page,url_prefix="/imooc/")
启动文件:
from www import * from application import app if __name__ == "__main__": app.run()
显示文件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>this is json</p> <p> {% if user %} {{ user.qq }} {% endif %} </p> <p> {% for item in result %} {{ item['User'] }} {% endfor %} </p> {% block content %} {% endblock content %} </body> </html>
结果显示: