Split views.py in several files

前端 未结 10 789
有刺的猬
有刺的猬 2020-11-27 09:37

My views.py has become too big and it\'s hard to find the right view.

How do I split it in several files and then import it? Does it involve any speed l

相关标签:
10条回答
  • 2020-11-27 10:11

    Suppose if you have a file named: password_generator.py then inside views.py add: from password_generator import *

    Then you can call that module's function from views.py.

    0 讨论(0)
  • 2020-11-27 10:14

    I've been playing with putting this in my init.py:

    import os
    
    currPath = os.path.realpath(os.path.dirname(__file__))
    
    dirFiles = []
    for root, dirs, files in os.walk(currPath):
        for name in files:
            if name.endswith('.py') and not name.startswith('_'): 
                dirFiles.append(name.strip('.py'))
    
    for f in dirFiles:
        exec("from %s import %s" % (f,f))
    

    I'm still new to python, so I'm still looking at what effect it has on speed/security/ease of use.

    0 讨论(0)
  • 2020-11-27 10:16

    I split almost all views in my apps into a views folder (with an init.py of course). I do not, however, import all of the subviews in the init.py like some of the answers have suggested. It seems to work just fine.

    0 讨论(0)
  • 2020-11-27 10:18

    Vincent Demeester's answer is superb! but for me addicted's answer worked like a charm. I faced difficulties in migrating database. The error indicates the line where the first model is imported and says could not recognize my app module. Searched a lot but could not find a solution but later on I imported the model like this:

    from ..models import ModelName
    

    It worked!!

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