2018-06-08

2018-06-08  本文已影响0人  有可能_666

Flask连接数据库


数据库配置文件
  class conf():
      USERNAME = 'root'
      PASSWORD = '123456'
      HOSTNAME = '127.0.0.1'
      PORT = '3306'
      DATABASE = 'flask_demo'
      DB_URI = 'mysql+mysqldb://{}:{}@{}:{}/{}?charset=utf8'.format
        (USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
SQLALCHEMY_DATABASE_URI = DB_URI
    #???
    SQLALCHEMY_TRACK_MODIFICATIONS = False

主app文件
  from flask import Flask
  from flask_sqlalchemy import SQLAlchemy
  from config import conf
  app = Flask(__name__)

  #1.绑定数据库配置文件
  app.config.from_object(conf)
  #2.sqlalchemy绑定入app
  db = SQLAlchemy(app=app)
  #3.初始化db
  db.init_app(app)

  class Student(db.Model):
    __tablename__ = 'student'
    id = db.Column(db.Integer, primary_key=True,       autoincrement=True)
    #nullable是否为空,unique是否唯一
    name = db.Column(db.String(50), nullable=False,     unique=True)
    gender = db.Column(db.String(20))
    profession = db.Column(db.String(100),   nullable=False)


  #4.创建表
  db.create_all()


@app.route('/')
def hello():
    return 'hello world!'

if __name__ == '__main__':
    app.run(debug=True, port=8888)
上一篇 下一篇

猜你喜欢

热点阅读