LoginSignup
32
29

More than 5 years have passed since last update.

RubyistがPython+bottle+MySQLで簡単APIを作ってみた

Posted at

python-framework.png

背景

普段はRubyで開発をしているけど、ビッグデータの解析系の仕事が増えてきたので、pythonをいじる必要性が出てきて、まずは軽量フレームワークのbottleで簡単なAPI的な役割のシステムを作ってみようと思い立ちました。

雑感

めちゃくちゃ軽量で、手軽なので、pythonのいい部分だけ使ってあとはメインの言語でってことも可能。

作ったものの概要

①rubyのアプリケーションからAPIを叩く
②pythonで書いたアプリでMySQLにあるデータを取得
③pythonで計算
④rubyのアプリケーションに計算結果を返す

実装

1.virtualenvで仮想環境を作成

pip install virtualenv
virtualenv bottle_sample
cd bottle_sample
source bin/activate

2.bottleのインストール

pip install bottle

3./updateでデータを更新

score_calculator.py
# -*- coding: utf-8 -*-
from bottle import route, run
import networkx as nx

db_name = {DATABASE名}
host = {DATABASEのホスト}
username = {MySQLのusername}
passwd = {MySQLのpassword}

@route('/update')
def update
  g = nx.DiGraph()
  import mysql.connector
  connect = mysql.connector.connect(db=db_name, host=host, port=3306, user=username, passwd=passwd)

  cur=connect.cursor()
  cur.execute("select from_user_id,to_user_id from awesome_graph_data)                                                                                      
  rows = cur.fetchall()
  for row in rows:
    if row[0] is not None:
      g.add_node(row[0])
      g.add_node(row[1])
      g.add_edge(row[0],row[1])

    cur.close()
    connect.close()
  pr=nx.pagerank(g,alpha=0.85,personalization=None, max_iter=500)

  for id, score in pr.items():
    print id,score #今回は割愛するけど、ここでmysqlに保存すればいい
  return str(pr)

これで、有向グラフからpagerankを算出して、mysqlに保存できた。

4./score/{user_id}でscoreを取得

score_calculator.py
@route('/score/<user_id>')
def score
  import mysql.connector
  connect = mysql.connector.connect(db=db_name, host=host, port=3306, user=username, passwd=passwd)

  cur=connect.cursor()
  cur.execute("select score from scoda_data where user_id = {{user_id}}")                                                                                      
  score = cur.fetchall()
  return score

これで特定のuser_idのscoreが取得できるように。

まとめ

非常に簡単なアプリケーションなら、python+bottleで簡単に作れる。
他にも、viewファイルを作って、Webサプリケーションを作成することも簡単にできる。

rubyでは相性の良くなかった色んな計算を外出ししてしまうって手も面白いと思いました。

32
29
0

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
32
29