Python flask with mysql

Welcome to Flask-MySQLdb’s documentation!¶

Flask-MySQLdb depends, and will install for you, recent versions of Flask (0.12.4 or later) and mysqlclient. Flask-MySQLdb is compatible with and tested on Python 2.7, 3.5, 3.6 and 3.7.

Next, add a MySQL instance to your code:

from flask import Flask from flask_mysqldb import MySQL app = Flask(__name__) mysql = MySQL(app) @app.route('/') def users(): cur = mysql.connection.cursor() cur.execute('''SELECT user, host FROM mysql.user''') rv = cur.fetchall() return str(rv) if __name__ == '__main__': app.run(debug=True) 

Configuration¶

MySQL understands the following configuration directives:

MYSQL_HOST name of host to connect to. Default: use the local host via a UNIX socket (where applicable)
MYSQL_USER user to authenticate as. Default: current effective user.
MYSQL_PASSWORD password to authenticate with. Default: no password.
MYSQL_DB database to use. Default: no default database.
MYSQL_PORT TCP port of MySQL server. Default: 3306.
MYSQL_UNIX_SOCKET location of UNIX socket. Default: use default location or TCP for remote hosts.
MYSQL_CONNECT_TIMEOUT Abort if connect is not completed within given number of seconds. Default: 10
MYSQL_READ_DEFAULT_FILE MySQL configuration file to read; see the MySQL documentation for mysql_options().
MYSQL_USE_UNICODE If True, CHAR and VARCHAR and TEXT columns are returned as Unicode strings, using the configured character set.
MYSQL_CHARSET If present, the connection character set will be changed to this character set, if they are not equal. Default: ‘utf-8’
MYSQL_SQL_MODE If present, the session SQL mode will be set to the given string.
MYSQL_CURSORCLASS If present, the cursor class will be set to the given string.

Classes¶

Attempts to connect to the MySQL server.

Returns: Bound MySQL connection object if successful or None if unsuccessful.

init_app ( app ) ¶

Initialize the app for use with this MySQL class. This is called automatically if app is passed to __init__() .

Parameters: app (flask.Flask) – the application to configure for use with this MySQL class.

History¶

  • 0.2.0: September 5, 2015 — Added option to change the cursor. Thanks to @Sp1tF1r3 on GitHub.
  • 0.1.1: February 14, 2015 — Initial Release

Источник

Flask-MySQL¶

Flask-MySQL is a Flask extension that allows you to access a MySQL database.

Читайте также:  Php импорт функции из файла

You can report bugs and discuss features on the issues page.

Installation¶

Use pip to install flask-mysql :

Configuration¶

To configure access to your MySQL database server by using these settings :

MYSQL_DATABASE_HOST default is ‘localhost’
MYSQL_DATABASE_PORT default is 3306
MYSQL_DATABASE_USER default is None
MYSQL_DATABASE_PASSWORD default is None
MYSQL_DATABASE_DB default is None
MYSQL_DATABASE_CHARSET default is ‘utf-8’

Usage¶

from flaskext.mysql import MySQL mysql = MySQL() mysql.init_app(app) 
cursor = mysql.get_db().cursor() 

Multiple connection example:

from flaskext.mysql import MySQL

mysql_1 = MySQL(app, prefix=”mysql1”, host=os.getenv(“db_host”), user=os.getenv(“db_username”),password=os.getenv(“db_pass”),db=os.getenv(“db_name), autocommit=True, cursorclass=pymysql.cursors.DictCursor) mysql_2 = MySQL(app, prefix=”mysql2”, host=”host2”, user=”UN”, passwd=”&&”, db=”DB”,autocommit=True,cursorclass=pymysql.cursors.DictCursor)

@app.route(‘/’) @app.route(‘/index’) def hello():

Источник

Создание веб-приложения с использованием Python Flask и MySQL

В этой серии мы будем использовать Python, Flask и MySQL для создания простого веб-приложения с нуля. Это будет приложение списка дел, в котором пользователи смогут зарегистрироваться, подписаться и создать свой список желаний.

Предполагается, что у вас есть базовые знания языка программирования Python . Мы будем использовать Flask , инфраструктуру веб-приложений Python для создания приложения и MySQL как сервер.

Введение в Python Flask

Flask — это фреймворк Python для создания веб-приложений. С официального сайта,

Когда мы думаем о Python, первое, что приходит нам в голову, — это Django framework. Но с точки зрения новичка в Python, начинать с Flask легче, чем с Django.

Установка Flask

Установить Flask легко и просто. С менеджером пакетов pip нужно сделать только:

Когда вы закончите установку Flask, создайте папку FlaskApp . Перейдите в папку FlaskApp и создайте файл с именем app.py . Импортируйте модуль flask и создайте приложение с помощью Flask, как показано ниже:

Теперь определим основной путь / и соответствующий ему обработчик запросов:

Затем проверьте, является ли исполняемый файл главной программой и запустите приложение:

Сохраните изменения и выполните app.py :

Укажите браузеру на http://localhost:5000/ и у вас должно появиться приветственное сообщение.

Создание домашней страницы

Во-первых, при запуске приложения мы должны показать домашнюю страницу с последними элементами списка дел, добавленными пользователями. Итак, добавим нашу домашнюю страницу в папку приложения.

Flask ищет файлы шаблонов внутри папки templates . Перейдите в папку PythonApp и создайте папку под названием templates . Внутри templates создайте файл index.html . Откройте index.html и пропишите следующий HTML:

 Python Flask Bucket List App 
 href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"> 
 href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet"> 
 class="nav nav-pills pull-right"> 
 role="presentation" class="active"> href="#">Home 
 role="presentation"> href="#">Sign In 
 role="presentation"> href="showSignUp">Sign Up 
 class="text-muted">Python Flask App 

class="btn btn-lg btn-success" href="showSignUp" role="button">Sign up today

 Donec id elit non mi porta gravida at eget metus. Maecenas faucibus mollis interdum. 
 Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cras mattis consectetur purus sit amet fermentum. 
 Maecenas sed diam eget risus varius blandit sit amet non magna. 
 Donec id elit non mi porta gravida at eget metus. Maecenas faucibus mollis interdum. 
 Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cras mattis consectetur purus sit amet fermentum. 
 Maecenas sed diam eget risus varius blandit sit amet non magna. 

Откройте app.py и импортируйте render_template , который мы будем использовать для рендеринга файлов шаблонов.

from flask import Flask, render_template 

Измените основной метод, чтобы вернуть созданный файл шаблона.

return render_template('index.html') 

Сохраните изменения и перезапустите сервер. Указав браузеру http://localhost:5000/ вы увидите следующее:

Bucket List App home page

Создание страницы регистрации

Шаг 1. Настройка базы данных

Мы будем использовать MySQL в качестве сервера. Войдите в MySQL из командной строки или, если вы предпочитаете GUI, например, MySQL work bench, тоже можете пользоваться. Сначала создайте базу данных BucketList . Из командной строки:

Введите требуемый пароль и при входе в систему выполните следующую команду для создания базы данных:

CREATE DATABASE BucketList; 

Как только база данных будет создана, создайте таблицу tbl_user , как показано ниже:

CREATE TABLE `BucketList`.`tbl_user` ( 
`user_id` BIGINT NULL AUTO_INCREMENT, 
`user_username` VARCHAR(45) NULL, 
`user_password` VARCHAR(45) NULL, 

Мы будем использовать Stored procedures в приложении Python для взаимодействия с базой данных MySQL. Поскольку таблица tbl_user была создана, создайте процедуру сохранения под названием sp_createUser , чтобы зарегистрировать пользователя.

При создании этой процедуры в таблице tbl_user сначала нужно проверить, не существует ли пользователь с тем же именем username . Если существует, нам нужно выдать ошибку, иначе мы создадим пользователя в таблице user. Вот как должна выглядеть процедура sp_createUser :

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_createUser`( 

Источник

Flask MySQL – Setting up a Flask and MySQL Database Connection

Flask Mysql

In this article, we will learn how to set up a Flask MySQL database connection. So let’s get started!!

Structured Query Language

SQL allows us to access and manipulate databases. In SQL, we can perform various tasks such as:

  • Adding records to databases
  • Creating tables
  • Perform CRUD (Create, Read, Update, Delete) operations

SQL is the query language that the database systems use. To set-up databases, we require RDMS like MySQL, PostgreSQL etc.

Do check out our SQL tutorial on the JournalDev website to gain more knowledge about the query language.

More about MySQL Database Tables

Let us now look at a typical MySQL DB table:

Xampp

2. Start Apache and MySQL

Once XAMPP is installed and loaded, start the following two processes:

  • Apache Webserver – to serve HTTP requests
  • MySQL Server – for the database

Xampp

Do note the default port for MySQL is 3306. Now in the browser, go to https://localhost.

Xampp Host Webpage

This is the Host webpage for Xampp. Click on phpMyAdmin on the top right, to go to the php web interface.

Phpmyadmin

  • Create a new Database by clicking new in the left column.
  • Keep a suitable Name for the DB. In my case, it is simply Flask

Flask DB

Go ahead and create a table in the DB. Enter the table name in the space given as shown in the picture and hit Go.

3. Installing Flask- MySQL library in our system

Flask uses flask_mysqldb connector to use MySQL. Run the following command to install the package:

pip install flask_mysqldb

Setting up a Flask MySQL Database Connection

Now we will connect and use MySQL to store data into our DB. If you’re not sure how to create a flask application, check out the flask introduction tutorial.

1. Connecting Flask Application with MySQL

The procedure we follow to connect Flask-MySQL is as follows:

from flask import Flask,render_template, request from flask_mysqldb import MySQL app = Flask(__name__) app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = '' app.config['MYSQL_DB'] = 'flask' mysql = MySQL(app)

2. Setting up MySQL connection cursor

Just with the above set-up, we can’t interact with DB tables. For that, we need something called a cursor.

So Cursor provides a way for Flask to interact with the DB tables. It can scan through the DB data, execute different SQL queries, and as well as Delete table records.

The cursor is used in the following way:

mysql = MySQL(app) #Creating a connection cursor cursor = mysql.connection.cursor() #Executing SQL Statements cursor.execute(''' CREATE TABLE table_name(field1, field2. ) ''') cursor.execute(''' INSERT INTO table_name VALUES(v1,v2. ) ''') cursor.execute(''' DELETE FROM table_name WHERE condition ''') #Saving the Actions performed on the DB mysql.connection.commit() #Closing the cursor cursor.close()

Since MySQL is not an auto-commit DB, we need to commit manually, ie, save the changes/actions performed by the cursor execute on the DB .

3. Coding a Flask application

Now we will build a small Flask application that will store data submitted by the user in the MySQL DB Table. Consider the following Application Code:

from flask import Flask,render_template, request from flask_mysqldb import MySQL app = Flask(__name__) app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = '' app.config['MYSQL_DB'] = 'flask' mysql = MySQL(app) @app.route('/form') def form(): return render_template('form.html') @app.route('/login', methods = ['POST', 'GET']) def login(): if request.method == 'GET': return "Login via the login Form" if request.method == 'POST': name = request.form['name'] age = request.form['age'] cursor = mysql.connection.cursor() cursor.execute(''' INSERT INTO info_table VALUES(%s,%s)''',(name,age)) mysql.connection.commit() cursor.close() return f"Done!!" app.run(host='localhost', port=5000)

When the user submits the data, it is added into the MySQL DB via the cursor.execute command. My table name is info_table.

The form.html will be:

4. Implementing the Code

Now fire up the server and go to “/form” (see Flask forms)

Form

Enter the details and hit Submit

Success

Now let’s check it in the phpMyAdmin web interface

Php

Conclusion

That’s it, guys!! This was all about setting up Flask MySQL connections. In the next article, we will look into Flask-PostgreSQL.

Источник

Оцените статью