本篇内容主要讲解“flask数据库如何连接与使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Flask数据库如何连接与使用”吧!数据库连接配置HOST = "XX
本篇内容主要讲解“flask数据库如何连接与使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Flask数据库如何连接与使用”吧!
HOST = "XXXXXXXXXXXXX"PORT = 3310USERNAME = "root"PASSWord = "@XXXXXXXXXXX"DATABASE = "mydb" sqlALCHEMY_DATABASE_URI = f"mysql+pyMysql://{USERNAME}:{quote(PASSWORD)}@{HOST}:{PORT}/{DATABASE}?charset=utf8mb4"SQLALCHEMY_TRACK_MODIFICATioNS = FalseSQLALCHEMY_ECHO = True
from exts.DBServer import dbfrom sqlalchemy import Column, Integer, String, Date, DateTime class Article(db.Model): __tablename__ = "article" id = Column(Integer, primay_key=True, autoincrement=True) title = Column(String(100), nullable=True) pub_time = Column(DateTime, nullable=True) author = Column(String(100), nullable=True) content = Column(String(10000), nullable=True) origin = Column(String(1000), nullable=True)
controller:
import JSON from flask.blueprints import Blueprintfrom exts.DBServer import dbfrom ..model.Article import Articlefrom flask_sqlalchemy.query import Queryfrom flask_restful import marshalfrom flask_restful import fields article_bp = Blueprint("article", __name__, url_prefix="/article") article_fields = { "id": fields.Integer, "title": fields.String, "pub_time": fields.DateTime, "author": fields.String, "content": fields.String, "origin": fields.String} @article_bp.route("/queryAll")def queryAll(): query: Query = Article.query articles = query.all() article = query.get(1) article2 = query.filter_by(author="XXX") return json.dumps(marshal(articles, fields=article_fields),ensure_ascii=False)
from exts.DBServer import dbfrom sqlalchemy import Column, Integer, String class User(db.Model): __tablename__ = "user" id = Column(Integer, primary_key=True, autoincrement=True) username = Column(String(100), nullable=True) password = Column(String(100), nullable=True) def __repr__(self): return "User %r" % self.body
@user_bp.route("/query")def query_match(): query: Query = User.query result = query.filter(or_(User.username.contains("祥"), User.id == 1)) return json.dumps(marshal(result.all(), fields=user_fields), ensure_ascii=False) @user_bp.route("/in")def in_sql(): query: Query = User.query result = query.order_by(-User.password, -User.id) return json.dumps(marshal(result.all(), fields=user_fields), ensure_ascii=False)
到此,相信大家对“Flask数据库如何连接与使用”有了更深的了解,不妨来实际操作一番吧!这里是编程网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
--结束END--
本文标题: Flask数据库如何连接与使用
本文链接: https://www.lsjlt.com/news/349986.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-04
2024-05-04
2024-05-04
2024-05-04
2024-05-04
2024-05-04
2024-05-04
2024-05-04
2024-05-04
2024-05-04
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0