All Courses

Explain database connection in Python Flask?

By Ganesh, 2 years ago
  • Bookmark
0

how to connect flask app to database?

Flask
Python
1 Answer
0

Flask supports database powered application (RDBS). Such system requires creating a schema, which requires piping the shema.sql file into a sqlite3 command. So you need to install sqlite3 command in order to create or initiate the database in Flask.

Flask allows to request database in three ways

  1. Before_request() : They are called before a request and pass no arguments
  2. After_request() : They are called after a request and pass the response that will be sent to the client
  3. Teardown_request(): They are called in situation when exception is raised, and response are not guaranteed.

They are called after the response been constructed. They are not allowed to modify the request, and their values are ignored.


Example :

import sqlite3  
  
con = sqlite3.connect("employee.db")  
print("Database opened successfully")  
  
con.execute("create table Employees (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT UNIQUE NOT NULL, address TEXT NOT NULL)")  
  
print("Table created successfully")  
  
con.close()  

Your Answer

Webinars

Why You Should Learn Data Science in 2023?

Jun 8th (7:00 PM) 289 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More