简体   繁体   中英

Use MySQL Flask connection in different python file

i have a app.py with:

from flask import FlasK
from flask_mysqldb import MySQL


# Objeto Flask
app = Flask(__name__)

# Secret key
app.secret_key = "appLogin"

# BD config
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'xxx'
app.config['MYSQL_PASSWORD'] = 'xxxx'
app.config['MYSQL_DB'] = 'feedlotdb'

# Obj MySQL
mysql = MySQL(app)


@app.route('/register', methods=["GET", "POST"])
def register():
   # USE BD
       sQuery = "INSERT INTO user (mail, password, name) VALUES (%s, %s, %s)"
       cur = mysql.connection.cursor()
       cur.execute(sQuery, (mail, password, name))
       mysql.connection.commit()

QUESTION:

I put part of the code above How can I take "/Register" and encapsulate the user code there in a file like user.py and use the same sql.connection? thx

you can create user.py and import mysql and app

users.py

from app import mysql
import app

from flask import Blueprint, render_template, abort

users_bp = Blueprint('users_bp', __name__)



@users_bp.route('/register', methods=["GET", "POST"])
def register():
       # USE BD
       sQuery = "INSERT INTO user (mail, password, name) VALUES (%s, %s, %s)"
       cur = mysql.connection.cursor()
       cur.execute(sQuery, (mail, password, name))
       mysql.connection.commit()

register blueprint in main app :-

from users import users_bp
app.register_blueprint(users_bp, url_prefix='/users')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM