Essentially, I want to make my code more modular and shareable: you can see how the following files made up a much larger one initially. It's not working and I suspect it's because I'm trying to do things in Python that I'm not supposed to:
app_config.py:
app_name = "quick scraper"
mysql_db = ... # intended "global" variable that connects to database
main.py:
from app_config import * # Getting shared variables
import app_library # See code app_library.py below
...
logger = logging.getLogger(app_name) # logger object to be shared later
...
app_library.dlAndSaveWebpage(url) # Module has key helper functions
...
app_library.py:
import app_models_orm as app_models
def dlAndSaveWebpage(url)
# download and process url
...
app_models.Webpage.create(url=url, body=body)
app_models_orm.py:
class MySQLModel(Model):
class Meta:
database = mysql_db
class Webpage(MySQLModel):
id = ...
...
Class
MySQLModelofapp_models_orm.pyfails because variablemysql_dbdoes not exist in the file. I could do animport app_config, but I want to haveapp_models_orm.pybe used by multiple scripts within the same directory. If I have to do an import of a file custom to a script, then I'd have to make copies of the models file, which just seems bizarre and wrong.Similarly, I want to use
app_library.pyby multiple scripts in the same directory. It seems to make sense to callapp_libraryfrommain.py, but ifapp_libraryneeds to reference variables directly fromapp_config.py, I'd have to also make copies ofapp_library.py.main.pycontains aloggerobject that, when all of this code was put together in one file, all the various methods could access/use. How can (or should?)app_library.pyfunctions access this instance of the logger class?
Feel free to "teach me how to catch fish" in this instance too: I saw many posts about using a global import file, but that doesn't help the intention to share the latter two files without adding in custom imports, nor does it help with the models file which, when imported, hits an error because the class is seeking a variable that isn't in the file. There's probably a right way to do all this.