【1.初级版】
flask-scrpit安装。
使用flask-scrpit可以创建命令,并在Flask的应用上下文中执行,因为这样才能对Flask对象进行修改。Flask Script自带了一些默认的命令,可以运行服务器或者开启带应用上下文的Python命令行。
env) D:\python\flask>pip install flask-script
Collecting flask-script
Downloading Flask-Script-2.0.6.tar.gz (43kB)
47% |███████████████▏ | 20kB 166kB/s eta 0:00
71% |██████████████████████▉ | 30kB 221kB/s e
94% |██████████████████████████████▍ | 40kB 1
100% |████████████████████████████████| 51kB
218kB/s
Requirement already satisfied: Flask in d:\python\flask\env\lib\site-packages (f
rom flask-script)
Requirement already satisfied: Werkzeug>=0.7 in d:\python\flask\env\lib\site-pac
kages (from Flask->flask-script)
Requirement already satisfied: itsdangerous>=0.21 in d:\python\flask\env\lib\sit
e-packages (from Flask->flask-script)
Requirement already satisfied: click>=2.0 in d:\python\flask\env\lib\site-packag
es (from Flask->flask-script)
Requirement already satisfied: Jinja2>=2.4 in d:\python\flask\env\lib\site-packa
ges (from Flask->flask-script)
Requirement already satisfied: MarkupSafe>=0.23 in d:\python\flask\env\lib\site-
packages (from Jinja2>=2.4->Flask->flask-script)
Building wheels for collected packages: flask-script
Running setup.py bdist_wheel for flask-script ... done
Stored in directory: C:\Users\test003\AppData\Local\pip\Cache\wheels\35\38\2a\
5a4aef4aa51913c135f5d2ff6f8552ad0db06667cd3e48ef2d
Successfully built flask-script
Installing collected packages: flask-script
Successfully installed flask-script-2.0.6
安装成功,开始写脚本。
from flask_script import Manager, Server
from main import app
然后把你的app传给Manager对象,以初始化Flask Script:
manager = Manager(app)
现在我们来添加一些命令。这里运行的服务器跟通过main.py运行的普通开发服务器是一样的。make_shell_context函数会创建一个Python命令行,并且在应用上下文中执行。返回的字典告诉Flask Script在打开命令行时进行一些默认的导入工作。
manager.add_command("server", Server())
@manager.shell
def make_shell_context():
return dict(app=app)
通过manage.py运行命令行在将来会十分必要,因为一些Flask扩展只有在Flask应用对象被创建之后才会被初始化。直接运行默认的Python命令行会令这些扩展返回错误。
然后,在文件结尾添加如下代码,这是Python的标准方式,用来限制仅在用户直接运行文件的时候,才执行上面的代码:
if __name__ == "__main__":
class Config(object):
pass
class ProdConfig(Config):
pass
class DevConfig(Config):
DEBUG = True
from flask import Flask
from config import DevConfig
app = Flask(__name__)
app.config.from_object(DevConfig)
@app.route('/')
def home():
return '
Hello World!
'if __name__ == '__main__':
app.run()
[运行服务器]
D:\python\flask>env\Scripts\activate
(env) D:\python\flask>python example2\manage.py server
* Restarting with stat
* Debugger is active!
* Debugger PIN: 104-739-710
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[命令行方式连接]
D:\python\flask>env\Scripts\activate
(env) D:\python\flask>python example2\manage.py shell
>>> app
>>>
以上,Flask和Flask-script安装,运行完成。
【2.进阶版-数据库连接】
安装Flask SQLAlchemy。SQLAlchemy在最底层包装了数据库操作接口,在最上层提供了对象关系映射(ORM)。ORM是在基于不同的数据结构和系统类型的数据源之间传递和转换数据的技术。在这里,它用来把大量不同类型的数据库中的数据,转换成python对象的集合。同时,像Python这样的语言,允许你在不同的对象之间建立引用,读取和设置它们的属性;而SQLAlchemy这样的ORM,能为你将对象操作转换为传统的数据库操作。
(env) D:\python\flask>pip install flask-sqlalchemy
Collecting flask-sqlalchemy
Downloading Flask_SQLAlchemy-2.3.2-py2.py3-none-any.whl
Collecting SQLAlchemy>=0.8.0 (from flask-sqlalchemy)
Downloading SQLAlchemy-1.1.15.tar.gz (5.2MB)
38% |████████████▏ | 2.0MB 46kB/s eta 0:01:10
...省略...
99% |████████████████████████████████| 5.2MB
100% |████████████████████████████████| 5.2M
B 28kB/s
Requirement already satisfied: Flask>=0.10 in d:\python\flask\env\lib\site-packa
ges (from flask-sqlalchemy)
Requirement already satisfied: Werkzeug>=0.7 in d:\python\flask\env\lib\site-pac
kages (from Flask>=0.10->flask-sqlalchemy)
Requirement already satisfied: click>=2.0 in d:\python\flask\env\lib\site-packag
es (from Flask>=0.10->flask-sqlalchemy)
Requirement already satisfied: Jinja2>=2.4 in d:\python\flask\env\lib\site-packa
ges (from Flask>=0.10->flask-sqlalchemy)
Requirement already satisfied: itsdangerous>=0.21 in d:\python\flask\env\lib\sit
e-packages (from Flask>=0.10->flask-sqlalchemy)
Requirement already satisfied: MarkupSafe>=0.23 in d:\python\flask\env\lib\site-
packages (from Jinja2>=2.4->Flask>=0.10->flask-sqlalchemy)
Building wheels for collected packages: SQLAlchemy
Running setup.py bdist_wheel for SQLAlchemy ... done
Stored in directory: C:\Users\test003\AppData\Local\pip\Cache\wheels\
b67f1ab4d5a08d3c3ad3edfc1e60e09f9263536aa3dc91824c
Successfully built SQLAlchemy
Installing collected packages: SQLAlchemy, flask-sqlalchemy
Successfully installed SQLAlchemy-1.1.15 flask-sqlalchemy-2.3.2
class Config(object):
pass
class ProdConfig(Config):
pass
class DevConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = "mysql://root:666666@localhost/mytest"
这个数据库连接方式,当时是看攻略写的,并不了解背后知识,结果后面有很大的麻烦。
2.main_mysql.py文件
from config import DevConfig
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object(DevConfig)
db = SQLAlchemy(app)
class User(db.Model):
#SQLAlchemy会假设你的表名就模型类型的小写版本。这个例子里,表名就是user。
#但是,如果你想给表起个别的名字,你可以给类添加'__tablename__'的类属性。
##另外,通过采用这种方式,你也可以使用在数据库中已经存在的表,只需把表名设为该属性的值:
##__tablename__ = 'user_table_name'
id = db.Column(db.Integer(), primary_key=True)
username = db.Column(db.String(255))
password = db.Column(db.String(255))
def __init__(self, username):
self.username = username
def __repr__(self):
return "".format(self.username)
from flask_script import Manager, Server
from main_mysql import app, db, User
#把你的app传给Manager对象,以初始化Flask Script:
manager = Manager(app)
#现在我们来添加一些命令。这里运行的服务器跟通过main.py运行的普通开发服务器是一样的。
#make_shell_context函数会创建一个Python命令行,并且在应用上下文中执行。
#返回的字典告诉Flask Script在打开命令行时进行一些默认的导入工作。
manager.add_command("server", Server())
@manager.shell
def make_shell_context():
#return dict(app=app)
#注意:每新增一个模型,都会在这个地方导入并添加到dict中。
return dict(app=app, db=db, User=User)
#通过manage.py运行命令行在将来会十分必要,因为一些Flask扩展只有在Flask应用对象被创建之后才会被初始化。直接运行默认的Python命令行会令这些扩展返回错误。
#然后,在文件结尾添加如下代码,这是Python的标准方式,用来限制仅在用户直接运行文件的时候,才执行上面的代码:
if __name__ == "__main__":
[运行服务器]
(env) D:\python\flask\example2>python manage.py server
D:\python\flask\env\lib\site-packages\flask_sqlalchemy\__init__.py:794: FSADepre
cationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this
warning.
'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
* Restarting with stat
D:\python\flask\env\lib\site-packages\flask_sqlalchemy\__init__.py:794: FSADepre
cationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this
warning.
'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
* Debugger is active!
* Debugger PIN: 104-739-710
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[运行客户端]
env) D:\python\flask\example2>python manage.py shell
D:\python\flask\env\lib\site-packages\flask_sqlalchemy\__init__.py:794: FSADepre
cationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will
be disabled by default in the future. Set it to True or False to suppress this
warning.
'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
>>> db.create_all()
...省略...
File "D:\python\flask\env\lib\site-packages\sqlalchemy\dialects\mysql\mysqldb.
py", line 110, in dbapi
return __import__('MySQLdb')
ImportError: No module named 'MySQLdb'
执行db.create_all()出错了。查攻略,缺少mysql的python连接库。好吧,开始下载mysql-python库。。
(env) D:\python\flask\example2>pip install mysql-python
...省略...
error: Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows S
----------------------------------------
Failed building wheel for mysql-python
Running setup.py clean for mysql-python
Failed to build mysql-python
Installing collected packages: mysql-python
Running setup.py install for mysql-python ... error
又出错了,缺少C++类库。好吧,下载winsdk_web.exe。再安装。
又出错了,有完没完,缺少framework4。再下载,dotNetFx40_Full_x86_x64,安装,总算不报错了。
现在可以安装winsdk_web.exe,需要n久时间,慢慢等吧。
趁这段时间,补一下python和mysql连接的知识吧,查了一篇文章https://www.zhihu.com/question/29719547,终于搞明白了。原来有2种方式,我现在用的是第一种,mysql-python库。连接代码,SQLALCHEMY_DATABASE_URI = "mysql://root:666666@localhost/mytest"
另外一种是pymysql库,反正现在winsdk_web.exe安装等待中,尝试一下吧。
(env) D:\python\flask>pip install pymysql3
...省略...
Successfully built pymysql3
Installing collected packages: pymysql3
Successfully installed pymysql3-0.5
config.py文件中,修改代码如下:
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:666666@localhost/mytest"
再运行db.create_all(),不报错了。
去mysql的mytest数据库,show tables,user表创建成功了~~~
以前从来没有研究过python连接mysql数据库,所以没有经验。不然不会那么折腾了,直接用pymysql方式简单多了。果断放弃winsdk_web.exe安装,等以后有空再尝试mysql-python库。
【后续】
shell中再运行了几个命令
增加数据
>>> user = User(username='fake_name')
>>> db.session.add(user)
>>> db.session.commit()
读取数据
>>> users = User.query.all()
>>> users
[]
修改数据
>>> User.query.filter_by(username='fake_name').update({'password':'test'})
1
>>> db.session.commit()
删除数据
>>> user = User.query.filter_by(username='fake_name').first()
>>> db.session.delete(user)
>>> db.session.commit()