我是 python 烧瓶的新手
在单个文件中使用 MongoDB 试验一些端点,如下所示
from flask import Flask, request
from flask.ext.mongoalchemy import MongoAlchemy
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['MONGOALCHEMY_DATABASE'] = 'library'
db = MongoAlchemy(app)
class Author(db.Document):
name = db.StringField()
class Book(db.Document):
title = db.StringField()
author = db.DocumentField(Author)
year = db.IntField();
@app.route('/author/new')
def new_author():
"""Creates a new author by a giving name (via GET parameter)
e.g.: GET /author/new?name=Francisco creates a author named Francisco
"""
author = Author(name=request.args.get('name', ''))
author.save()
return 'Saved :)'
@app.route('/authors/')
def list_authors():
"""List all authors.
e.g.: GET /authors"""
authors = Author.query.all()
content = '<p>Authors:</p>'
for author in authors:
content += '<p>%s</p>' % author.name
return content
if __name__ == '__main__':
app.run()
上面的代码包含两个端点发布并获取工作正常的数据
知道寻找一种将代码分离到不同文件中的方法,例如
数据库连接相关代码应该在不同的文件中
from flask import Flask, request
from flask.ext.mongoalchemy import MongoAlchemy
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['MONGOALCHEMY_DATABASE'] = 'library'
db = MongoAlchemy(app)
我应该能够在定义架构的不同文件中获取数据库引用并使用它
class Author(db.Document):
name = db.StringField()
class Book(db.Document):
title = db.StringField()
author = db.DocumentField(Author)
year = db.IntField();
和路线将是不同的文件
@app.route('/author/new')
def new_author():
"""Creates a new author by a giving name (via GET parameter)
e.g.: GET /author/new?name=Francisco creates a author named Francisco
"""
author = Author(name=request.args.get('name', ''))
author.save()
return 'Saved :)'
@app.route('/authors/')
def list_authors():
"""List all authors.
e.g.: GET /authors"""
authors = Author.query.all()
content = '<p>Authors:</p>'
for author in authors:
content += '<p>%s</p>' % author.name
return content
在端点文件中,我应该获取数据库模式的参考,请帮助我获取此结构
指点我一些可以帮助我做的可以理解的示例或视频,我是 python 和烧瓶的新手,请指点一些示例并帮助了解更多谢谢