使用MongoKit到MongoLabs的MongoDB烧瓶

时间:2014-10-28 19:39:36

标签: heroku flask mlab mongokit

我是初学者,我有一个我在本地开发的简单应用程序,它使用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?

任何帮助将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分: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)
相关问题