Forums

MySQL error

.

File "./main.py", line 35, in login
2021-11-28 18:43:45,516:     cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
2021-11-28 18:57:42,882: Error running WSGI application
2021-11-28 18:57:42,903: NameError: name 'mysql' is not defined

Anyone knows what causes this error?

It looks like you haven't imported mysql (or defined it) in your code.

Locally it works fine, that's odd.

could you share your code with us? Contact us at support@pythonanywhere.com if you do not want to do it here.

from flask import Flask, render_template, request, redirect, url_for, session from flask_mysqldb import MySQL import MySQLdb.cursors import re

app = Flask(__name__)
app.debug = True


@app.route('/login/', methods=['GET', 'POST'])
def login():
    # Output message if something goes wrong...
    msg = ''
    # Check if "username" and "password" POST requests exist (user submitted form)
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
        # Create variables for easy access
        username = request.form['username']
        password = request.form['password']

        # Check if account exists using MySQL
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM accounts WHERE username = %s AND password = %s', (username, password,))
        # Fetch one record and return result
        account = cursor.fetchone()
        # If account exists in accounts table in out database
        if account:
            # Create session data, we can access this data in other routes
            session['loggedin'] = True
            session['id'] = account['id']
            session['username'] = account['username']
            # Redirect to home page
            #return render_template('index.html')
            return redirect(url_for('home'))
        else:
            # Account doesnt exist or username/password incorrect
            msg = 'Usuário ou senha incorretos!'

    return render_template('login.html', msg=msg)

@app.route('/register/', methods=['GET', 'POST'])
def register():
    # Output message if something goes wrong...
    msg = ''
    # Check if "username", "password" and "email" POST requests exist (user submitted form)
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in request.form:
        # Create variables for easy access
        username = request.form['username']
        password = request.form['password']
        email = request.form['email']
        # Check if account exists using MySQL
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM accounts WHERE username = %s', (username,))
        account = cursor.fetchone()
        # If account exists show error and validation checks
        if account:
            msg = 'Conta já existe!'
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
            msg = 'E-mail inválido!'
        elif not re.match(r'[A-Za-z0-9]+', username):
            msg = 'Usuário deve conter apenas letras e números!'
        elif not username or not password or not email:
            msg = 'Por favor, preencha os campos!'
        else:
            # Account doesnt exists and the form data is valid, now insert new account into accounts table
            cursor.execute('INSERT INTO accounts VALUES (NULL, %s, %s, %s)', (username, password, email,))
            mysql.connection.commit()
            msg = f'Olá,{username}! Você se registrou.'
    elif request.method == 'POST':
        # Form is empty... (no POST data)
        msg = 'Por favor, preencha os campos!'
    # Show registration form with message (if any)
    return render_template('register.html', msg=msg)

@app.route('/home')
def home():
    if session:
        return render_template('index.html')
    else:
        return render_template('login.html')

@app.route('/logout')
def logout():
    # Remove session data, this will log the user out
    session.pop('loggedin', None)
    session.pop('id', None)
    session.pop('username', None)
    # Redirect to login page
    return redirect(url_for('login'))


@app.route('/')
def landing():
    return redirect(url_for('login'))


if __name__ == '__main__':
    # Change this to your secret key (can be anything, it's for extra protection)
    app.secret_key = 'your secret key'

    # Enter your database connection details below, the real values are omitted
    # app.config['MYSQL_HOST'] = 'localhost'
    # app.config['MYSQL_USER'] = 'root'
    # app.config['MYSQL_PASSWORD'] = 'Database1!'
    # app.config['MYSQL_DB'] = 'pythonlogin'

    # Intialize MySQL
    mysql = MySQL(app)
    app.run()

The code in the if statement at the end does not get run on PythonAnywhere. Move your database code out of that section.

I did it now I'm getting another error MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'arthurpdesimone'@'10.0.0.254' (using password: YES)")

Make sure that you use the correct database name that on PythonAnywhere looks like <username>$<something>