1、直接连接
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text
app = Flask(__name__)
# "mysql+pymysql://账号:密码@127.0.0.1:3306/数据库?charset=utf8"
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root:root@127.0.0.1:3306/dade?charset=utf8"
db = SQLAlchemy(app)
# 测试是否连接成功
with app.app_context():
with db.engine.connect() as conn:
result = conn.execute(text("SELECT * FROM `dade1`"))
print(result.fetchone()) # (1,)
print(result.all())
@app.route('/')
def hello_world(): # put application's code here
return 'Hello World!'
if __name__ == '__main__':
app.run()
2、通过配置文件连接
创建setting.py
DIALECT = 'mysql'
DRIVER = 'pymysql'
USERNAME = 'root'
PASSWORD = 'root'
HOST = '127.0.0.1'
PORT = '3306'
DATABASE = 'dade'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT, DRIVER, USERNAME, PASSWORD, HOST, PORT, DATABASE)
2、创建app.py
# 导入Flask类
from flask import Flask, request
#Flask类接收一个参数__name__
#static_folder静态文件路径,可以不传,默认静态文件路径static
#template_folder模板路径html,可以不传,默认templates
from sqlalchemy import text
from apps.user import user_bp
app = Flask(__name__, static_folder='static')
app.config.from_pyfile('setting.py')
#注册路由
#app.register_blueprint(user_bp, url_prefix='/user')
#数据库配置
from flask_sqlalchemy import SQLAlchemy
import setting
app.config.from_object(setting)
db = SQLAlchemy(app)
# 测试是否连接成功
with app.app_context():
with db.engine.connect() as conn:
result = conn.execute(text("SELECT * FROM `dade1`"))
print(result.fetchone()) # (1,)
print(result.all())
@app.route('/')
def index2():
return 'Hello World'
@app.route("/itcast1", methods=["POST"])
def view_func_1():
req = request.form
return "hello world 1"+req['dades']
@app.route("/itcast2", methods=["GET", "POST"])
def view_func_2():
req = request.args.get("dades")
return "333"+req
# Flask应用程序实例的run方法启动WEB服务器
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000, debug=True)