Flask网站sqlalchemy连接mariadb

毕瀚
2023-12-01
  •    安装python3.6之后建立虚拟环境并启用,退出虚拟环境使用deactivate命令
 1007  python3 -m venv venv  #建立虚拟环境
 1008  source venv/bin/activate #启用虚拟环境
 1009  pip install pyodbc #虚拟环境下安装python扩展包
 1010  pip install --upgrade pip
 1011  pip install pyodbc
 1012  pip install ibm_db
 1013  pip --version
 1014  pip install pymysql #安装mysql驱动
  • Flask 中连接mariadb
# coding:utf8

import os
from datetime import datetime

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import pymysql

app = Flask(__name__)
app.debug = True

app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://lubaohui:lubaohui@127.0.0.1:3306/cbdb"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True

db = SQLALchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(100), unique = True)

测试数据库连接:

(venv) [leo@linux pytest]$ ipython3
\/usr/lib/python3.6/site-packages/IPython/core/interactiveshell.py:763: UserWarning: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
  warn("Attempting to work in a virtualenv. If you encounter problems, please "
Python 3.6.5 (default, Mar 29 2018, 18:20:46) 
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from models_with_appv2 import db,User

In [2]: db.create_all()

In [3]: u = User(name="leo")

In [4]: db.session.add(u)

In [5]: db.session.commit()

 

 类似资料: