0

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:

  • A function verifying a Shopify webhook
  • Generating the "Credentials" portion of a post XML to a different API (Can make into a function)
  • Some credentials variables for this API: ID, username, password, pin, referenceNumber, etc.
  • Google Sheets API credential variables

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?

1
  • you will probably get circular imports if you put them in main.py ... but you could put the shared code in some util.py or something and import it from there Commented Jul 8, 2018 at 4:32

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! What about importing modules such as gspread, lxml, json, os, etc.? Would I be able to also put them all in utils.py?
Just import them in the place you need.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.