APIサーバー Falcon post,headerの値の取得方法

APIサーバーのFalconをインストールし、getパラメーターの取得を行ってみました。
Python + Falconで高速APIサーバーを作成する

その他のパラメーターの取得方法を調べてみます。
このドキュメントを参考にしました。
https://github.com/falconry/falcon/blob/master/README.rst


POST



POSTパラメーターの取得は以下のようになりました。
json形式のデータをpostし、解析しています。


  1. # -*- coding:utf-8 -*-
  2. import json
  3. import falcon
  4. class HelloResource(object):
  5.     
  6.     # postされた時の動作
  7.     def on_post(self, req, res):
  8.         
  9.         # postパラメーターを取得
  10.         body = req.stream.read()
  11.         data = json.loads(body)
  12.         
  13.         # パラメーターの取得
  14.         name = data['name']
  15.         
  16.         msg = {
  17.             "message": "Hello, " + name
  18.         }
  19.         res.body = json.dumps(msg)
  20. app = falcon.API()
  21. app.add_route("/", HelloResource())
  22. if __name__ == "__main__":
  23.     from wsgiref import simple_server
  24.     httpd = simple_server.make_server("0.0.0.0", 8000, app)
  25.     httpd.serve_forever()





テストプログラム


  1. # -*- coding:utf-8 -*-
  2. import json
  3. import urllib2
  4. values = {'name' : 'symfo'}
  5. data = json.dumps(values)
  6. response = urllib2.urlopen('http://192.168.1.102:8000', data)
  7. body = response.read()
  8. response.close()
  9. data = json.loads(body)
  10. print(data['message'])




実行結果


$ python api_test.py
Hello, symfo







headerの取得



get_headerでヘッダーの情報が取得できます。


  1. # -*- coding:utf-8 -*-
  2. import json
  3. import falcon
  4. class HelloResource(object):
  5.     
  6.     # getされた時の動作
  7.     def on_get(self, req, res):
  8.         
  9.         # headerを取得
  10.         name = req.get_header('name')
  11.         
  12.         msg = {
  13.             "message": "Hello, " + name
  14.         }
  15.         res.body = json.dumps(msg)
  16. app = falcon.API()
  17. app.add_route("/", HelloResource())
  18. if __name__ == "__main__":
  19.     from wsgiref import simple_server
  20.     httpd = simple_server.make_server("0.0.0.0", 8000, app)
  21.     httpd.serve_forever()





テストプログラム


  1. # -*- coding:utf-8 -*-
  2. import json
  3. import urllib2
  4. headers = { 'name' : 'symfo' }
  5. req = urllib2.Request(url='http://192.168.1.102:8000', headers=headers)
  6. response = urllib2.urlopen(req)
  7. body = response.read()
  8. response.close()
  9. data = json.loads(body)
  10. print(data['message'])







画像ファイルのPOST



POSTのヘッダーにファイル名。
ボディに画像ファイルを設定。

サーバー側で保存してみます。


  1. # -*- coding:utf-8 -*-
  2. import json
  3. import falcon
  4. class HelloResource(object):
  5.     
  6.     # postされた時の動作
  7.     def on_post(self, req, res):
  8.         
  9.         # headerからファイル名を取得
  10.         filename = req.get_header('File-Name')
  11.         
  12.         # bodyから画像ファイルのバイナリ取得
  13.         body = req.stream.read()
  14.         
  15.         # ファイルを保存
  16.         with open(filename, 'wb') as f:
  17.             f.write(body)
  18.         
  19.         res.body = json.dumps({'result':'ok'})
  20. app = falcon.API()
  21. app.add_route("/", HelloResource())
  22. if __name__ == "__main__":
  23.     from wsgiref import simple_server
  24.     httpd = simple_server.make_server("0.0.0.0", 8000, app)
  25.     httpd.serve_forever()




テスト用のプログラム


  1. # -*- coding:utf-8 -*-
  2. import json
  3. import urllib2
  4. # ファイル名
  5. headers = { 'File-Name' : 'sample.jpg' }
  6. # ファイル本体を取得
  7. with open('cc2.jpg', 'rb') as f:
  8.     image = f.read()
  9. req = urllib2.Request(url='http://192.168.1.102:8000', data=image, headers=headers)
  10. response = urllib2.urlopen(req)
  11. # 戻り値を解析
  12. body = response.read()
  13. response.close()
  14. data = json.loads(body)
  15. print(data['result'])




だいぶ使い方がわかってきました。





on_get,on_postに渡されるリクエスト



渡されるリクエストオブジェクトには、こんなメソッドがあるようです。
メモとして残しておきます。


accept
access_route
app
auth
client_accepts
client_accepts_json
client_accepts_msgpack
client_accepts_xml
client_prefers
content_length
content_type
context
context_type
cookies
date
env
expect
get_header
get_header_as_datetime
get_param
get_param_as_bool
get_param_as_date
get_param_as_int
get_param_as_list
headers
host
if_match
if_modified_since
if_none_match
if_range
if_unmodified_since
log_error
method
options
params
path
protocol
query_string
range
range_unit
relative_uri
remote_addr
stream
subdomain
uri
url
user_agent




続きです。
Falcon URLによる分岐と値の取得
関連記事

コメント

プロフィール

Author:symfo
blog形式だと探しにくいので、まとめサイト作成中です。
https://symfo.web.fc2.com/

PR

検索フォーム

月別アーカイブ