Python: How to run flask mysqldb on Windows machine?

雨燕双飞 提交于 2019-12-13 22:07:47

问题


I've installed the flask-mysqldb module with pip package management system on my Windows machine and I don't know how to run it.

I have tried to add the path to the MySQLdb in System properties and still nothing.


回答1:


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.

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

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

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) 

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



来源:https://stackoverflow.com/questions/47015590/python-how-to-run-flask-mysqldb-on-windows-machine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!