🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# python3怎么用sqlalchemy操作mysql ``` <pre class="calibre15">``` 第一步 python需要安装pymysql mysqldb不可用于python3 第二步使用 url链接 链接字符串 dialect<span class="token">+</span>driver<span class="token1">:</span><span class="token">/</span><span class="token">/</span>username<span class="token1">:</span>password@host<span class="token1">:</span>port<span class="token">/</span>database 在config中写配置 # 增加: article1 <span class="token">=</span> <span class="token3">Article</span><span class="token1">(</span>title<span class="token">=</span><span class="token4">'aaa'</span><span class="token1">,</span>content<span class="token">=</span><span class="token4">'bbb'</span><span class="token1">)</span> db<span class="token1">.</span>session<span class="token1">.</span><span class="token3">add</span><span class="token1">(</span>article1<span class="token1">)</span> # 事务 db<span class="token1">.</span>session<span class="token1">.</span><span class="token3">commit</span><span class="token1">(</span><span class="token1">)</span> # 查 # select <span class="token">*</span> <span class="token2">from</span> article where article<span class="token1">.</span>title<span class="token">=</span><span class="token4">'aaa'</span><span class="token1">;</span> article1 <span class="token">=</span> Article<span class="token1">.</span>query<span class="token1">.</span><span class="token3">filter</span><span class="token1">(</span>Article<span class="token1">.</span>title <span class="token">==</span> <span class="token4">'aaa'</span><span class="token1">)</span><span class="token1">.</span><span class="token3">first</span><span class="token1">(</span><span class="token1">)</span> print <span class="token4">'title:%s'</span> <span class="token">%</span> article1<span class="token1">.</span>title print <span class="token4">'content:%s'</span> <span class="token">%</span> article1<span class="token1">.</span>content <span class="token5">3.</span> 改: <span><span class="token4">``</span></span><span><span class="token4">` # 改: # 1\. 先把你要更改的数据查找出来 article1 = Article.query.filter(Article.title == 'aaa').first() # 2\. 把这条数据,你需要修改的地方进行修改 article1.title = 'new title' # 3\. 做事务的提交 db.session.commit() # 删 # 1\. 把需要删除的数据查找出来 article1 = Article.query.filter(Article.content == 'bbb').first() # 2\. 把这条数据删除掉 db.session.delete(article1) # 3\. 做事务提交 db.session.commit() `</span></span><span><span class="token4">``</span></span> ### Flask<span class="token">-</span>SQLAlchemy外键及其关系: <span class="token5">1.</span> 外键: <span><span class="token4">``</span></span><span><span class="token4">` class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer,primary_key=True,autoincrement=True) username = db.Column(db.String(100),nullable=False) class Article(db.Model): __tablename__ = 'article' id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(100),nullable=False) content = db.Column(db.Text,nullable=False) author_id = db.Column(db.Integer,db.ForeignKey('user.id')) author = db.relationship('User',backref=db.backref('articles')) `</span></span><span><span class="token4">``</span></span> <span class="token5">2.</span> <span><span class="token4">`author = db.relationship('User',backref=db.backref('articles'))`</span></span>解释: <span class="token">*</span> 给<span><span class="token4">`Article`</span></span>这个模型添加一个<span><span class="token4">`author`</span></span>属性,可以访问这篇文章的作者的数据,像访问普通模型一样。 <span class="token">*</span> <span><span class="token4">`backref`</span></span>是定义反向引用,可以通过<span><span class="token4">`User.articles`</span></span>访问这个模型所写的所有文章。 <span class="token5">3.</span> 多对多: <span class="token">*</span> 多对多的关系,要通过一个中间表进行关联。 <span class="token">*</span> 中间表,不能通过<span><span class="token4">`class`</span></span>的方式实现,只能通过<span><span class="token4">`db.Table`</span></span>的方式实现。 <span class="token">*</span> 设置关联:<span><span class="token4">`tags = db.relationship('Tag',secondary=article_tag,backref=db.backref('articles'))`</span></span>需要使用一个关键字参数<span><span class="token4">`secondary=中间表`</span></span>来进行关联。 <span class="token">*</span> 访问和数据添加可以通过以下方式进行操作: <span class="token">*</span> 添加数据: <span><span class="token4">``</span></span><span><span class="token4">` article1 = Article(title='aaa') article2 = Article(title='bbb') tag1 = Tag(name='111') tag2 = Tag(name='222') 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() `</span></span><span><span class="token4">``</span></span> <span class="token">*</span> 访问数据: <span><span class="token4">``</span></span><span><span class="token4">` article1 = Article.query.filter(Article.title == 'aaa').first() tags = article1.tags for tag in tags: print tag.name `</span></span><span><span class="token4">``</span></span> ### Flask<span class="token">-</span>Script的介绍与安装: <span class="token5">1.</span> Flask<span class="token">-</span>Script:Flask<span class="token">-</span>Script的作用是可以通过命令行的形式来操作Flask。例如通过命令跑一个开发版本的服务器、设置数据库,定时任务等。 <span class="token5">2.</span> 安装:首先进入到虚拟环境中,然后<span><span class="token4">`pip install flask-script`</span></span>来进行安装。 <span class="token5">3.</span> 如果直接在主<span><span class="token4">`manage.py`</span></span>中写命令,那么在终端就只需要<span><span class="token4">`python manage.py command_name`</span></span>就可以了。 <span class="token5">4.</span> 如果把一些命令集中在一个文件中,那么在终端就需要输入一个父命令,比如<span><span class="token4">`python manage.py db init`</span></span>。 <span class="token5">5.</span> 例子: <span><span class="token4">``</span></span><span><span class="token4">` from flask_script import Manager from flask_script_demo import app from db_scripts import DBManager manager = Manager(app) # 和数据库相关的操作,我都放在一起 @manager.command def runserver(): print '服务器跑起来了!!!!!' manager.add_command('db',DBManager) if __name__ == '__main__': manager.run() `</span></span><span><span class="token4">``</span></span> <span class="token5">6.</span> 有子命令的例子: <span><span class="token4">``</span></span><span><span class="token4">` #encoding: utf-8 from flask_script import Manager DBManager = Manager() @DBManager.command def init(): print '数据库初始化完成' @DBManager.command def migrate(): print '数据表迁移成功' `</span></span><span><span class="token4">``</span></span> ### 分开<span><span class="token4">`models`</span></span>以及解决循环引用: <span class="token5">1.</span> 分开models的目的:为了让代码更加方便的管理。 <span class="token5">2.</span> 如何解决循环引用:把<span><span class="token4">`db`</span></span>放在一个单独的文件中,切断循环引用的线条就可以了。 ### Flask<span class="token">-</span>Migrate的介绍与安装: <span class="token5">1.</span> 介绍:因为采用<span><span class="token4">`db.create_all`</span></span>在后期修改字段的时候,不会自动的映射到数据库中,必须删除表,然后重新运行<span><span class="token4">`db.craete_all`</span></span>才会重新映射,这样不符合我们的需求。因此flask<span class="token">-</span>migrate就是为了解决这个问题,她可以在每次修改模型后,可以将修改的东西映射到数据库中。 <span class="token5">2.</span> 首先进入到你的虚拟环境中,然后使用<span><span class="token4">`pip install flask-migrate`</span></span>进行安装就可以了。 <span class="token5">3.</span> 使用<span><span class="token4">`flask_migrate`</span></span>必须借助<span><span class="token4">`flask_scripts`</span></span>,这个包的<span><span class="token4">`MigrateCommand`</span></span>中包含了所有和数据库相关的命令。 <span class="token5">4.</span> <span><span class="token4">`flask_migrate`</span></span>相关的命令: <span class="token">*</span> <span><span class="token4">`python manage.py db init`</span></span>:初始化一个迁移脚本的环境,只需要执行一次。 <span class="token">*</span> <span><span class="token4">`python manage.py db migrate`</span></span>:将模型生成迁移文件,只要模型更改了,就需要执行一遍这个命令。 <span class="token">*</span> <span><span class="token4">`python manage.py db upgrade`</span></span>:将迁移文件真正的映射到数据库中。每次运行了<span><span class="token4">`migrate`</span></span>命令后,就记得要运行这个命令。 <span class="token5">5.</span> 注意点:需要将你想要映射到数据库中的模型,都要导入到<span><span class="token4">`manage.py`</span></span>文件中,如果没有导入进去,就不会映射到数据库中。 <span class="token5">6.</span> <span><span class="token4">`manage.py`</span></span>的相关代码: <span><span class="token4">``</span></span><span><span class="token4">` from flask_script import Manager from migrate_demo import app from flask_migrate import Migrate,MigrateCommand from exts import db from models import Article # init # migrate # upgrade # 模型 -> 迁移文件 -> 表 manager = Manager(app) # 1\. 要使用flask_migrate,必须绑定app和db migrate = Migrate(app,db) # 2\. 把MigrateCommand命令添加到manager中 manager.add_command('db',MigrateCommand) if __name__ == '__main__': manager.run() `</span></span><span><span class="token4">``</span></span> ``` ```