sudo apt-get install apache2
service apache2 status
VM上で http://localhost に接続し、Apacheのテストページが表示されていることを確認してください。
PostgreSQLによるデータ分析で使ったデータを今回も使います。
# ホームディレクトリへ cd ~ # 今回用のディレクトリを作成 mkdir swa # Pythonファイルを作成 touch swa.py # PostgreSQLに接続するモジュールをインストールします sudo apt-get install python-psycopg2 # Flaskを使うためのモジュールをインストールします sudo pip install setuptools # Flask(Python向けウェブフレームワーク)をインストールします sudo pip install Flask # PostgreSQLにPythonからの要求を受け取る設定をします。 vi /etc/postgresql/9.5/main/pg_hba.conf # 赤枠内の設定を書き換えてください。
# PostgreSQLサーバーを再起動します sudo service postgresql stop sudo service postgresql start
環境設定は以上です。
複数の技術を組み合わせて簡単なウェブアプリケーションのサンプルを作る演習をします。
具体的には、PythonからPostgreSQLデータベースに問い合わせし、その内容をApacheサーバーを経由してBootstrapウェブページ上に表示します。
表示されたウェブページではjapan_cities内の検索ができるように、検索機能を追加します。
それぞれの関係性を図に表すと以下のようになります。
下記のSQLコードを用いて、データベースのデータをJSON形式で取得できます。
select jsonb_pretty(to_jsonb(array_agg(json_build_object( 'prefecture', prefecture, 'city', city, 'ward', ward, 'population', population, 'city_ward', city_ward)))) from japan_cities ;
#!/usr/bin/python # -*- coding: utf-8 -*- """ Avinton python endpoint swa.py """ import sys import json import psycopg2 import psycopg2.extensions psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY) from flask import Flask # Import class Flask from module flask from flask_cors import CORS, cross_origin #Import flask-cors to accept access to the data app = Flask(__name__) # Construct an instance of Flask class CORS(app) # apply CORS @app.route('/') # Register index() as route handler for root URL '/' def index(): """Route handler (or View Function) for root URL '/'""" return 'Hello, you have reached the default route for the python endpoint' @app.route('/cities.json') def cities(): con = None js_string = '' try: con = psycopg2.connect(database='avinton', user='postgres') cur = con.cursor() cur.execute("""<上の SQL in JSON のSQLコード>""") js_string = str(cur.fetchone()[0]) print js_string except psycopg2.DatabaseError, e: print 'DB Error %s' % e sys.exit(1) finally: if con: con.close() return js_string @app.route('/test') def test(): return 'test' if __name__ == '__main__': # Script executed directly? app.run() # Launch built-in web server and run this Flask webapp
(http://localhostで表示されるのはこのページです。)
<DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Data Table in Bootstrap</title> ~~~import Bootstrap source~~~ (css,javascript) </head> <body> ~~~create table with the data~~~ </body> </html>
index.html としてApache2のディレクトリに保存します。
最終的には以下のように、データベースのデータをフロントエンドで表示できます。