0

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

Mariano
  • 11
  • 2

1 Answers1

1

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')
  • Did not work. When I call the event /Register in user.py Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. Try use https://flask.palletsprojects.com/en/1.1.x/patterns/lazyloading/#converting-to-centralized-url-map but I also couldn't – Mariano Mar 13 '20 at 23:43
  • if the request URL is not found then i am sure you have not registered users.py file as blueprint to main app . see flask blueprint for more detail :- https://flask.palletsprojects.com/en/1.1.x/blueprints/ – ANISH KUMAR MOURYA Mar 16 '20 at 07:05