Matrix21
Matrix21

Reputation: 115

Global Variables/Functions in Flask app

I'm new to Flask and Python and am currently creating a small web app. The files it has are: Main (Just runs the app), Activate, Checkout, Payment.

I have a bunch of redundant code and variables throughout the 3 other pages such as:

Would I be able to just put the functions and variables inside Main.py and just import it to the other 3 files? Would that be good practice? Would it be a problem if some of those other files would access a variable or function from Main at the same time? For example: Checkout and Payment may somehow be accessing the verifyShopifyWebhook() function at the same time since they are run when Shopify sends a webhook to either address.

I also have a bunch of the same imports on Activate, Checkout and Refund. Can I just put the same ones all under Main and import them from Main?

Upvotes: 0

Views: 1348

Answers (1)

Grey Li
Grey Li

Reputation: 12762

Credential variables

The general way to use sensitive variable is to store them as enviroment variable. You can save all your credentials variables into a .env file at project root:

API_ID=my_id
API_USERNAME=my_username

Remember to add it into .gitignore:

.env

Then you can use python-dotenv or something similar to import the variable:

# pip install python-dotenv
import os
from dotenv import load_dotenv

load_dotenv() 

Now you can access this variable in this way:

import os

api_id = os.getenv('API_ID')

Redundant code

Just create a utils.py, save them as functions.

Upvotes: 1

Related Questions