接着上篇,对系统做功能升级,在页面上输入文本,存入数据库,再显示在页面上
- 安装MySQL
$ sudo apt-get install mysql-server
$ sudo apt-get install mysql-client
$ sudo
### 登录数据库
$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 40
Server version: 5.5.49-0ubuntu0.14.04.1 (Ubuntu)
- 安装MySQL-Python和SQLAlchemy(ORM)
## 如果没有安徽easy_install,请先安装
$ wget http://peak.telecommunity.com/dist/ez_setup.py
$ easy_install MySQL-Python #这个模块已经被pymysql取代
$ easy_install pymysql
$ easy_install SQLAlchemy
ORM方法论基于三个核心原则:
简单性:以最基本的形式建模数据。
传达性:数据库结构被任何人都能理解的语言文档化。
精确性:基于数据模型创建正确标准化了的结构。
添加mysql数据库连接驱动
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Table
db_config = {
'host': '127.0.0.1',
'user': 'root',
'passwd': '123456',
'db':'test',
'charset':'utf8'
}
mysql_engine = create_engine('mysql+pymysql://%s:%s@%s/%s?charset=%s' \
%(db_config['user'],
db_config['passwd'],
db_config['host'],
db_config['db'],
db_config['charset']), \
echo=True)
在control.py中添加数据库操作部分
from app import celery
from db_driver import mysql_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Table
import time
Base = declarative_base()
# 定义表结构
class User(Base):
__tablename__ = 'user'
id = Column(String(20), primary_key=True)
name = Column(String(20))
@celery.task
def set_name2db(name):
u = User()
## USE TIMESTAMP AS KEY TO AVOID DUPLICATION
u.id = str(time.time())
u.name = name
new_user = User(id=u.id, name=u.name)
Session = sessionmaker()
Session.configure(bind=mysql_engine)
session = Session()
result = session.add(new_user)
session.commit()
query = session.query(User)
#rs = query.filter_by(name=u.name)
result = query.filter(User.id==u.id).first().name
session.commit()
session.close()
return result
在view.py中添加新的uri路径
@flask_app.route('/setname')
def set_name():
# FLASK MUST RETURN AN OBJECT OR A STRING
return control.set_name2db("Wendy & Simon")
网友评论