My code is trying to check the login username and password, and if match, just send a new post request to localhost /api/homepage with data "values", I tried it in local virtual env of the python scripts and it works, but for production mode, after inputting the user name and password, 502 Bad Gateways occured. I have already imported 'requests' library.in Nginx setting no load balance is used.
#app.route('/api/login',methods=['GET', 'POST'])
def login():
username = request.form['usermail']
pw = request.form['password']
db=MySQLdb.connect("localhost","root","1234","4080")
cursor = db.cursor()
query = "select * from user where username='"+username+"' AND password='"+pw+"';"
try:
cursor.execute(query)
result = cursor.fetchall()
except:
db.rollback()
return query
if len(result)==1:
values ={'user':'wes'}
r = requests.post('http://127.0.0.1/api/homepage' ,data=values)
return r.content
else:
return 'Fail login'
#app.route('/api/homepage',methods=['POST'])
def Display_Homepage():
return request.form['user'];
Related
I am writing a simple auth service in python using flask and flask_mysqldb. There is an error with the cursor.
import jwt
from flask import Flask, request
from flask_mysqldb import MySQL
server = Flask(__name__)
mysql = MySQL(server)
# server configuration
server.config["MYSQL_HOST"] = os.environ.get("MYSQL_HOST")
server.config["MYSQL_USER"] = os.environ.get("MYSQL_USER")
server.config["MYSQL_PASSWORD"] = os.environ.get("MYSQL_PASSWORD")
server.config["MYSQL_DB"] = os.environ.get("MYSQL_DB")
server.config["MYSQL_PORT"] = os.environ.get("MYSQL_PORT")
# print(server.config["MYSQL_HOST"])
# print(server.config["MYSQL_PORT"])
#server.route("/login", methods=["POST"])
def login():
auth = request.authorization
if not auth:
return "missing credentials",401
#check db for username and password
cur = mysql.connection.cursor()
res = cur.execute(
"SELECT email,password FROM user WHERE email=%s, (auth.username)"
)
This works on a virtual environment. All the specified packages are correctly installed.
Please try
cur = mysql.connect.cursor()
if you use a connection it will not suggest cursor(). once you use connect.cursor() it will not show the error. Thanks
I have an app that is deployed to Heroku that uses gunicorn as the Procfile and has a Python flask backend that manages pushing the frontend with send_from_directory(app.static_folder, 'index.html') and API calls such as
#app.route('/login', methods=['POST'])
#cross_origin()
def login():
if request.method == 'POST':
return loginUser(request.form['email'], request.form['password'])
I have a connect file that looks like:
import mysql.connector
from mysql.connector import errorcode
from mysql.connector.constants import ClientFlag
config = {
'user': 'root',
'password': 'password',
'host': 'ip',
'database': 'name',
'client_flags': [ClientFlag.SSL],
'ssl_ca': 'ssl/server-ca.pem',
'ssl_cert': 'ssl/client-cert.pem',
'ssl_key': 'ssl/client-key.pem'
}
def connectToDB():
try:
connection = mysql.connector.connect(**config)
if connection.is_connected():
return connection
return False
except:
return False
I can connect to the database locally through the API call, but when it is run on the server it does not work. I usually get the "Something went wrong" statement from this code
def loginUser(email, password):
try:
connection = connectToDB()
if(connection != False):
cursor = connection.cursor(buffered=True)
if(invalidEmail(email, cursor, connection)):
return {"response": "No account with that Email"}
userId = getId(email, password, cursor, connection)
connection.commit()
cursor.close()
if(userId == -1):
return {"response": "Incorrect Password"}
return {"response": "Success",
"id": userId}
# need to return ID
except mysql.connector.Error as err:
return {"response": err.msg }
return {"response": "Something went wrong"}
I have tried adding the Fixie extension to heroku and adding the static IPs from there to the Authorised networks in the GCP relational database (also tried adding 0.0.0.0/0).
I don't get any errors in the heroku logs, it just simply can't connect when it is done on the server. I also tested the API call and it works fine in postman using the heroku project link.
I have been learning how to use the Flask framework using a tutorial, but the code in my app.py keeps returning an error 500, and I can't figure out why (my code is identical to the tutorial).
Here's the app.py:
from flask import Flask, render_template, json, request
from flask.ext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash
mysql = MySQL()
app = Flask(__name__)
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'BucketList'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
#app.route('/')
def main():
return render_template('index.html')
#app.route('/showSignUp')
def showSignUp():
return render_template('signup.html')
#app.route('/signUp',methods=['POST','GET'])
def signUp():
try:
_name = request.form['inputName']
_email = request.form['inputEmail']
_password = request.form['inputPassword']
# validate the received values
if _name and _email and _password:
# All Good, let's call MySQL
conn = mysql.connect()
cursor = conn.cursor()
_hashed_password = generate_password_hash(_password)
cursor.callproc('sp_createUser',(_name,_email,_hashed_password))
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
return json.dumps({'message':'User created successfully !'})
else:
return json.dumps({'error':str(data[0])})
else:
return json.dumps({'html':'<span>Enter the required fields</span>'})
except Exception as e:
return json.dumps({'error':str(e)})
return traceback.format_exc()
finally:
cursor.close()
conn.close()
if __name__ == "__main__":
app.run(port=5002)
It's for a signup system.
a 500 error usually means there is an error in your python instead when you run try it withh app.run(port=5002,debug=True) this wont solve your problem ... but it should tell you whats going on
I know you are following this tutorial, because I am having the same problem - http://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-python-flask-and-mysql--cms-22972
The issue is that inside the stored procedure they are having you set a column of size 20:
CREATE DEFINER=`root`#`localhost` PROCEDURE `sp_createUser`(
IN p_name VARCHAR(20),
IN p_username VARCHAR(20),
IN p_password VARCHAR(20)
)
But when they tell you to salt the password in your python code, like you do:
_hashed_password = generate_password_hash(_password)
You are creating a string much longer than 20 characters, so if you ran this in debug mode you'd see the error says invalid column length for column password. I fixed this by just changing the size of the column to 100. :)
I know this tutorial and I was getting the same error a couple of minutes back.
I changed -
_hashed_password = generate_password_hash(_password)
to
_hashed_password = _password
and it worked! :).
I am assuming that the reason is size that we have declared for password field is less than what is actually needed if we hash. But for now, you can do the same and get the app running.
Happy Coding!
i'm making a login system for part of my coursework, where it querys the database to see if the data is correct. It works fine until I introduce a login that's not in the database. Is there anyway I can make the while working even after the mycursor.fetchone() gives the error for not fetching anything?
The code below is the subroutine I'm having issues with:
#the error message I'm receiving
username, password = mycursor.fetchone()
TypeError: 'NoneType' object is not iterable
#the subroutine I'm having trouble with
def accept(self):
conn = mysql.connector.connect(user, password, host, database)
#create cursor between python and mysql
mycursor = conn.cursor()
query = """
SELECT
username, password
FROM
UserInfo.User
WHERE
username = %s AND password = %s
"""
mycursor.execute(query, (self.textName.text(),self.textPass.text(), ))
global username
username, password = mycursor.fetchone()
#self.textName.text() and self.textPass.text() is the username and password entered by the user
if username == self.textName.text() and password == self.textPass.text():
self.GoToLogin()
else:
#the error message I want to display
QtGui.QMessageBox.warning(
self, 'Error', 'Username and password are incorrect')
Add try except block and ignore the exception that happens when the record is not found or if multiple records are found.
try:
#db call
except (SpecificException, AnotherException):
pass
It's good to catch specific exceptions than catch all exceptions but in this case you can just catch the global Exception
Also there is no reason to check again if the user and password are equal, since you're already passing that as part of the query.
I have a CherryPy "site" set up under Apache with modwsgi. It works fine and I can return hello world messages no problem. The problem is when I try to connect to my MySQL database. Here is the code I'm using.
import sys
sys.stdout = sys.stderr
import atexit
import threading
import cherrypy
import MySQLdb
cherrypy.config.update({'environment': 'embedded'})
if cherrypy.__version__.startswith('3.0') and cherrypy.engine.state == 0:
cherrypy.engine.start(blocking=False)
atexit.register(cherrypy.engine.stop)
def initServer():
global db
db=MySQLdb.connect(host="localhost", user="root",passwd="pass",db="Penguin")
class Login(object):
def index(self):
return 'Login Page'
index.exposed = True
class Root(object):
login = Login();
def index(self):
# Sample page that displays the number of records in "table"
# Open a cursor, using the DB connection for the current thread
c=db.cursor()
c.execute('SELECT count(*) FROM Users')
result=cursor.fetchall()
cursor.close()
return 'Help' + result
index.exposed = True
application = cherrypy.Application(Root(), script_name=None, config=None)
Most of this was copied from the CherryPy site on setting up modwsgi, I just added the database stuff which I pieced together from various internet sources.
When I try to view the root page I get a 500 Internal Server Error. I can still get to the login page fine but so I'm pretty sure I'm messing up the database connection somehow.
You have a bunch of errors, not related to CherryPy really.
def initServer():
global db
db is not defined in the global scope. Try:
db = None
def initServer():
global db
In addition, initServer() is never called to create the DB connection.
Another:
c = db.cursor()
c.execute('SELECT count(*) FROM Users')
result = cursor.fetchall()
cursor.close()
cursor is not defined. I think you mean c:
c = db.cursor()
c.execute('SELECT count(*) FROM Users')
result = c.fetchall()
c.close()