私は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()
投稿して正常に動作しているデータを取得する2つのエンドポイントを含む上記のコード
コードを別のファイルに分割する方法を探していることを知っている
データベース接続関連のコードは別のファイルにある必要があります
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)
スキーマが定義されている別のファイルでDB参照を取得して使用できるはずです
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とフラスコが初めてです。いくつかのサンプルを指摘して、より多くのことを学ぶのを手伝ってください