且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:如何在Windows计算机上运行flask mysqldb?

更新时间:2022-12-24 22:08:52

在Windows中使用Flask和MySQL时,我使用

When I work with Flask and MySQL in Windows, I use XAMPP that includes MariaDB, PHP, and Perl. I run the XAMPP server and start MySQL service.

我使用 Flask-MySQL ,可以使用pip install Flask-MySQL安装.

I use Flask-MySQL which can be installed using pip install Flask-MySQL.

然后我从XAMPP附带的phpMyAdmin创建数据库.在Flask应用中,我声明了连接并操作了数据库.

Then I create database from phpMyAdmin which comes with XAMPP. In Flask app, I declare the connection and manipulate the database.

以下是此Python文件中有关如何在MySQL中使用Flask的演示:

Here is a demonstration of how to use Flask with MySQL in this Python file:

from flask import Flask
from flask import request
from flask import render_template
from flaskext.mysql import MySQL

app = Flask(__name__)

mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'matrimony'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

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

@app.route('/create_table', methods=['POST'])
def create_table():
    if request.method=="POST":
        try:
            table_name = request.form.get('table_name')
            field_name_list = request.form.getlist('fields[]')
            field_list = []
            for field in field_name_list:
                field_list.append(field+ " VARCHAR(50) DEFAULT NULL")
            field_query = " ( " + ", ".join(field_list) + " ) "
            create_table_query = 'CREATE TABLE `'+table_name+'`' + field_query
            conn = mysql.connect()
            cursor = conn.cursor()
            cursor.execute(create_table_query)
            return "Table: "+table_name+" created successfully"
        except Exception as e:
            return str(e)

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

在此示例中,我从用户输入创建了带有用户提到的列名的MySQL表.

In this example, I created MySQL table from user input with user mentioned column names.