This is a base skeleton Flask project to start developing on.
You may want to modify some of the configurations and files as needed.
flask, lean, skeleton, project, structure, environment, setup, template, fullstack, web, development, app, university, education.
Open the project's dir in the terminal and run the following commands:
- pip install virtualenv
- virtualenv venv
- pip install python-dotenv
Open the project's dir in the terminal and:
- Run the command: python -c "import os; print(os.urandom(16))"
- Copy the output string
- Edit the project's .env file found inside the root folder
- Overwrite the SECRET_KEY value with the string you copied
Run the project with your IDE's configuration, or from the terminal by using the flask run command
- Edit .env file with your database details
METHOD 1 - Query the database by using the implemented DBManager module
-
A module named DBManager exists for querying the database.
-
On
.py
files you'd like to connect and query the database, use the following import:from utilities.db.db_manager import dbManager
-
Then use one of the methods
commit(query, args=())
,fetch(query, args=())
,execute(query, args=())
to query the database according to the explanation below:-
commit(query, args=())
Use this method for INSERT, UPDATE and DELETE queries.
Returns number of affected rows. -
fetch(query, args=())
Use this method for SELECT queries.
Returns:
- The query result as a list of named tuples where fields are accessible with dot notation. Read more about it here.
- False if query fails. -
execute(query, args=())
Use this method for CREATE..., ALTER... and DROP... queries.
Returns:
- True if query is successful.
- False if query fails.
Example:
from utilities.db.db_manager import dbManager query_result = dbManager.fetch('SELECT * FROM example_table') if query_result: for record in query_result: print(record.id) #prints the record's ID
-
METHOD 2 - DIY
-
On
.py
files you'd like to connect to the database, use the following imports:from settings import DB import mysql.connector
-
Connect to the database with **DB as the argument
db_connection = mysql.connector.connect(**DB)
-
Tip: If you'd like the queried results to behave like JavaScript objects then instantiate cursor as follows:
db_cursor = db_connection.cursor(named_tuple=True)
Once you do that, you'll be able access the properties with dot notation.
Read more about it here
Example:
from settings import DB import mysql.connector db_connection = mysql.connector.connect(**DB) db_cursor = db_connection.cursor(named_tuple=True) db_cursor.execute('SELECT * FROM example_table') records = db_cursor.fetchall() for record in records: print(record.id) #prints the record's ID