flask-peeweeのRestAPIを触ってみる 

先日flask-peeweeの管理サイトを触ってみましたが、RestAPIも同じような感じで追加できるみたいなので
やってみました

非常に簡単で、以下のコードを追加するだけです

from flaskext.rest import RestAPI

api = RestAPI(app)
api.register(Post)
api.setup()

/api//でアクセスできます
http://localhost:5000/api/post/

登録されているモデルのデータがjsonが返されます

{
  "meta": {
    "model": "post",
    "next": "",
    "page": 1,
    "previous": ""
  },
  "objects": [
    {
      "entry": "\u3042\u3044\u3046\u3048\u304a",
      "created": "2011-11-10 22:01:28",
      "id": 1,
      "title": "test"
    }
  ]
}

データの登録はPOSTで行う必要があります
requestsを使ってやってみます

>>> import requests
>>> requests.post('http://localhost:5000/api/post/')
<Response [401]>

401が返されました。

POSTには認証処理を追加する必要があるようです。

from flaskext.rest import RestAPI, UserAuthentication

user_auth = UserAuthentication(auth)
api = RestAPI(app, default_auth=user_auth)

user/passを渡して、データ登録の処理ができました

>>> res = requests.post('http://localhost:5000/api/post/', data={"data": '{"title": "test", "entry": "test_entry"}'}, auth=("admin","admin"))
>>> res.content
'{\n  "entry": "test_entry",\n  "created": "2011-11-11 22:50:04",\n  "id": 6,\n  "title": "test"\n}'

削除してみます

>>>res = requests.delete('http://localhost:5000/api/post/6/', auth=("admin","admin"))
>>>res.content
'{\n  "deleted": 1\n}'

削除もできましたね

requestsも便利です

全体だと、先日のAdminの分とあわせて以下のような感じです

import datetime
from flask import Flask, render_template
from flaskext.auth import Auth
from flaskext.admin import Admin, ModelAdmin
from flaskext.db import Database
from flaskext.rest import RestAPI, UserAuthentication
from peewee import TextField, DateTimeField, CharField

# configure our database
DATABASE = {
    'name': 'flask_peewee_sample.db',
    'engine': 'peewee.SqliteDatabase',
}
DEBUG = True
SECRET_KEY = '*****************************'

app = Flask(__name__)
app.config.from_object(__name__)

db = Database(app)

# model
class Post(db.Model):
    title = CharField()
    entry = TextField()
    created = DateTimeField(default=datetime.datetime.now)

class PostAdmin(ModelAdmin):
    columns = ('title', 'entry', 'created',)

# for admin site
auth = Auth(app, db)
admin = Admin(app, auth)
admin.register(Post, PostAdmin)
auth.register_admin(admin)
admin.setup()

# for restapi
user_auth = UserAuthentication(auth)
api = RestAPI(app, default_auth=user_auth)
api.register(Post)
api.setup()

if __name__ == '__main__':
    auth.User.create_table(fail_silently=True)
    Post.create_table(fail_silently=True)

    app.run()

参考

flask-peewee

flask と peeweeとを統合するレイヤーを提供する
http://charlesleifer.com/docs/flask-peewee/

requests

webアクセスモジュール
http://docs.python-requests.org/en/latest/