0

Im new in python and im getting the above error by trying to assign a connection variable to a function in a different .py file

i've tried to set connection as none but didnt solve my issue

views.py

from datetime import datetime
from flask import render_template, request, redirect, url_for, flash
from FlaskWebProject1 import app

import json
import mysql.connector
from mysql.connector import Error
import FlaskWebProject1.db 



@app.route('/')
@app.route('/users')
def users():

  try: 
    lstUsers = ''

    #connect to DB
    connection = db.get_connection()

    if connection.is_connected():
        #db_Info = connection.get_server_info()
        #print("Connected to MySQL Server version ", db_Info)
        cursor = connection.cursor(dictionary=True)
        cursor.execute("select * from users;")
        record = cursor.fetchall()
        lstUsers = record       
        #print("Your connected to database: ", record)
  except Error as e:
         print("Error while connecting to MySQL", e) 
  finally:
        if (connection.is_connected()):
            cursor.close()
            connection.close()
            print("MySQL connection is closed")

  return render_template('users.html',
    title = 'Users Page', 
    users = lstUsers)

db.py

_connection = None

def get_connection():
    global _connection
    if not _connection:
        _connection = mysql.connector.connect(user="bla@bla", 
                       password='bla', 
                       host="mysql.database.azure.com", 
                       port=3306, 
                       database='testdb')
        return _connection

# List of stuff accessible to importers of this module. Just in case
__all__ = [ 'getConnection' ]

Traceback (most recent call last): File "C:\Users\Usuario\source\repos\FlaskWebProject1\FlaskWebProject1\FlaskWebProject1\views.py", line 24, in users connection = db.get_connection() NameError: name 'db' is not defined

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:\Users\Usuario\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "C:\Users\Usuario\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\Usuario\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Users\Usuario\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask_compat.py", line 33, in reraise raise value File "C:\Users\Usuario\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\Usuario\source\repos\FlaskWebProject1\FlaskWebProject1\env\lib\site-packages\flask\app.py", line 1598, in dispatch_request return self.view_functionsrule.endpoint File "C:\Users\Usuario\source\repos\FlaskWebProject1\FlaskWebProject1\FlaskWebProject1\views.py", line 37, in users if (connection.is_connected()): UnboundLocalError: local variable 'connection' referenced before assignment 127.0.0.1 - - [09/Sep/2019 23:56:55] "GET / HTTP/1.1" 500 - 127.0.0.1 - - [09/Sep/2019 23:56:55] "GET /favicon.ico HTTP/1.1" 404 -

I expect to assign the connection variable in views.py file to the get_connection() that returns a connection in db.py and use the connection in order to connect to MySQL server with no issues

8
  • You need to show us all of the code, and the full stack trace. Commented Sep 10, 2019 at 2:46
  • 1
    ok, wait me a second please Commented Sep 10, 2019 at 2:46
  • i have added all the code Commented Sep 10, 2019 at 2:56
  • so now put full error mesage (starting at word "Traceback") There are other useful information. Commented Sep 10, 2019 at 2:57
  • done, i added it Commented Sep 10, 2019 at 2:58

1 Answer 1

1

Error shows

NameError: name 'db' is not defined` 

so this is your main problem and source of other problems.

You have

import FlaskWebProject1.db

so you need FlaskWebProject1. in

connection = FlaskWebProject1.db.get_connection()

or you should import

from FlaskWebProject1 import db
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.