连接mysql数据库,创建用户模型
- 安装与配置python3.6+flask+mysql数据库
- 下载安装MySQL数据库
- 下载安装MySQL-python 中间件
- pip install flask-sqlalchemy (Python的ORM框架SQLAlchemy)
- mysql创建数据库
- 数据库配置信息config.py
- 建立mysql和app的连接
- 创建用户模型
untitled.py
from flask import Flask,render_template from flask_sqlalchemy import SQLAlchemy import config app = Flask(__name__) # 创建Flask对象 app.config.from_object(config) #关联config.py文件进来 db=SQLAlchemy(app) #建立和数据库的关系映射 class User(db.Model): #创建类User __tablename__='user' #类对应的表名user id=db.Column(db.Integer,primary_key=True,autoincrement=True) #autoincrement自增长 username=db.Column(db.String(20),nullable=False) #nullable是否为空 password=db.Column(db.String(20),nullable=False) db.create_all() #测试是否连接成功 # route制定路径和函数之间的关系 # def定义一个变量 @app.route('/') # 跳转首页 def daohang(): return render_template('daohang.html') @app.route('/lin/') # 跳转测试 def lin(): return 'lin' @app.route('/denglu/') # 跳转登陆 def denglu(): return render_template('denglu.html') @app.route('/zhuce/') # 跳转注册 def zhuce(): return render_template('zhuce.html') @app.route('/tupian/') # 跳转图片 def tupian(): return render_template('tupian.html') @app.route('/fabu/') # 跳转图片 def fabu(): return render_template('fabu.html') if __name__ == '__main__': app.run(debug=True)
config.py
# 配置和数据库的连接信息 SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:@localhost:3306/mis_db?charset=utf8' SQLALCHEMY_TRACK_MODIFICATIONS = False