简体   繁体   中英

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?

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 ie 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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM