1

So I am in the midst of adding chat history to my flask website. In order to do that, I have to first save the messages and room id in a separate class. However, I am getting an error for some reason while trying to save these messages. Could someone guide me on how to save the messages without getting an error? I have put the code below. Thank you. I am trying to do this because of the solution provided to one of my other questions. So if you do not find any issues in this, please go to this link to view my question and the answer provided to get further clarity.

main.py

 from flask import Flask, request, session, render_template, redirect, url_for, flash, get_flashed_messages, jsonify from flask.globals import current_app from flask_login import LoginManager, login_user, login_required, logout_user, current_user, UserMixin, AnonymousUserMixin from datetime import timedelta, datetime from werkzeug.security import generate_password_hash, check_password_hash import sqlite3 from os import error, path from flask_sqlalchemy import SQLAlchemy import random from flask_socketio import SocketIO, join_room, leave_room, emit from flask_session import Session app = Flask(__name__) DB_NAME = "spark.db" app.config["SECRET_KEY"] = "1986319249872139865432" app.config['SQLALCHEMY_DATABASE_URI'] = f"sqlite:///{DB_NAME}" app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.config['SESSION_TYPE'] = 'filesystem' Session(app) socketio = SocketIO(app, manage_session=False) db = SQLAlchemy(app) db.init_app(app) def create_database(app): if not path.exists(DB_NAME): db.create_all(app=app) print("Created Database!") class Tutor(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) tremail = db.Column(db.String(10000)) trusername = db.Column(db.String(1200)) subjects = db.Column(db.String(1200)) session_length = db.Column(db.String(1200)) class Messages(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) room_id = db.Column(db.String(1200), unique=True, nullable=False) content = db.Column(db.String(10000)) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(150), unique=True) username = db.Column(db.String(150), unique=True) password = db.Column(db.String(150)) tutors = db.relationship('Tutor') create_database(app) login_manager = LoginManager() login_manager.login_view = 'login' login_manager.init_app(app) @login_manager.user_loader def load_user(id): return User.query.get(int(id)) @app.route("/") @login_required def home(): return render_template("index.html") @app.route("/login", methods=["GET", 'POST']) def login(): if request.method == "POST": email = request.form.get('email') password = request.form.get('password') user = User.query.filter_by(email=email).first() if user: if check_password_hash(user.password, password): flash('Login successful!', category="success") login_user(user, remember=True) return redirect(url_for("home")) else: flash('Incorrect password! Please try again.', category="error") else: flash("Account does not exist. Please register to continue.", category="error") return render_template("login.html", user=current_user) @app.route("/register", methods=["GET", "POST"]) def register(): if request.method == 'POST': email = request.form.get('email') username = request.form.get('username') password1 = request.form.get('password1') password2 = request.form.get('password2') user = User.query.filter_by(email=email).first() if user: flash("Email already exists.", category="error") elif len(email) < 4: flash("Email must be greater than 3 characters.", category="error") elif len(username) < 2: flash("Username must be greater than 1 character.", category="error") elif password1 != password2: flash("Passwords do not match! Please try again.", category="error") elif len(password1) < 8: flash("Password must be greater than 7 characters.", category="error") else: new_user = User(email=email, username=username, password=generate_password_hash(password1, method='sha256')) db.session.add(new_user) db.session.commit() login_user(new_user, remember=True) flash("Account successfully created!", category="success") return redirect(url_for('home')) return render_template("register.html", user=current_user) @app.route("/logout") @login_required def logout(): logout_user() flash("Logged out succcessfully!", category="success") return redirect(url_for('login')) @app.route("/selection") @login_required def selection(): return render_template("selection.html") @app.route("/tutorform", methods=['GET', 'POST']) @login_required def tutorform(): if request.method == 'POST': email = request.form.get('email') tremail = request.form.get('tremail') trusername = request.form.get('trusername') subjects = request.form.get('subjects') session_length = request.form.get('session_length') new_tutor = Tutor(user_id=current_user.id, tremail=tremail, trusername=trusername, subjects=subjects, session_length=session_length) db.session.add(new_tutor) db.session.commit() flash('Entry has been saved!', category='success') return redirect(url_for("display")) return render_template("tutorform.html", user=current_user) @app.route("/tutoreeform", methods=['GET', 'POST']) @login_required def tutoreeform(): if request.method == 'POST': flash("Tutoree Entry Successful!", category='success') return redirect(url_for("display")) return render_template("tutoreeform.html") @app.route("/display") @login_required def display(): users = Tutor.query.all() return render_template("display.html", users=users) @login_required @app.route('/chat', methods=['GET', 'POST']) def chat(): if(request.method=='POST'): username = current_user.username room = request.form['room'] #Store the data in session session['username'] = username session['room'] = room return render_template('chat.html', session = session) else: if(current_user.username is not None): return render_template('chat.html', session = session) else: return redirect(url_for('chatselection')) class Anonymous(AnonymousUserMixin): def __init__(self): self.username = 'Guest' @socketio.on('join', namespace='/chat') @login_required def join(message): room = session.get('room') join_room(room) emit('status', {'msg': current_user.username + ' has entered the room.'}, room=room) @socketio.on('text', namespace='/chat') @login_required def text(message): room = session.get('room') message = Messages(room_id=room, content=message) db.session.add(message) db.session.commit() emit('message', {'msg': session.get('username') + ' : ' + message['msg']}, room=room) @socketio.on('left', namespace='/chat') @login_required def left(message): room = session.get('room') leave_room(room) session.clear() emit('status', {'msg': current_user.username + ' has left the room.'}, room=room) @app.route("/chatselection", methods=['GET', 'POST']) def chatselection(): return render_template("chatselection.html") if __name__ == '__main__': db.create_all() socketio.run(app, debug=True) 

chat.html

{% extends "base.html" %} {% block title %}SparkWIT | | Chat{% endblock %} {% block content %} <div class="chatwindow"> <center><h2 style="color: beige;">SparkWIT Babbles!</h2></center> <center><h3 style="color: beige;">Room : {{session['room']}}</h3></center><br> <center><textarea id="chat" cols="90" rows="12" placeholder="No messages yet. Start one..."></textarea><br /><br /></center> <div> <center><div class="buttonIn"> <input type="text" id="text" name="text" size="75" placeholder="Enter your message here" /> <button type="button" id="send" class="btn btn-success">SEND</button> <br> <br> </div></center> <center><button type="button" class="btn btn-danger" onclick=leave_room()>Leave this Chat</button></center> </div> {% endblock %} 

chatselection.html

{% extends "base.html" %} {% block title %}SparkWIT | | Chat Selection{% endblock %} {% block content %} <center><h1 class="h2 mb-3 font-weight-normal" style="color: beige;">SparkWIT Babbles</h1><br><br></center> <br> <hr> <form class="form-signin" action="{{url_for('chat')}}" method="POST"> <input type="text" id="room" name="room" class="form-control" placeholder="Room Code" required><br> <button class="btn btn-lg btn-primary btn-block" value="submit">Create/Join Room</button> </form> <br> {% endblock %} 

base.html

 <!DOCTYPE html> <html> <head> <title >{% block title %}{% endblock %}</title> <link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='style.css') }}"> <link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='bootstrap.min.css') }}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script> <!-- Bootstrap core JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <!-- Plugin JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/js/stylish-portfolio.min.js"></script> <script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script> <script src="https://cdn.socket.io/3.1.3/socket.io.min.js" integrity="sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh" crossorigin="anonymous"></script> <script type="text/javascript" charset="utf-8"> var socket; $(document).ready(function(){ socket = io.connect('http://' + document.domain + ':' + location.port + '/chat'); socket.on('connect', function() { socket.emit('join', {}); }); socket.on('status', function(data) { $('#chat').val($('#chat').val() + '<' + data.msg + '>\n'); $('#chat').scrollTop($('#chat')[0].scrollHeight); }); socket.on('message', function(data) { $('#chat').val($('#chat').val() + data.msg + '\n'); $('#chat').scrollTop($('#chat')[0].scrollHeight); }); $('#send').click(function(e) { text = $('#text').val(); $('#text').val(''); socket.emit('text', {msg: text}); }); }); function leave_room() { socket.emit('left', {}, function() { socket.disconnect(); // go back to the login page window.location.href = "{{ url_for('display') }}"; }); } </script> </head> <body style="background-image: url(https://media.istockphoto.com/photos/abstract-glittering-dna-helix-with-depth-of-field-over-dark-space-picture-id1201193016?k=6&m=1201193016&s=612x612&w=0&h=_H80RaLa4OYIiT136j_cFgm-YRHAiV4wmaSkSKAMFbQ=)"> <nav class="navbar navbar-expand-lg navbar-dark" style="background-color: #549bf773;"> <a class="navbar-brand" href="/"> <img src="{{url_for('static', filename='logo.jpg')}}" alt="" width="40"> </a> <a class="navbar-brand" href="/" style="color: rgb(22, 9, 3);"><i><b style="font-family: fantasy; font-size: larger;">SparkWIT</b></i></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> {% if current_user.is_authenticated %} <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/" style="color: rgb(37, 20, 13);"><b><i>Home</i></b> <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="/selection" style="color: rgb(37, 20, 13);"><b><i>Selection</i></b> <span class="sr-only">(current)</span></a> </li> </ul> <a class="nav-link" href="/logout"><button type="button" class="btn btn-outline-danger" style="color: rgb(0, 0, 0);"><b>Logout</b></button></a> {% else %} <a class="nav-link" href="/login"><button type="button" class="btn btn-outline-light"><b>Login</b></button></a> <a class="nav-link" href="/register"><button type="button" class="btn btn-outline-warning"><b>Register</b></button></a> {% endif %} </div> </nav> {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} {% if category == "error" %} <div class="alert alert-danger alter-dismissable fade show" role="alert"> {{ message }} <button type="button" class="close" data-dismiss="alert"> <span aria-hidden="true">&times;</span> </button> </div> {% endif %} {% if category == "success" %} <div class="alert alert-success alter-dismissable fade show" role="alert"> {{ message }} <button type="button" class="close" data-dismiss="alert"> <span aria-hidden="true">&times;</span> </button> </div> {% endif %} {% endfor %} {% endif %} {% endwith %} <div class="container"> {% block content %}{% endblock %} </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> 

This is the error I'm getting by the way.

 Exception in thread Thread-32: Traceback (most recent call last): File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\engine\base.py", line 1276, in _execute_context self.dialect.do_execute( File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\engine\default.py", line 593, in do_execute cursor.execute(statement, parameters) sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\Everyday_Uses\lib\threading.py", line 954, in _bootstrap_inner self.run() File "D:\Everyday_Uses\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "D:\Everyday_Uses\lib\site-packages\socketio\server.py", line 680, in _handle_event_internal r = server._trigger_event(data[0], namespace, sid, *data[1:]) File "D:\Everyday_Uses\lib\site-packages\socketio\server.py", line 704, in _trigger_event return self.handlers[namespace][event](*args) File "D:\Everyday_Uses\lib\site-packages\flask_socketio\__init__.py", line 283, in _handler return self._handle_event(handler, message, namespace, sid, File "D:\Everyday_Uses\lib\site-packages\flask_socketio\__init__.py", line 751, in _handle_event ret = handler(*args) File "D:\Everyday_Uses\lib\site-packages\flask_login\utils.py", line 272, in decorated_view return func(*args, **kwargs) File "d:\Everyday_Uses\Programming\SparkWIT\main.py", line 200, in text db.session.commit() File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\orm\scoping.py", line 163, in do return getattr(self.registry(), name)(*args, **kwargs) File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\orm\session.py", line 1042, in commit self.transaction.commit() File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\orm\session.py", line 504, in commit self._prepare_impl() File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\orm\session.py", line 483, in _prepare_impl self.session.flush() File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\orm\session.py", line 2536, in flush self._flush(objects) File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\orm\session.py", line 2678, in _flush transaction.rollback(_capture_exception=True) File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\util\langhelpers.py", line 68, in __exit__ compat.raise_( File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\util\compat.py", line 182, in raise_ raise exception File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\orm\session.py", line 2638, in _flush flush_context.execute() File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\orm\unitofwork.py", line 422, in execute rec.execute(self) File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\orm\unitofwork.py", line 586, in execute persistence.save_obj( File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\orm\persistence.py", line 239, in save_obj _emit_insert_statements( File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\orm\persistence.py", line 1135, in _emit_insert_statements result = cached_connections[connection].execute( File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\engine\base.py", line 1011, in execute return meth(self, multiparams, params) File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\sql\elements.py", line 298, in _execute_on_connection return connection._execute_clauseelement(self, multiparams, params) File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\engine\base.py", line 1124, in _execute_clauseelement ret = self._execute_context( File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\engine\base.py", line 1316, in _execute_context self._handle_dbapi_exception( File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\engine\base.py", line 1510, in _handle_dbapi_exception util.raise_( File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\util\compat.py", line 182, in raise_ raise exception File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\engine\base.py", line 1276, in _execute_context self.dialect.do_execute( File "C:\Users\aarya\AppData\Roaming\Python\Python39\site-packages\sqlalchemy\engine\default.py", line 593, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.InterfaceError: (sqlite3.InterfaceError) Error binding parameter 1 - probably unsupported type. [SQL: INSERT INTO messages (room_id, content) VALUES (?, ?)] [parameters: ('test', {'msg': 'gsefasd'})] (Background on this error at: http://sqlalche.me/e/13/rvf5) 
4
  • better you share login.html file or any files required to test your code. Commented May 10, 2021 at 21:16
  • Please check the room_id, it may not have the correct type. Commented May 10, 2021 at 21:29
  • Could you please explain what you mean by the correct room_if type? Commented May 10, 2021 at 22:14
  • is it string or not? Check it by executing. It might have a different that you do not expect. Commented May 10, 2021 at 22:39

1 Answer 1

1

As you do not provide a minimum code (MRC) to test it, I can only help you where to check for the problem.

From your code your room_id is : room_id = db.Column(db.String(1200), unique=True, nullable=False)

But when you execute your code, your variable in message may be different;

room = session.get('room') # HERE CHECK room_id type, what is the type of room here? message = Messages(room_id=room, content=message) db.session.add(message) db.session.commit() 

if there is no problem with room_id, then check all of your variable in your db and their type.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.