3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

msgpack を ajax で flask(werkzeug) な環境に送る

Last updated at Posted at 2013-02-07

js でクライアント側からも msgpack なデータを werkzeug な環境に
以下のようにして送りますた。

クライアント側

ninja.coffee
sendMsgPack:(event)=>
  event.preventDefault()
  arr = $('#hogehogeForm').serializeArray()
  data = msgpack.pack(arr)
  arrayBinary = new Uint8Array(data)
  xhr = new XMLHttpRequest()
  xhr.open('POST', '/api/url', true)
  xhr.onreadystatechange = ()->
  if xhr.readyState is 4 and xhr.status is 200
      console.log xhr.responseText
  else if xhr.readyState is 4 and xhr.status isnt 200
      console.log xhr, "hogehoge"
  xhr.setRequestHeader('Content-Type', 'application/x-msgpack; charset=x-user-defined')
  xhr.send(arrayBinary.buffer)

サーバー側

tasukete.py
import msgpack
from shimehari import Response, ApplicationController, request
import msgpack

class FooController(ApplicationController):
    def __init__(self, name):
        ApplicationController.__init__(self, name)

    def index(self, *args, **kwargs):
        return 'hidebu'

    def create(self, *args, **kwargs):
        #ほんとはちゃんとヘッダ見ようね
        print msgpack.unpackb(request.data)
        return Response('aaa')
$ ({'name': 'name', 'value': 'aaaaa'},)

msgpack.js には msgpack.upload というメソッドが用意されているようなのですが
メソッドが PUT になっていたり、リクエストヘッダの Content-Type が application/x-www-form-urlencoded になっていたりして、
僕にははかりしれない何かを感じたのでとりあえず生の XMLHttpRequest を使った次第です。
jQuery.ajax だと ArrayBuffer が送れないのでだめぽです。

Content-Type を x-www-form-urlencoded にすると、送信したデータが werkzeug の Request.data ではなく、 Request.form に入ってしまうのがなんとなくこれじゃない感があったのでなんとかかんとかした次第です。

ここまでやっといて実際は WebSocket で送ることにした次第であります。
まぁ WebSocket 使えない状況のほうが多い気がするのでもうちょい便利にブラッシュアップすれば使い物になるんではないでしょうか。

っていうか突っ込みどころは多いと思うので詳しい人がいたら教えて下さい。

3
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?