Python之web开发首页投稿(暂停使用,暂停投稿)Python 运维

Flask-MongoEngine官方文档·中文版·2016.4

2016-04-12  本文已影响6081人  森与渊

声明:本文档保证语义完备,使用Markdown排版,计划基于git管理文档,随时同步更新

Flask-MongoEngine

一个用来集成MongoEngine的Flask扩展,更多MongoEngine详细信息请参看MongoEngine文档。

它处理应用的连接管理。你也可以用WTForms作为模型的格式。

安装Flask-MongoEngine

使用pip安装:

pip install flask-mongoengine

配置

基本步骤很简单,仅需获取扩展:

from flask import Flask
from flask.ext.mongoengine import MongoEngine

app = Flask(__name__)
app.config.from_pyfile('the-config.cfg')
db = MongoEngine(app)

或者,若你想在应用初始化之前配置数据库,下方是一个应用工厂的列子:

from flask import Flask
from flask.ext.mongoengine import MongoEngine
db = MongoEngine()
...
app = Flask(__name__)
app.config.from_pyfile('the-config.cfg')
db.init_app(app)

默认情况下,Flask-MongoEngine假设mongod实例运行在本地主机27017端口上,并且你将连接名为test的数据库。

如果MongoDB运行在别处,你需要在app.config的'MONGODB_SETTINGS'字典中配置主机端口

app.config['MONGODB_SETTINGS'] = {
  'db': 'project1',
  'host': '192.168.1.35', 
  'port': 12345
}

如果数据库需要身份验证,app.config['MONGODB_SETTINGS']字典需要提供usernamepassword参数:

app.config['MONGODB_SETTINGS'] = {
  'db': 'project1', 
  'username':'webapp', 
  'password':'pwd123'
}

也支持Uri风格的连接,仅需在app.config['MONGODB_SETTINGS']字典中将host值设为uri。注意,自uri获取的数据库名称优先级高于本地设置

app.config['MONGODB_SETTINGS'] = {
  'db': 'project1', 
  'host': 'mongodb://localhost/database_name'
}

连接配置也可以通过带有MONGODB_前缀的字典单独设置:

app.config['MONGODB_DB'] = 'project1'
app.config['MONGODB_HOST'] = '192.168.1.35'
app.config['MONGODB_PORT'] = 12345
app.config['MONGODB_USERNAME'] = 'webapp'
app.config['MONGODB_PASSWORD'] = 'pwd123'

定制查询集

flask-mongoengine位MongoEngine的默认查询集附加了下列方法:

例子:

# 404 if object doesn't exist
def view_todo(todo_id):
    todo = Todo.objects.get_or_404(_id=todo_id)
..

# Paginate through todo
def view_todos(page=1):
    paginated_todos = Todo.objects.paginate(page=page, per_page=10)

# Paginate through tags of todo
def view_todo_tags(todo_id, page=1):
    todo = Todo.objects.get_or_404(_id=todo_id)
    paginated_tags = todo.paginate_field('tags', page, per_page=10)

分页对象包含以下属性: iter_pages, next, prev, has_next, has_prev, next_num, prev_num.

在模板中:

{% macro render_pagination(pagination, endpoint) %}
  <div class=pagination>
  {%- for page in pagination.iter_pages() %}
    {% if page %}
      {% if page != pagination.page %}
        <a href="{{ url_for(endpoint, page=page) }}">{{ page }}</a>
      {% else %}
        <strong>{{ page }}</strong>
      {% endif %}
    {% else %}
      <span class=ellipsis>…</span>
    {% endif %}
  {%- endfor %}
  </div>
{% endmacro %}

MongoEngine 和 WTForms

你可以这样使用MongoEngine 和 WTForms:

from flask.ext.mongoengine.wtf import model_form

class User(db.Document): 
  email = db.StringField(required=True) 
  first_name = db.StringField(max_length=50) 
  last_name = db.StringField(max_length=50)

class Content(db.EmbeddedDocument): 
  text = db.StringField() 
  lang = db.StringField(max_length=3)

class Post(db.Document): 
  title = db.StringField(max_length=120, required=True, validators=[validators.InputRequired(message=u'Missing title.'),]) 
  author = db.ReferenceField(User) 
  tags = db.ListField(db.StringField(max_length=30)) 
  content = db.EmbeddedDocumentField(Content)

PostForm = model_form(Post)

def add_post(request): 
  form = PostForm(request.POST) 
  if request.method == 'POST' and form.validate(): 
    # do something 
    redirect('done') 
  return render_template('add_post.html', form=form)

支持字段

目前不支持字段类型:

Session Interface

To use MongoEngine as your session store simple configure the session interface:

from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface

app = Flask(__name__)
db = MongoEngine(app)
app.session_interface = MongoEngineSessionInterface(db)

调试工具栏面板

调试工具栏面板.png

如果你使用Flask-DebugToolbar,你可以添加

app.config['DEBUG_TB_PANELS'] = ['flask.ext.mongoengine.panels.MongoDebugPanel']

,然后它将自动跟踪查询:

from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension

app = Flask(__name__)
app.config['DEBUG_TB_PANELS'] = ['flask.ext.mongoengine.panels.MongoDebugPanel']
db = MongoEngine(app)
toolbar = DebugToolbarExtension(app)

升级

ListFieldPagination参数的顺序已经改变的更为符合逻辑:

# Old order
ListFieldPagination(self, queryset, field_name, doc_id, page, per_page, total)
# New order
ListFieldPagination(self, queryset, doc_id, field_name, page, per_page, total)
上一篇下一篇

猜你喜欢

热点阅读