Reskink Flask – FlaskとRethinkDBを使用したシンプルなTodoリスト
ところで:私たちは常にリクエストを歓迎します。 あなたが私たちに何か書いてもらいたい、または作りたいものがあれば、私たちにメールを送ってください。
今日は、simpleのtodoリストを作成します。これは、自分のニーズに合わせて変更できます。 始める前に、thisの記事を読むことを強くお勧めします。この記事では、RethinkDBが他のNoSQLデータベースとどのように異なるかについて詳しく説明しています。
RethinkDBをセットアップする
RethinkDBをインストールする
hereをナビゲートし、システムに適切なパッケージをダウンロードします。 Homebrew-$ brew install rethinkdb
-を使用しましたが、ビルドをダウンロードしてインストールするのに約20分かかりました。
==> Installing rethinkdb
==> Downloading http://download.rethinkdb.com/dist/rethinkdb- 1.11.2.tgz
######################################################################## 100.0%
==> ./configure --prefix=/usr/local/Cellar/rethinkdb/1.11.2 -- fetch v8 --fetch protobuf
==> make
==> make install-osx
==> Caveats
To have launchd start rethinkdb at login:
ln -sfv /usr/local/opt/rethinkdb/*.plist ~/Library/LaunchAgents
Then to load rethinkdb now:
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.rethinkdb.plist
==> Summary
🍺 /usr/local/Cellar/rethinkdb/1.11.2: 174 files, 29M, built in 19.7 minutes
Pythonドライバーをグローバルにインストールする
$ sudo pip install rethinkdb
Note: Rethinkをグローバルに(virtualenvの外で)インストールしました。おそらく、同じバージョンをいくつかのプロジェクトで、いくつかの異なる言語で使用するからです。 このチュートリアルの後半で、virtualenv内にインストールします。
セットアップをテストする
まず、次のコマンドでサーバーを起動しましょう。
$ rethinkdb
すべてが正しくインストールされると、次のようなものが表示されます。
info: Creating directory /Users/michaelherman/rethinkdb_data
info: Creating a default database for your convenience. (This is because you ran 'rethinkdb' without 'create', 'serve', or '--join', and the directory '/Users/michaelherman/rethinkdb_data' did not already exist.)
info: Running rethinkdb 1.11.2 (CLANG 4.2 (clang-425.0.28))...
info: Running on Darwin 12.4.0 x86_64
info: Loading data from directory /Users/michaelherman/rethinkdb_data
info: Listening for intracluster connections on port 29015
info: Listening for client driver connections on port 28015
info: Listening for administrative HTTP connections on port 8080
info: Listening on addresses: 127.0.0.1, ::1
info: To fully expose RethinkDB on the network, bind to all addresses
info: by running rethinkdb with the `--bind all` command line option.
info: Server ready
次に接続をテストします。 ターミナルで新しいウィンドウを開き、次のコマンドを入力します。
>>>
$ python
>>> import rethinkdb
>>> rethinkdb.connect('localhost', 28015).repl()
君は見るべきだ:
>>>
Pythonシェルを終了しますが、他のターミナルウィンドウでRethinkDBサーバーを実行したままにします。
基本的なFlaskプロジェクトをセットアップする
プロジェクトを保存するディレクトリを作成します
$ mkdir flask-rethink
$ cd flask-rethink
セットアップとactivate a virtualenv
$ virtualenv --no-site-packages env
$ source env/bin/activate
FlaskとFlask-WTFをインストールする
$ pip install flask
$ pip install flask-wtf
Pip要件ファイルを作成する
$ pip freeze > requirements.txt
Flaskボイラープレートをダウンロードする
thisリポジトリのテンプレートディレクトリにあります。 プロジェクト構造は次のようになります。
├── app │ ├── __init__.py │ ├── forms.py │ ├── models.py │ ├── templates │ │ ├── base.html │ │ └── index.html │ └── views.py ├── readme.md ├── requirements.txt └── run.py
アプリを実行する
$ python run.py
http://localhost:5000/に移動すると、次のように表示されます。
最初にデータベースをセットアップする必要があるため、まだ何も送信しないでください。 RethinkDBを始めましょう。
RethinkDB構成
RethinkDBをインストールする
$ pip install rethinkdb
「views.py」に次のコードを追加します
# rethink imports
import rethinkdb as r
from rethinkdb.errors import RqlRuntimeError
# rethink config
RDB_HOST = 'localhost'
RDB_PORT = 28015
TODO_DB = 'todo'
# db setup; only run once
def dbSetup():
connection = r.connect(host=RDB_HOST, port=RDB_PORT)
try:
r.db_create(TODO_DB).run(connection)
r.db(TODO_DB).table_create('todos').run(connection)
print 'Database setup completed'
except RqlRuntimeError:
print 'Database already exists.'
finally:
connection.close()
dbSetup()
# open connection before each request
@app.before_request
def before_request():
try:
g.rdb_conn = r.connect(host=RDB_HOST, port=RDB_PORT, db=TODO_DB)
except RqlDriverError:
abort(503, "Database connection could be established.")
# close the connection after each request
@app.teardown_request
def teardown_request(exception):
try:
g.rdb_conn.close()
except AttributeError:
pass
各機能の機能の簡単な説明については、コメントを確認してください。
サーバーを再起動します
端末に次のアラートが表示されるはずです。
Database setup completed
このエラー
rethinkdb.errors.RqlDriverError: Could not connect to localhost:28015.
が表示された場合は、RethinkDBサーバーが実行されていません。 新しいターミナルウィンドウを開き、$ rethinkdb
を実行します。
そこで、「todo」という名前のテーブルを持つ「todo」という名前の新しいデータベースを作成しました。
これはRethinkDB Adminで確認できます。 http://localhost:8080/に移動します。 管理者がロードする必要があります。 [テーブル]をクリックすると、作成したデータベースとテーブルが表示されます。
Todoを表示する
データベースのセットアップで、todoを表示するコードを追加しましょう。 「views.py」のindex()
関数を更新します。
@app.route("/")
def index():
form = TaskForm()
selection = list(r.table('todos').run(g.rdb_conn))
return render_template('index.html', form=form, tasks=selection)
ここでは、「todos」テーブルを選択し、JSON形式のすべてのデータを取得して、テーブル全体をテンプレートに渡します。
データを手動で追加する
Todoを表示する前に、最初にTodoを追加する必要があります。 シェルを調べて、手動で追加してみましょう。
>>>
$ python
>>> import rethinkdb
>>> conn = rethinkdb.connect(db='todo')
>>> rethinkdb.table('todos').insert({'name':'sail to the moon'}).run(conn)
{u'errors': 0, u'deleted': 0, u'generated_keys': [u'c5562325-c5a1-4a78-8232-c0de4f500aff'], u'unchanged': 0, u'skipped': 0, u'replaced': 0, u'inserted': 1}
>>> rethinkdb.table('todos').insert({'name':'jump in the ocean'}).run(conn)
{u'errors': 0, u'deleted': 0, u'generated_keys': [u'0a3e3658-4513-48cb-bc68-5af247269ee4'], u'unchanged': 0, u'skipped': 0, u'replaced': 0, u'inserted': 1}
>>> rethinkdb.table('todos').insert({'name':'think of another todo'}).run(conn)
{u'errors': 0, u'deleted': 0, u'generated_keys': [u'b154a036-3c3b-47f4-89ec-cb9f4eff5f5a'], u'unchanged': 0, u'skipped': 0, u'replaced': 0, u'inserted': 1}
>>>
そこで、データベースに接続し、データベース内のテーブルに3つの新しいオブジェクトを入力しました。 Check the API docs for more information.
サーバーを起動します。 次の3つのタスクが表示されます。
フォームを完成させる
index()
関数を再度更新して、フォームからデータをプルし、データベースに追加します。
@app.route('/', methods = ['GET', 'POST'])
def index():
form = TaskForm()
if form.validate_on_submit():
r.table('todos').insert({"name":form.label.data}).run(g.rdb_conn)
return redirect(url_for('index'))
selection = list(r.table('todos').run(g.rdb_conn))
return render_template('index.html', form = form, tasks = selection)
これをテストしてください。 いくつかの仕事を追加します。 夢中になる。
結論と課題
現在のアプリは機能していますが、できることは他にもたくさんあります。 このアプリを次のレベルに進めてください。
ここにいくつかのアイデアがあります:
-
ユーザーログインを追加します。
-
より堅牢なフォームを作成します。各フォームに期日を追加し、DOMにレンダリングする前にその日付でToDoを並べ替えることができます。
-
機能とunit testsを追加します。
-
各タスクのサブタスクを作成する機能を追加します。
-
APIリファレンスdocsを読みます。 さまざまな方法で遊んでください。
-
アプリをモジュール化します。
-
コードをリファクタリングします。 RethinkDBに新しいコードを見せてください。
他に何を見たいですか? パート2をご覧になりたいですか? MongoDBと比較してRethinkDBが好きですか? 以下にあなたの考えを共有してください。
repoからすべてのコードを取得できます。 乾杯!