-1

In my flask application, I cannot insert user_id which I get from request.form and it is an integer to MySQL. Here is my code:

from flask import Flask, jsonify, render_template
from flask import request
import socket
from flask_mysqldb import MySQL

app = Flask(__name__)

app.config['MYSQL_HOST'] = '192.168.0.101'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PORT'] = '3307'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'msblog_users'
 
mysql = MySQL(app)   

@app.route("/create_post", methods = ['POST', 'GET'])
def create_post():
    if request.method == 'GET':
        return "You can only send post requests here!"

    if request.method == 'POST':
        user_id = request.form.get('user_id')
        message = request.form.get('message')
        cursor = mysql.connection.cursor()
        cursor.execute('''INSERT INTO posts (user_id, post)VALUES (%s, %s)''', (int(user_id), message))
        mysql.connection.commit()
        cursor.close()
        return "Done"

I get the following error:

TypeError: 'str' object cannot be interpreted as an integer

What should I do? I did lots of search but so far nothing!

Jamiu S.
  • 5,257
  • 5
  • 12
  • 34

3 Answers3

0

The %s stands for string, if you want you want that parameters to be an integer, make it %i.

INSERT INTO posts (user_id, post)VALUES (%i, %s) ....

If the column post is a string / text column (varchar probably) you should also quote it as such.

cursor.execute("INSERT INTO posts (user_id, post) VALUES (%i , '%s')" % (1, 'string value')

By the way, this is the old way of formatting strings

The new way is doing this:

cursor.execute("INSERT INTO posts (user_id, post) VALUES ({}, '{}')".format(1, 'string value')

Or you can name the parameters:

"INSERT INTO posts (user_id, post) VALUES ({id}, '{str}')".format( str='string value',id=1)
Roger
  • 7,535
  • 5
  • 41
  • 63
  • I Still got the same error with %i and 1 – Sajad Kamali Sep 05 '22 at 12:37
  • There's only the `%s` placeholder. Do *not* quote placeholders. Do *not* `%` interpolate placeholders, because then they're not placeholders anymore, but just injection-prone string interpolations. The parameterised SQL placeholder mechanism is *not* Python string interpolation, even if it looks very similar. – deceze Sep 05 '22 at 12:38
  • https://stackoverflow.com/a/775399/476 – deceze Sep 05 '22 at 12:43
  • @deceze, my bad, you're right.... Anyway I just sent a string, the parameters are not sent as an 2nd argument to execute. – Roger Sep 05 '22 at 12:44
  • I tried both ways but I got the same error – Sajad Kamali Sep 06 '22 at 04:30
  • @SajadKamali did you try with the "" % (...,...) ? then you sent a plain sql string, which is NOT escaped (so *not* with a comma). You can try to create first manual a SQL INSERT without the parameters. Maybe something else is wrong? – Roger Sep 06 '22 at 07:12
0

The error comes from the int(user_id) part, specifically due to the value being None. You should first make sure it is a valid integer:

try:
    user_id = int(request.form.get('user_id'))
except (ValueError, TypeError):
    return <error 400>
Michal Racko
  • 462
  • 2
  • 4
0

Finally, I found the problem. It's so strange!! the problem was not even related to the insert query. Take a look at the MySQL connection configuration part in my flask code, as you can see below:

app.config['MYSQL_HOST'] = '192.168.0.101'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PORT'] = '3307'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'msblog_users'

the port is written between quotations! it's a string but MySQL needs an integer value for the port to be able to connect!

here is the quick fix:

app.config['MYSQL_PORT'] = 3307

It took me a day to solve it!