1. 程式人生 > >python3 + falsk + sqlalchemy 連結mysql 資料庫

python3 + falsk + sqlalchemy 連結mysql 資料庫

1、pycharm中新建一個flask專案

2、按裝flask、PyMySQL、SQLAlchemy

3、專案下面新建一個config.py 檔案

DEBUG = True
#dialect+driver://root:[email protected]:3306/
DIALECT = 'mysql'
DRIVER='pymysql'
USERNAME = 'root'
PASSWORD = '1q2w3e4r5t'
HOST = '127.0.0.1'
PORT = 3306
DATABASE = 'db_demo1'

SQLALCHEMY_DATABASE_URI 
= "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT,DRIVER,USERNAME,PASSWORD,HOST,PORT,DATABASE) SQLALCHEMY_TRACK_MODIFICATIONS = False print(SQLALCHEMY_DATABASE_URI)

4、app.py 檔案

from flask import Flask
import config

from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object(config)

db 
= SQLAlchemy(app) db.create_all() @app.route('/') def index(): return 'index' if __name__ == '__main__': app.run()

執行app.py 檔案,結果如下,表面執行成功

FLASK_APP = test_sqlalchemy.py
FLASK_ENV = development
FLASK_DEBUG = 1
In folder /Users/autotest/PycharmProjects/python3_flask
/Users/autotest/PycharmProjects/python3_flask/venv/bin/python /Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py --module --multiproc --qt-support=auto --client 127.0.0.1 --port 55365 --file flask run
pydev debugger: process 3089 is connecting

Connected to pydev debugger (build 182.4505.26)
* Serving Flask app "test_sqlalchemy.py" (lazy loading)
* Environment: development
* Debug mode: on
mysql+pymysql://root:[email protected]:3306/db_demo1?charset=utf8
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
pydev debugger: process 3090 is connecting

mysql+pymysql://root:[email protected]:3306/db_demo1?charset=utf8
* Debugger is active!
* Debugger PIN: 216-502-598