Internal Server Error: Python Flask render template sqlite3 - python

I am getting an internal server error (500) when I try to access https://127.0.0.1:5000/deliveries_awaiting_pickup. When I try to access it, the terminal running the Flask server looks like this (after multiple attempts of trying to access it):
$ python minitwitLocal.py
table user already exists
* Running on https://127.0.0.1:5000/ (Press CTRL+C to quit)
hello
[]
127.0.0.1 - - [13/Apr/2015 21:26:57] "GET /deliveries_awaiting_pickup HTTP/1.1" 500 -
hello
[]
127.0.0.1 - - [13/Apr/2015 21:26:59] "GET /deliveries_awaiting_pickup HTTP/1.1" 500 -
I tried deleting the database and restarting the server, and it doesn't work. Also, the table is empty, but I expected it to render a blank page.
How do I get it to render the template? Thanks!
Most relevant part of minitwitLocal.py:
#app.route('/deliveries_awaiting_pickup')
def deliveries_awaiting_pickup():
if not g.user:
return redirect(url_for('public_timeline'))
print "hello"
orders=query_db('''select * from deliveries_awaiting_pickup''')
print orders
return render_template('deliveries_awaiting_pickup.html', orders)
deliveries_awaiting_pickup.html:
{% extends "layout.html" %}
{% block title %}
Deliveries Awaiting Pickup
{% endblock %}
{% block body %}
<h2>{{ self.title() }}</h2>
Deliveries Awaiting Pickup go here<br><br>
{% if orders %}
{% for order in orders %}
{% endfor %}
{% endif %}
{% endblock %}
minitwitLocal.py: (Mostly the "minitwit" example that Flask provides, with a few modifications)
# -*- coding: utf-8 -*-
"""
MiniTwit
~~~~~~~~
A microblogging application written with Flask and sqlite3.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import time
from sqlite3 import dbapi2 as sqlite3
from hashlib import md5
from datetime import datetime
from flask import Flask, request, session, url_for, redirect, \
render_template, abort, g, flash, _app_ctx_stack
from werkzeug import check_password_hash, generate_password_hash
import requests
import json
# configuration
DATABASE = 'minitwit.db'
PER_PAGE = 30
DEBUG = True
SECRET_KEY = 'development key'
#FOURSQUARE OAUTH2
FOURSQUARE_CLIENT_ID = 'XXXXXXX'
FOURSQUARE_CLIENT_SECRET = 'XXXXXX'
FOURSQUARE_REDIRECT_URI = "https://127.0.0.1:5000/authenticated"
FOURSQUARE_API_BASE = "https://api.foursquare.com/v2/"
# create our little application :)
app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('MINITWIT_SETTINGS', silent=True)
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
top = _app_ctx_stack.top
if not hasattr(top, 'sqlite_db'):
top.sqlite_db = sqlite3.connect(app.config['DATABASE'])
top.sqlite_db.row_factory = sqlite3.Row
return top.sqlite_db
#app.teardown_appcontext
def close_database(exception):
"""Closes the database again at the end of the request."""
top = _app_ctx_stack.top
if hasattr(top, 'sqlite_db'):
top.sqlite_db.close()
def init_db():
"""Creates the database tables."""
with app.app_context():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
try:
db.cursor().executescript(f.read())
except sqlite3.OperationalError, msg:
print msg
db.commit()
def query_db(query, args=(), one=False):
"""Queries the database and returns a list of dictionaries."""
cur = get_db().execute(query, args)
rv = cur.fetchall()
return (rv[0] if rv else None) if one else rv
def get_user_id(username):
"""Convenience method to look up the id for a username."""
rv = query_db('select user_id from user where username = ?',
[username], one=True)
return rv[0] if rv else None
def format_datetime(timestamp):
"""Format a timestamp for display."""
return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d # %H:%M')
def gravatar_url(email, size=80):
"""Return the gravatar image for the given email address."""
return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \
(md5(email.strip().lower().encode('utf-8')).hexdigest(), size)
#app.before_request
def before_request():
g.user = None
if 'user_id' in session:
g.user = query_db('select * from user where user_id = ?',
[session['user_id']], one=True)
#app.route('/add_new_delivery_order')
def add_new_delivery_order():
if not g.user:
return redirect(url_for('public_timeline'))
return render_template('add_new_delivery_order.html')
#app.route('/deliveries_awaiting_pickup')
def deliveries_awaiting_pickup():
if not g.user:
return redirect(url_for('public_timeline'))
print "hello"
orders=query_db('''select * from deliveries_awaiting_pickup''')
print orders
return render_template('deliveries_awaiting_pickup.html', orders)
#app.route('/')
def deliveries_in_progress():
if not g.user:
return redirect(url_for('public_timeline'))
return render_template('deliveries_in_progress.html')
#app.route('/completed_deliveries')
def completed_deliveries():
if not g.user:
return redirect(url_for('public_timeline'))
return render_template('completed_deliveries.html')
#app.route('/deliveries_waiting_for_bids')
def deliveries_waiting_for_bids():
if not g.user:
return redirect(url_for('public_timeline'))
return render_template('deliveries_waiting_for_bids.html')
#app.route('/authenticated')
def authenticated():
db = get_db()
CODE = request.args.get('code', '')
response = requests.get("https://foursquare.com/oauth2/access_token?client_id=" + FOURSQUARE_CLIENT_ID
+ "&client_secret=" + FOURSQUARE_CLIENT_SECRET + "&grant_type=authorization_code&redirect_uri="
+ FOURSQUARE_REDIRECT_URI +"&code=" + CODE + "&sort=newestfirst")
dict = json.loads(response.text)
db.execute('insert into access_token (user_id, access_token_text) values (?, ?)',
[session['user_id'], dict['access_token']])
db.commit()
return redirect(url_for('foursquare'), code=302)
#app.route('/foursquare')
def foursquare():
"""Shows your foursquare info. Or, if you have not authorized this app to connect to
foursquare, then it will redirect you to foursquare.
"""
if not g.user:
return redirect(url_for('public_timeline'))
result = query_db('select access_token_text from access_token where user_id = ?',
[session['user_id']], one=True)
if not result:
return redirect("https://foursquare.com/oauth2/authenticate?response_type=code&client_id=" + FOURSQUARE_CLIENT_ID + "&redirect_uri=" + FOURSQUARE_REDIRECT_URI,code=302)
else:
#Get info from foursquare
token = result['access_token_text']
response = requests.get(FOURSQUARE_API_BASE + "users/self/checkins?oauth_token=" + token +
"&v=20150326&m=foursquare")
dict = json.loads(response.text)
list = dict['response']['checkins']['items']
return render_template('foursquare.html', listOfCheckins=list)
#app.route('/')
def timeline():
"""Shows a users timeline or if no user is logged in it will
redirect to the public timeline. This timeline shows the user's
messages as well as all the messages of followed users.
"""
if not g.user:
return redirect(url_for('public_timeline'))
#Get info from foursquare
result = query_db('select access_token_text from access_token where user_id = ?',
[session['user_id']], one=True)
if result:
token = result['access_token_text']
response = requests.get(FOURSQUARE_API_BASE + "users/self/checkins?oauth_token=" + token +
"&v=20150326&m=foursquare")
dict = json.loads(response.text)
item = dict['response']['checkins']['items'][0]
return render_template('timeline.html',messages=query_db('''
select message.*, user.* from message, user
where message.author_id = user.user_id and (
user.user_id = ? or
user.user_id in (select whom_id from follower
where who_id = ?))
order by message.pub_date desc limit ?''',
[session['user_id'], session['user_id'], PER_PAGE]),checkin=item)
return render_template('timeline.html',messages=query_db('''
select message.*, user.* from message, user
where message.author_id = user.user_id and (
user.user_id = ? or
user.user_id in (select whom_id from follower
where who_id = ?))
order by message.pub_date desc limit ?''',
[session['user_id'], session['user_id'], PER_PAGE]),checkin=None)
#app.route('/public')
def public_timeline():
"""Displays the latest messages of all users."""
return render_template('timeline.html', messages=query_db('''
select message.*, user.* from message, user
where message.author_id = user.user_id
order by message.pub_date desc limit ?''', [PER_PAGE]))
#app.route('/<username>')
def user_timeline(username):
"""Display's a users tweets."""
profile_user = query_db('select * from user where username = ?',
[username], one=True)
if profile_user is None:
abort(404)
followed = False
if g.user:
followed = query_db('''select 1 from follower where
follower.who_id = ? and follower.whom_id = ?''',
[session['user_id'], profile_user['user_id']],
one=True) is not None
#Get info from foursquare
result = query_db('select access_token_text from access_token where user_id = ?',
[profile_user['user_id']], one=True)
if result:
token = result['access_token_text']
response = requests.get(FOURSQUARE_API_BASE + "users/self/checkins?oauth_token=" + token +
"&v=20150326&m=foursquare")
dict = json.loads(response.text)
item = dict['response']['checkins']['items'][0]
return render_template('timeline.html', messages=query_db('''
select message.*, user.* from message, user where
user.user_id = message.author_id and user.user_id = ?
order by message.pub_date desc limit ?''',
[profile_user['user_id'], PER_PAGE]), followed=followed,
profile_user=profile_user, checkin=item)
#app.route('/<username>/follow')
def follow_user(username):
"""Adds the current user as follower of the given user."""
if not g.user:
abort(401)
whom_id = get_user_id(username)
if whom_id is None:
abort(404)
db = get_db()
db.execute('insert into follower (who_id, whom_id) values (?, ?)',
[session['user_id'], whom_id])
db.commit()
flash('You are now following "%s"' % username)
return redirect(url_for('user_timeline', username=username))
#app.route('/<username>/unfollow')
def unfollow_user(username):
"""Removes the current user as follower of the given user."""
if not g.user:
abort(401)
whom_id = get_user_id(username)
if whom_id is None:
abort(404)
db = get_db()
db.execute('delete from follower where who_id=? and whom_id=?',
[session['user_id'], whom_id])
db.commit()
flash('You are no longer following "%s"' % username)
return redirect(url_for('user_timeline', username=username))
#app.route('/add_message', methods=['POST'])
def add_message():
"""Registers a new message for the user."""
if 'user_id' not in session:
abort(401)
if request.form['text']:
db = get_db()
db.execute('''insert into message (author_id, text, pub_date)
values (?, ?, ?)''', (session['user_id'], request.form['text'],
int(time.time())))
db.commit()
flash('Your message was recorded')
return redirect(url_for('timeline'))
#app.route('/login', methods=['GET', 'POST'])
def login():
"""Logs the user in."""
if g.user:
return redirect(url_for('timeline'))
error = None
if request.method == 'POST':
user = query_db('''select * from user where
username = ?''', [request.form['username']], one=True)
if user is None:
error = 'Invalid username'
elif not check_password_hash(user['pw_hash'],
request.form['password']):
error = 'Invalid password'
else:
flash('You were logged in')
session['user_id'] = user['user_id']
return redirect(url_for('timeline'))
return render_template('login.html', error=error)
#app.route('/register', methods=['GET', 'POST'])
def register():
"""Registers the user."""
if g.user:
return redirect(url_for('timeline'))
error = None
if request.method == 'POST':
if not request.form['username']:
error = 'You have to enter a username'
elif not request.form['email'] or \
'#' not in request.form['email']:
error = 'You have to enter a valid email address'
elif not request.form['password']:
error = 'You have to enter a password'
elif request.form['password'] != request.form['password2']:
error = 'The two passwords do not match'
elif get_user_id(request.form['username']) is not None:
error = 'The username is already taken'
else:
db = get_db()
db.execute('''insert into user (
username, email, pw_hash) values (?, ?, ?)''',
[request.form['username'], request.form['email'],
generate_password_hash(request.form['password'])])
db.commit()
flash('You were successfully registered and can login now')
return redirect(url_for('login'))
return render_template('register.html', error=error)
#app.route('/api/receive_text', methods=['GET', 'POST'])
def receive_text():
"""receive a text message from Twilio."""
return
#app.route('/logout')
def logout():
"""Logs the user out."""
flash('You were logged out')
session.pop('user_id', None)
return redirect(url_for('public_timeline'))
# add some filters to jinja
app.jinja_env.filters['datetimeformat'] = format_datetime
app.jinja_env.filters['gravatar'] = gravatar_url
if __name__ == '__main__':
init_db()
app.run(host='127.0.0.1', debug=False, port=5000, ssl_context=('/Users/l/Development/Certificates/server.crt', '/Users/l/Development/Certificates/server.key'))
schema.sql:
create table user (
user_id integer primary key autoincrement,
username text not null,
email text not null,
pw_hash text not null
);
create table follower (
who_id integer,
whom_id integer
);
create table message (
message_id integer primary key autoincrement,
author_id integer not null,
text text not null,
pub_date integer
);
create table access_token (
user_id integer not null,
access_token_text text not null
);
create table completed_deliveries (
flower_order text not null,
shipping_address text not null,
total_cost real not null,
driver_name text not null,
estimated_delivery_time integer not null,
reputation text not null,
charge real not null,
arrival_estimation text not null,
picked_up_time text not null,
actual_arrival_time text not null
);
create table deliveries_in_progress (
flower_order text not null,
shipping_address text not null,
total_cost real not null,
driver_name text not null,
estimated_delivery_time integer not null,
reputation text not null,
charge real not null,
arrival_estimation text not null,
picked_up_time text not null
);
create table deliveries_awaiting_pickup (
flower_order text not null,
shipping_address text not null,
total_cost real not null,
driver_name text not null,
estimated_delivery_time integer not null,
reputation text not null,
charge real not null,
arrival_estimation text not null
);
create table deliveries_waiting_for_bids (
flower_order text not null,
shipping_address text not null,
total_cost real not null
);

On this line of deliveries_awaiting_pickup():
return render_template('deliveries_awaiting_pickup.html', orders)
I was supposed to name each variable explicitly, like this:
return render_template('deliveries_awaiting_pickup.html', orders=orders)
Then it worked.
Also, I noticed my debug was set to false accidentally. I set it to true like below. Since it was false, it was only giving "internal server error" and not a detailed debug report.
app.run(host='127.0.0.1', debug=True, port=5000, ssl_context=('/Users/l/Development/Certificates/server.crt', '/Users/l/Development/Certificates/server.key'))

Related

I have an api that manages likes and dislike for recipes but i keep getting error in my code

the Like api is supposed to check if the recipe has been liked before. If yes, it should delete and if no, it should add like to db but I get an error.
#app.route("/like/<int:id>", methods=['GET'])
#jwt_required()
def like(id):
current_user = get_jwt_identity()
if not Recipe.select().where(Recipe.id == id).exists():
return jsonify({'Status': 'Unsuccessful', 'Message': 'Recipe ID does not Exist'}), 400
like = Like.select().where(Like.recipe_id == id) & (Like.poster_id == current_user)
if like:
like = Like.delete().where(Like.recipe_id == id) & (Like.poster_id == current_user)
data = like.execute()
return jsonify({'Status': data, 'Message': 'Like Deleted'}), 204
new_like = Like.create(recipe_id = id , poster_id=current_user )
return jsonify({'Status': 'Successful', 'Message': 'You have liked a recipe'}), 200
this is the error:
File "/Users/user/PythonProject/venv/lib/python3.8/site-packages/pymysql/protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "/Users/user/PythonProject/venv/lib/python3.8/site-packages/pymysql/err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
peewee.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INTERSECT ((`t2`.`poster_id` = 2))' at line 1")
Here is the dislike API
#app.route("/dislike/<int:id>", methods=['GET'])
#jwt_required()
def dislike(id):
current_user = get_jwt_identity()
if not Recipe.select().where(Recipe.id == id).exists():
return jsonify({'Status': 'Unsuccessful', 'Message': 'Recipe ID does not Exist'}), 400
like = Like.select().where(Like.recipe_id == id)
dislike = Dislike.select().where(Dislike.recipe_id == id)
if dislike:
remove_dislike = Dislike.delete().where(Dislike.poster_id == current_user)
data = remove_dislike.execute()
return jsonify({'Status': data, 'Message': 'Dislike Deleted'}), 204
elif like:
remove_like = Like.delete().where(Like.poster_id == current_user) & (Like.recipe_id == id)
data = remove_like.execute()
return jsonify({'Status': data, 'Message': 'Like Deleted'}), 204
else:
new_dislike = Dislike.create(recipe_id = id , poster_id=current_user )
return jsonify({'Status': 'Successful', 'Message': 'You have disliked a recipe'}), 200
The second API is to dislike a recipe. i need this API to check first if the API has been like and delete it, if not check if it has been disliked, then delete else add dislike to db but it just return 1 and nothing happens in the db. I cant seem to figure out what i am doing wrong.
Here is what my model looks like;
class Like(BaseModel):
id = PrimaryKeyField(primary_key=True)
recipe_id = ForeignKeyField(Recipe, backref='comment', lazy_load=False)
post_date = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
poster_id = ForeignKeyField(Users, backref='like', lazy_load=False)
class Dislike(BaseModel):
id = PrimaryKeyField(primary_key=True)
recipe_id = ForeignKeyField(Recipe, backref='comment', lazy_load=False)
post_date = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
poster_id = ForeignKeyField(Users, backref='dislike', lazy_load=False)
I can't check it but as for me you have ( ) in wrong places and & (...) is outside where(...) and this makes problem.
You have & (...) outside where(...)
.where(Like.poster_id == current_user) & (Like.recipe_id == id)
but it should be inside where(...)
.where( (Like.poster_id == current_user) & (Like.recipe_id == id) )
Eventually it could work with two where
.where(Like.poster_id == current_user).where(Like.recipe_id == id)
And the same is in other places.
Peewee doc: Query operators

Restric logged users to access unwanted url routes in a tornado server

I am trying to restrict logged user to access URL routes that are not assigned to them. As soon a user had logged, for example user1, will be redirected to https://myurl.com/user1. So far, that works good, but I would like to avoid that user1 can see the content in the route of user2 in https://myurl.com/user2.
Below you can see the code I am currently using.
import tornado
from tornado.web import RequestHandler
import sqlite3
# could define get_user_async instead
def get_user(request_handler):
return request_handler.get_cookie("user")
# could also define get_login_url function (but must give up LoginHandler)
login_url = "/login"
db_file = "user_login.db"
connection = None
cursor = None
# optional login page for login_url
class LoginHandler(RequestHandler):
def get(self):
try:
errormessage = self.get_argument("error")
except Exception:
errormessage = ""
self.render("login.html", errormessage=errormessage)
def check_permission(self, username, password):
connection = sqlite3.connect(db_file)
cursor = connection.cursor()
cursor.execute("SELECT * FROM users WHERE username=? AND password=?", (username, password))
data = cursor.fetchone()
if username == data[1] and password == data[2]:
return True
return False
def post(self):
username = self.get_argument("username", "")
password = self.get_argument("password", "")
auth = self.check_permission(username, password)
if auth:
self.set_current_user(username)
self.redirect(self.get_argument("next", f"/{username}"))
else:
error_msg = "?error=" + tornado.escape.url_escape(
"Login failed, please try again or contact your system administrator."
)
self.redirect(login_url + error_msg)
def set_current_user(self, user):
if user:
self.set_cookie("user", tornado.escape.json_encode(user))
else:
self.clear_cookie("user")
# optional logout_url, available as curdoc().session_context.logout_url
# logout_url = "/logout"
# optional logout handler for logout_url
class LogoutHandler(RequestHandler):
def get(self):
self.clear_cookie("user")
self.redirect(self.get_argument("next", "/"))

JSON Token won't load the value after being verified

Once I get to the verify_token function it keeps executing the except statement instead of returning the value in 'id_user' and I'm not sure why. I am using these libraries. flask-login, sqlalchemy, itsdangerous for jsonwebserializer, and wtforms.
Functions
def get_reset_token(user):
serial = Serializer(app.config['SECRET_KEY'], expires_in=900) # 15 mins in seconds
return serial.dumps({'id_user':user.id}).decode('utf-8')
def verify_token(token):
serial = Serializer(app.config['SECRET_KEY'])
try:
user_id = serial.load(token)['id_user']
except:
return None
return Users.query.get('id_user')
def send_mail(user):
token = get_reset_token(user)
message = Message('Password Reset Request', recipients = [user.email], sender='noreply#gmail.com')
message.body= f'''
To Reset your password, click the following link:
{url_for('reset_token', token = token, _external = True)}
If you did not send this email, please ignore this message.
'''
mail.send(message)
ROUTES
#app.route('/password_reset', methods = ['GET', 'POST'])
def password_reset():
form = Password_request()
if request.method == "POST":
if form.validate_on_submit:
user = Users.query.filter_by(email = form.email.data).first()
send_mail(user)
flash('Check your email. Password change request has been sent')
return redirect(url_for('login'))
else:
flash('Your email was not linked to an account')
return render_template('password_reset.html', form = form)
#app.route('/password_reset/<token>', methods = ['GET', 'POST'])
def reset_token(token):
user = verify_token(token)
if user == None:
flash('The token is invalid or expired')
return redirect(url_for('password_reset'))
form = Password_success()
if form.validate_on_submit:
hashed_password=generate_password_hash(form.password.data, method = 'sha256')
user.password = hashed_password
db.session.commit()
flash('Your password has been updated!')
return redirect(url_for('signup'))
def verify_token(token):
serial = Serializer(app.config['SECRET_KEY'])
try:
user_id = serial.load(token)['id_user']
except:
return None
return Users.query.get('id_user') # this looks wrong
Shouldn't the last line of verify_token be return Users.query.get(user_id)? You're assigning the value of the token to that variable , then ignoring it and telling SQLAlchemy to find a record with the ID of the string value 'id_user' which I doubt is what you're intending to do.
def verify_token(token):
serial = Serializer(app.config['SECRET_KEY'])
try:
user_id = serial.load(token)['id_user']
except:
return None
return Users.query.get(user_id) # What happens when you change this?

Error in query, response is that row exists but value is None

I creating my first bot using Flask, Twilio, Dialogflow to be deployed at Heroku. My local development is using SQLite but final version should use POSTGRES.
Yesterday as I began to store data to local db, I started getting this error as I try to identify the user that is sending message.
The idea is that, after user is created at db, I will store every message that he sent and every response given by dialogflow. But even though the user is being created at my db, I'm failing to query for his user_id afterwards.
Since it's not an actual error, but not finding the user, I'm posting the code below and printing some parts of it that I'm being trying to use to debug.
CODE:
import os
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from twilio.twiml.messaging_response import MessagingResponse
from sportsbot.utils import fetch_reply
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///myDB.db' #path to database and its name
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False #supress warning of changes on database
db = SQLAlchemy(app)
#app.debug = True
from sportsbot.models import User, Team, Matches, Messages
#app.route('/')
def hello():
return "hello world!"
#app.route('/whatsapp', methods=['POST'])
def sms_reply():
"Check if user is new, create user at db if it is"
phone_no = int(request.form.get('From').split(':')[1][1:])
if User.query.filter(User.user_phone_no == phone_no).count() == 0:
user = User(user_phone_no=phone_no)
db.session.add(user)
db.session.commit()
print("New user")
else:
print("User already at base")
#tring to debug
print(phone_no)
user_id = User.query.filter(User.user_phone_no == phone_no).first()
print(user_id)
msg = request.form.get('Body')
reply = fetch_reply(msg,phone_no)
"Reply to it"
print(reply['text'])
print(reply['intent'])
resp = MessagingResponse()
resp.message(reply['text'])
#message = Messages(user_id = user_id, message= msg, response=reply['text'],intent=reply['intent'])
#db.session.add(message)
#try:
# db.session.commit()
#except:
# db.session.rollback()
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
User class:
class User(db.Model):
user_id = db.Column(db.Integer, primary_key=True)
user_name = db.Column(db.String(80), index = True, unique = False)
user_phone_no = db.Column(db.Integer, index = True, unique = True)
team_id = db.Column(db.Integer, db.ForeignKey('team.team_id'))
def __repr__(self):
return "{}".format(self.user_name)
Prints:
User already at base
5511990046548
None
Oi! Bem Vindo ao EsporteBot. VocĂȘ gostaria de saber sobre algum time ou quer a agenda de eventos da semana?
Default Welcome Intent
Any idea of what I'm doing wrong since it sees the user at db but cannot find it afterwards?
This code
User.query.filter(User.user_phone_no == phone_no).count()
finds 1 user
This code
user_id = User.query.filter(User.user_phone_no == phone_no).first()
gives None as answer
Code works correctly.
Problem is that in model User you created own __repr__() which displays user_name but you don't add user_name to database so it uses None as user_name and when you run first() then this __repr__() prints None as user_name - and this is why you get None on screen.
When you use
def __repr__(self):
return "name: {}".format(self.user_name)
then you get name: None instead of None
Maybe better use
def __repr__(self):
return "id: {}, name: {}, phone no: {}".format(self.user_id, self.user_name, self.user_phone_no)
to get more information.
Or simply remove __repr__ from your model and then you will see something like <User 1>
Minimal working example which everyone can execute:
import os
from flask import Flask, request, render_template_string
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///myDB.db' #path to database and its name
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False #supress warning of changes on database
db = SQLAlchemy(app)
db.create_all()
class User(db.Model):
user_id = db.Column(db.Integer, primary_key=True)
user_name = db.Column(db.String(80), index = True, unique = False)
user_phone_no = db.Column(db.Integer, index = True, unique = True)
def __repr__(self):
#return "{}".format(self.user_name)
#return "name: {}".format(self.user_name)
return "id: {}, name: {}, phone no: {}".format(self.user_id, self.user_name, self.user_phone_no)
#db.create_all()
#app.route('/')
def hello():
return render_template_string("""
<form method="POST" action="/whatsapp">
Phone <input name="From" value="James Bond:+007"></input>
<button type="submit">OK</button>
</form>
""")
#app.route('/whatsapp', methods=['POST'])
def sms_reply():
"Check if user is new, create user at db if it is"
parts = request.form.get('From').split(':')
user_name = parts[0]
phone_no = int(parts[1][1:])
if User.query.filter(User.user_phone_no == phone_no).count() == 0:
#user = User(user_phone_no=phone_no)
user = User(user_phone_no=phone_no, user_name=user_name)
db.session.add(user)
db.session.commit()
print("New user")
else:
print("User already at base")
#tring to debug
print('phone_no:', phone_no)
user = User.query.filter(User.user_phone_no == phone_no).first()
print('user:', user)
return render_template_string("""{{user}}""", user=user)
if __name__ == "__main__":
app.run(debug=True)

flask-bcrypt: check password method always return "Type error"

I'm using falsk-bcrypt and mysql connector to connect to mySQL database.
Everything looks good when I sign up in my website and store the hashed password. When I'm log in and check the user password input and compare it to the hashed password using bcrypt.check_password_hash() it always return different errors such as:
TypeError: expected string or bytes-like object
or when I change the parameters in the bcrypt.check_password_hash()method
I've tried to decode the hashed password before it stored in the database and here what I got in my database:
$2b$12$t4uE4WxdWWv5pbNNF5Njk.viBxx/3AGYJx3aUxL20kH9cb0jTfqf2
My password column is varchar(100) and I used tinytext() and the same problem appear.
Also I tried to convert the hashed password and the user input password to strings using str() method.
Here is the code to insert the password (sign up page) :
#app.route('/sign_up' , methods=['POST', 'GET'])
def sign_up():
form = register_form() # imported from forms.py file as a class
db.connect()
if form.validate_on_submit():
first_name = form.first_name.data
last_name = form.last_name.data
email = form.email.data
hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
cur.execute("SELECT email FROM users WHERE email ='%s'", (email))
email_exsist = cur.fetchone()
if email_exsist:
flash ('email is already exisist','danger')
else :
cur.execute('INSERT INTO users(first_name, last_name,email,password) VALUES(%s,%s,%s,%s)''',(first_name, last_name, email, hashed_password) )
db.commit()
flash(f'Account Successfully created for {form.first_name.data + " " + form.last_name.data} !' , 'success' )
return redirect(url_for('sign_up'))
cur.close()
return render_template('sign_up.html' , title='Sign up' , form= form)
and here is the checking if statement in the (sign in page):
#app.route('/login' , methods=['POST', 'GET'])
def login():
form = login_form()# imported from forms.py file as a class
email = form.email.data
if form.validate_on_submit():
cur.execute("SELECT email FROM users WHERE email =%s", [email])
user_email = cur.fetchone()
cur.execute("SELECT password FROM users WHERE email =%s",[email])
hashed_password = cur.fetchone()
if user_email and bcrypt.check_password_hash( hashed_password,form.password.data) :
login_user(user_email,remember=form.remember.data)
return redirect(url_for('home'))
else :
flash ('Unable to log in , please check your email and password', 'danger')
return render_template('login.html' , title='login' , form= form)
Is there anything to put on app.config or convert?

Categories

Resources