【问题标题】:Flask with MongoDB using MongoKit to MongoLabsFlask with MongoDB 使用 MongoKit 到 MongoLabs
【发布时间】:2014-12-24 08:59:01
【问题描述】:

我是初学者,我在本地开发了一个简单的应用程序,它使用 mongodb 和 mongoKit,如下所示:

app = Flask(__name__)
app.config.from_object(__name__)

customerDB = MongoKit(app)
customerDB.register([CustomerModel])

然后在视图中我只使用 CustomerDB

我已将所有内容都放在 heroku 云上,但我的数据库连接不起作用。

我得到了我需要连接的链接:

heroku config | grep MONGOLAB_URI 

但我不知道如何拉这个。我看了下面的帖子,但我更困惑 How can I use the mongolab add-on to Heroku from python?

任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: heroku flask mlab mongokit


    【解决方案1】:

    根据the documentation,Flask-MongoKit 支持一组配置设置。

    MONGODB_DATABASE
    MONGODB_HOST
    MONGODB_PORT
    MONGODB_USERNAME
    MONGODB_PASSWORD
    

    需要解析MONGOLAB_URI 环境设置以获取其中的每一个。我们可以将this answer 用于您链接到的问题作为起点。

    import os
    from urlparse import urlsplit
    
    from flask import Flask
    from flask_mongokit import MongoKit
    
    app = Flask(__name__)
    
    # Get the URL from the Heroku setting.
    url = os.environ.get('MONGOLAB_URI', 'mongodb://localhost:27017/some_db_name')
    # Parse it.
    parsed - urlsplit(url)
    
    # The database name comes from the path, minus the leading /.
    app.config['MONGODB_DATABASE'] = parsed.path[1:]
    
    if '@' in parsed.netloc:
        # If there are authentication details, split the network locality.
        auth, server = parsed.netloc.split('@')
        # The username and password are in the first part, separated by a :.
        app.config['MONGODB_USERNAME'], app.config['MONGODB_PASSWORD'] = auth.split(':')
    else:
        # Otherwise the whole thing is the host and port.
        server = parsed.netloc
    
    # Split whatever version of netloc we have left to get the host and port.
    app.config['MONGODB_HOST'], app.config['MONGODB_PORT'] = server.split(':')
    
    customerDB = MongoKit(app)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-26
      • 2013-05-30
      • 2015-05-25
      • 2013-02-24
      • 2023-03-09
      • 2017-03-08
      • 2012-05-12
      • 1970-01-01
      相关资源
      最近更新 更多