What changes need to be made for my pask application for Flask to use the MySQL database?

I am new to application development and I tried to get to know this with Flask. I followed their wonderful tutorial and read their documentation in the same detail to create my first base application that uses the SQLite3 database.

To accomplish this and in accordance with their instructions, I imported the following:

from __future__ import with_statement from contextlib import closing import sqlite3 from flask import Flask, request, session, g, redirect, url_for, \ abort, render_template, flash 

and to configure the database with the schema.sql file schema.sql perform the following settings:

 drop table if exists entries; create table entries ( id integer primary key autoincrement, title string not null, text string not null ); 

I access the database using the commands that reappeared in the Flask Tutorial . I get the impression that when creating applications in which users create their own accounts and manage them, I need to create a MySQL database. In this case, what things about my code related to the database do I need to change? I am sure that there is a big difference between working with these two databases, so any recommendation - usage tips or documentation for reading - would be greatly appreciated.

Thank you very much in advance.

+4
source share
1 answer

I will not answer your question directly, but instead I will give you a good alternative to your current approach.

Instead of manipulating the database using SQL, why not use the OOP approach with SQLAlchemy ?

Here is a rough translation of your current code:

 # ... from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__.split('.')[0]) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///path/database.db' #app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://user: pass@localhost /database' db = SQLAlchemy(app) class Entry(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.Text) text = db.Column(db.Text) def __init__(self, title, text): self.title = title self.text = text def uppercase(self): self.title = self.title.upper() self.text = self.text.upper() 

Notice how the data structure is database independent. You can switch from SQLite to MySQL simply by changing one configuration line.

Initializing a database is just as simple:

 $ python -c "from your_app import db; db.create_all()" 

Working with the database is even easier:

 entry = Entry('test', 'entry') entry.uppercase() db.session.add(entry) db.session.commit() 

Just an offer.

+5
source

Source: https://habr.com/ru/post/1444252/


All Articles