06_展示数据库表单

2018-11-02 大宝

1 效果图

将AdminUser表显示在网页上,如下所示:

2 代码说明

SQLAlchemy官网

SQLAlchemy-ORM 可以将对这些数据对象的操作转化为对数据库的操作。

mysql-pythonSQLAlchemyMySQL之间的连接器。

实现改功能涉及的代码较多,这里不列出来,直接跟着操作指南走。

3 操作指南

安装python模块

[root@am_01 ~]# pip install mysql-python flask-sqlalchemy 
[root@am_01 ~]# yum install -y gcc mysql-devel python-devel

使用myweb用户登陆服务器

[myweb@am_01 PonyTail]$ pwd
/home/myweb/PonyTail
[myweb@am_01 PonyTail]$ ll
total 8
-rw-rw-r--. 1 myweb myweb 1 Nov 2 18:33 __init__.py
-rw-rw-r--. 1 myweb myweb 1743 Nov 2 19:19 manage.py
drwxrwxr-x. 2 myweb myweb 63 Nov 2 17:32 templates

修改后manage.py文件如下:

# -*- coding:utf8 -*- 

from flask import Flask
from flask_admin import Admin
from flask_admin import BaseView
from flask_admin import expose
from flask_babelex import Babel
# 06_展示数据库表单新增
from flask_sqlalchemy import SQLAlchemy
from flask_admin.contrib.sqla import ModelView

# 06_展示数据库表单新增
db = SQLAlchemy()
app = Flask(__name__)
babel = Babel(app)

#set optional bootswatch theme
app.config['FLASK_ADMIN_SWATCH'] = 'cerulean'
app.config['BABEL_DEFAULT_LOCALE'] = 'zh_CN'
# 06_展示数据库表单新增
## 连接数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:myweb@localhost:3306/myweb?charset=utf8'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 06_展示数据库表单新增
db.init_app(app)
admin = Admin(app, name='PonyTail', template_mode='bootstrap3')

# 06_展示数据库表单新增
# models
class AdminUser(db.Model):
__tablename__ = 'AdminUser'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255), nullable=False)


# Add administrative views here
class Happy(BaseView):
@expose('/')
def index(self):
return self.render('happy.html')

class Birthday(BaseView):
@expose('/')
def index(self):
return self.render('birthday.html')

class MyV_AdminUser(ModelView):
column_list = ('id','name','password')
def __init__(self, session, **kwargs):
super(MyV_AdminUser, self).__init__(AdminUser, session, **kwargs)



if __name__ == "__main__":

admin.add_view(Happy(name=u'工作之愉'))
admin.add_view(Birthday(name=u'年年有今日岁岁有今朝'))
#admin.add_view(ModelView(AdminUser, db.session, name=u'用户管理'))
admin.add_view(MyV_AdminUser(db.session, name=u'用户管理'))

app.run(debug=True,host='0.0.0.0',port=5000)

运行程序

[myweb@am_01 PonyTail]$ python manage.py 
* Serving Flask app "manage" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 476-676-292

访问网站http://10.200.6.150:5000/admin/adminuser/