python3 + flask + sqlalchemy

2022-07-14 15:17:29 浏览数 (1)

python3 flask sqlalchemy orm(1):链接mysql 数据库

1、pycharm中新建一个flask项目

2、按装flask、PyMySQL、flask-sqlalchemy

3、项目下面新建一个config.py 文件

代码语言:javascript复制
DEBUG = True
#dialect driver://root:1q2w3e4r5t@127.0.0.1:3306/
DIALECT = 'mysql'
DRIVER='pymysql'
USERNAME = 'root'
PASSWORD = '1q2w3e4r5t'
HOST = '127.0.0.1'
PORT = 3306
DATABASE = 'db_demo1'

SQLALCHEMY_DATABASE_URI = "{} {}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT,DRIVER,USERNAME,PASSWORD,HOST,PORT,DATABASE)
SQLALCHEMY_TRACK_MODIFICATIONS = False
print(SQLALCHEMY_DATABASE_URI)

4、app.py 文件

代码语言:javascript复制
from flask import Flask
import config

from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object(config)

db = SQLAlchemy(app)
db.create_all()



@app.route('/')
def index():
    return 'index'



if __name__ == '__main__':
    app.run()

执行app.py 文件,结果如下,表面执行成功

代码语言:javascript复制
from flask import Flask
import config

from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object(config)

db = SQLAlchemy(app)
db.create_all()



@app.route('/')
def index():
    return 'index'



if __name__ == '__main__':
    app.run()

FLASK_APP = test_sqlalchemy.py FLASK_ENV = development FLASK_DEBUG = 1 In folder /Users/autotest/PycharmProjects/python3_flask /Users/autotest/PycharmProjects/python3_flask/venv/bin/python /Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py --module --multiproc --qt-support=auto --client 127.0.0.1 --port 55365 --file flask run pydev debugger: process 3089 is connecting

Connected to pydev debugger (build 182.4505.26) * Serving Flask app "test_sqlalchemy.py" (lazy loading) * Environment: development * Debug mode: on mysql pymysql://root:1q2w3e4r5t@127.0.0.1:3306/db_demo1?charset=utf8 * Running on http://127.0.0.1:5000/ (Press CTRL C to quit) * Restarting with stat pydev debugger: process 3090 is connecting

mysql pymysql://root:1q2w3e4r5t@127.0.0.1:3306/db_demo1?charset=utf8 * Debugger is active! * Debugger PIN: 216-502-598

python3 flask sqlalchemy orm(2):数据库中添加表

往数据库中添加一张保存文章的表,表明为article,字段有id,title,content

同样一个配置文件:config.py

代码语言:javascript复制
DEBUG = True
#dialect driver://root:1q2w3e4r5t@127.0.0.1:3306/
DIALECT = 'mysql'
DRIVER='pymysql'
USERNAME = 'root'
PASSWORD = '1q2w3e4r5t'
HOST = '127.0.0.1'
PORT = 3306
DATABASE = 'db_demo1'

SQLALCHEMY_DATABASE_URI = "{} {}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT,DRIVER,USERNAME,PASSWORD,HOST,PORT,DATABASE)
SQLALCHEMY_TRACK_MODIFICATIONS = False
print(SQLALCHEMY_DATABASE_URI)

flask app 中新建一个class Blog,里面定义好id ,title ,content。代码执行到db.create_all()时,会自动在数据库中创建一个表,表明为blog

代码语言:javascript复制
from flask import Flask
import config

from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.declarative import declarative_base

app = Flask(__name__)
app.config.from_object(config)

db = SQLAlchemy(app)
Base = declarative_base()


class Blog(db.Model):
    __tablename__ = 'blog'
    id  = db.Column(db.Integer,primary_key=True,autoincrement=True)
    title = db.Column(db.String(100),nullable=False)
    content = db.Column(db.Text,nullable=True)


db.create_all()


@app.route('/')
def index():
    return 'index'


if __name__ == '__main__':
    app.run(debug=True)

启动flask app,数据库中查询表和表结构如下,有新增相应的表,说明新建表成功

数据库表中的数据增删改查

代码语言:javascript复制
    #新增
    blog = Blog(title="first blog",content="this is my first blog")
    db.session.add(blog)
    db.session.commit()

    #查询
    #res =Blog.query.filter(Blog.title=="first blog")[0]

    res =Blog.query.filter(Blog.title=="first blog").first()
    print(res.title)
     #修改
    blog_edit = Blog.query.filter(Blog.title=="first blog").first()
    blog_edit.title = "new first blog"
    db.session.commit()
    #删除
    blog_delete  = Blog.query.filter(Blog.title=="first blog").first()
    db.session.delete(blog_delete)
    db.session.commit()

完整代码

代码语言:javascript复制
from flask import Flask
import config

from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.declarative import declarative_base

app = Flask(__name__)
app.config.from_object(config)

db = SQLAlchemy(app)
Base = declarative_base()


class Blog(db.Model):
    __tablename__ = 'blog'
    id  = db.Column(db.Integer,primary_key=True,autoincrement=True)
    title = db.Column(db.String(100),nullable=False)
    content = db.Column(db.Text,nullable=True)


db.create_all()


@app.route('/')
def index():
    #新增
    blog = Blog(title="first blog",content="this is my first blog")
    db.session.add(blog)
    db.session.commit()

    #查询
    #res =Blog.query.filter(Blog.title=="first blog")[0]

    res =Blog.query.filter(Blog.title=="first blog").first()
    print(res.title)
     #修改
    blog_edit = Blog.query.filter(Blog.title=="first blog").first()
    blog_edit.title = "new first blog"
    db.session.commit()
    #删除
    blog_delete  = Blog.query.filter(Blog.title=="first blog").first()
    db.session.delete(blog_delete)
    db.session.commit()


    return 'index'


if __name__ == '__main__':
    app.run(debug=True)

一篇文章有多个tag,一个tag也可以属于多篇文章,文章和tag存在多对多关系

config.py

代码语言:javascript复制
DEBUG = True
#dialect driver://root:1q2w3e4r5t@127.0.0.1:3306/
DIALECT = 'mysql'
DRIVER='pymysql'
USERNAME = 'demo_user'
PASSWORD = 'demo_123'
HOST = '172.16.10.6'
PORT = 3306
DATABASE = 'db_demo1'

SQLALCHEMY_DATABASE_URI = "{} {}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT,DRIVER,USERNAME,PASSWORD,HOST,PORT,DATABASE)
SQLALCHEMY_TRACK_MODIFICATIONS = False
print(SQLALCHEMY_DATABASE_URI)

app.py

代码语言:javascript复制
from flask import Flask
import config

from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.declarative import declarative_base

app = Flask(__name__)
app.config.from_object(config)

db = SQLAlchemy(app)
Base = declarative_base()

article_tag = db.Table('article_tag',
                       db.Column('article_id',db.Integer,db.ForeignKey("article.id"),primary_key=True),
                       db.Column('tag_id',db.Integer,db.ForeignKey("tag.id"),primary_key=True)
                       )

class Article(db.Model):
    __tablename__='article'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    title = db.Column(db.String(100),nullable=True)
    tags = db.relationship('Tag',secondary=article_tag,backref=db.backref('articles'))


class Tag(db.Model):
    __tablename__='tag'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(100),nullable=True)

db.create_all()


@app.route('/')
def index():
    article1 = Article(title="aaa")
    article2 = Article(title="bbb")

    tag1 = Tag(name='1111')
    tag2 = Tag(name='2222')

    article1.tags.append(tag1)
    article1.tags.append(tag2)
    article2.tags.append(tag1)
    article2.tags.append(tag2)
    db.session.add(article1)
    db.session.add(article2)
    db.session.add(tag1)
    db.session.add(tag2)
    db.session.commit()
    return 'index'


if __name__ == '__main__':
    app.run(debug=True)

0 人点赞