How to import modules in Google App Engine?

前端 未结 4 1197
礼貌的吻别
礼貌的吻别 2020-11-27 16:36

I have created a simple GAE app based on the default template. I want to add an external module like short_url. How do I do this? The directions that I have found so far are

4条回答
  •  被撕碎了的回忆
    2020-11-27 16:54

    Simply place the short_url.py file in your app's directory.

    Sample App Engine project:

    myapp/
        app.yaml
        index.yaml
        main.py
        short_url.py
        views.py
    

    And in views.py (or wherever), you can then import like so:

    import short_url
    

    For more complex projects, perhaps a better method is to create a directory especially for dependencies; say lib:

    myapp/
        lib/
            __init__.py
            short_url.py
        app.yaml
        index.yaml
        main.py
        views.py
    
    from lib import short_url
    

    Edit #2:
    Apologies, I should have mentioned this earlier. You need modify your path, thanks to Nick Johnson for the following fix.
    Ensure that this code is run before starting up your app; something like this:

    import os
    import sys
    
    def fix_path():
        # credit:  Nick Johnson of Google
        sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
    
    def main():
        url_map = [ ('/', views.IndexHandler),] # etc.
        app = webapp.WSGIApplication(url_map, debug=False)
        wsgiref.handlers.CGIHandler().run(app)
    
    if __name__ == "__main__":
        fix_path()
        main()
    

    Edit3:
    To get this code to run before all other imports, you can put the path managing code in a file of its own in your app's base directory (Python recognizes everything in that directory without any path modifications).
    And then you'd just ensure that this import

    import fix_path
    

    ...is listed before all other imports in your main.py file.
    Here's a link to full, working example in case my explanation wasn't clear.

提交回复
热议问题