abeerShami
abeerShami

Reputation: 665

connect python to flask-mysqldb

install the db:

pip install flask-mysqldb

create my database localy using xampp setting the config

from flask import Flask, render_template, flash, redirect, url_for, request, 
logging
from wtforms import Form, StringField, TextAreaField, validators
from flask_mysqldb import MySQL

app = Flask (__name__)
# Config MySQL
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'todo'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'

# init MYSQL
mysql = MySQL(app)
@app.route('/')
def index():
return render_template('index.html')


@app.route('/add')
def task():
return render_template('add.html')

# Task Form Class
class TaskForm(Form):
name = StringField('Name', [validators.Length(min=1, max=55)])
description = TextAreaField('Description', [validators.Length(min=5)])

# Add task
@app.route('/add', methods=['GET', 'POST'])
def add():
    form = TaskForm(request.form)
    if request.method == 'POST' and form.validate():
    name = form.name.data
    description = form.description.data

    # Create Cursor
    cur = mysql.connection.cursor()

    # Execute
    cur.execute("INSERT INTO todotask(name, description) VALUES(%s, %s)",
    (name, description))

    # Commit to DB
    mysql.connection.commit()

    #Close connection
    cur.close()

    flash('the task created ', 'success')

    return redirect(url_for('add'))

return render_template('index.html', form=form)
if __name__ == '__main__':
app.run(debug = True)

when I run the server it's working normally and give me 200 status for the post method when inserting any thing to the db but when I'm trying to check nothing insert or saved in the db , how can I make it work?

Upvotes: 2

Views: 12092

Answers (2)

Ilija
Ilija

Reputation: 1604

It looks like you are doing everything right, except odd way of handling routes.

Provided that:

  1. you are running Flask in development mode with default parameters i.e. development server listens on localhost:5000,
  2. index.html contains link to http://localhost:5000/add,
  3. after adding you want to redirect back to http://localhost:5000.

this code should work:

from flask import Flask, render_template, flash, \
redirect, url_for, request, logging
from wtforms import Form, StringField, TextAreaField, validators
from flask_mysqldb import MySQL

app = Flask (__name__)
# Config MySQL
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'todo'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'

# TODO Update secret key
app.secret_key = 'UPDATETHISPART'

# init MYSQL
# mysql = MySQL(app)


# Task Form Class
class TaskForm(Form):
    name = StringField('Name', [validators.Length(min=1, max=55)])
    description = TextAreaField('Description', [validators.Length(min=5)])


@app.route('/')
def index():
    return render_template('index.html')


# Add task
@app.route('/add', methods=['GET', 'POST'])
def add():
    form = TaskForm(request.form)
    if request.method == 'POST' and form.validate():
        name = form.name.data
        description = form.description.data

        # Create Cursor
        cur = mysql.connection.cursor()

        # Execute
        cur.execute("INSERT INTO todotask(name, description) VALUES(%s, %s)", (name, description))

        # Commit to DB
        mysql.connection.commit()

        # Close connection
        cur.close()

        flash('the task created ', 'success')

        return redirect(url_for('index'))

    return render_template('add.html', form=form)


if __name__ == '__main__':
    app.run(debug=True)

What I have updated:

  1. Removed first route for /add since it seems like it is unnecessary,
  2. Added secret key,
  3. Reorganized how adding in /add route handles redirects/rendering.

By looking at the db insert handling, it looks just fine. Probably routes did interfere with what you intended.

Upvotes: 2

WholesomeGhost
WholesomeGhost

Reputation: 1121

Try doing it like this:

conn = mysql.connect()

cur = conn.cursor()

cur.execute("INSERT INTO todotask(name, description) VALUES(%s, %s)",
(name, description))

conn.commit()

Upvotes: 0

Related Questions