将python连接到flask-mysqldb

时间:2018-02-11 10:48:18

标签: python mysql

安装db:

pip install flask-mysqldb

使用xampp创建我的数据库localy 设置配置

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)

当我运行服务器时,它正常工作并在向数据库插入任何内容时为post方法提供200状态,但是当我尝试检查没有插入或保存在数据库中时,如何使其工作?

2 个答案:

答案 0 :(得分:1)

看起来你正在做正确的事情,除了处理路线的奇怪方式。

提供:

  1. 您正在使用默认参数在开发模式下运行Flask,即开发服务器侦听localhost:5000
  2. index.html包含指向http://localhost:5000/add
  3. 的链接
  4. 添加后,您想重定向回http://localhost:5000
  5. 此代码应该有效:

    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)
    

    我更新的内容:

    1. 删除/add的第一条路线,因为它似乎没必要,
    2. 添加了密钥,
    3. 重新组织了添加/add路由处理重定向/呈现的方式。
    4. 通过查看数据库插入处理,它看起来很好。可能路线确实干扰了你的意图。

答案 1 :(得分:0)

尝试这样做:

services:
  camping.helper_controller:
      class: CampingBundle\Controller\HelperController
      arguments: ["@doctrine.orm.entity_manager"]
相关问题