import function from a file in the same folder

后端 未结 4 1183
甜味超标
甜味超标 2020-12-29 01:36

I\'m building a Flask app with Python 3.5 following a tutorial, based on different import rules. By looking for similar questions, I managed to solve an ImportError based on

相关标签:
4条回答
  • 2020-12-29 02:12

    Another, shorter way would be:

    import .config as Config
    
    0 讨论(0)
  • 2020-12-29 02:27

    To import from the same folder you can do:

    from .config import function_or_class_in_config_file
    

    or to import the full config with the alias as you asked:

    from ..app import config as Config
    
    0 讨论(0)
  • 2020-12-29 02:29
    # imports all functions    
    import config
    # you invoke it this way
    config.my_function()
    

    or

    # import specific function
    from config import my_function
    # you invoke it this way
    my_function()
    

    If the app.py is invoked not from the same folder you can do this:

    # csfp - current_script_folder_path
    csfp = os.path.abspath(os.path.dirname(__file__))
    if csfp not in sys.path:
        sys.path.insert(0, csfp)
    # import it and invoke it by one of the ways described above
    
    0 讨论(0)
  • 2020-12-29 02:32

    Have you tried

    import app.config as Config
    

    It did the trick for me.

    0 讨论(0)
提交回复
热议问题