您好,登錄后才能下訂單哦!
本篇內容主要講解“Flask數據庫如何連接與使用”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Flask數據庫如何連接與使用”吧!
HOST = "XXXXXXXXXXXXX" PORT = 3310 USERNAME = "root" PASSWORD = "@XXXXXXXXXXX" DATABASE = "mydb" SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://{USERNAME}:{quote(PASSWORD)}@{HOST}:{PORT}/{DATABASE}?charset=utf8mb4" SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_ECHO = True
from exts.DBServer import db from 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 Blueprint from exts.DBServer import db from ..model.Article import Article from flask_sqlalchemy.query import Query from flask_restful import marshal from 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 db from 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數據庫如何連接與使用”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。