\

この記事では、PythonとFlaskを使用して簡易的なチャットアプリケーションを開発する方法について説明します。WebSocketを使用してリアルタイムの通信を実現し、ユーザー間でメッセージをやり取りできるようにします。

必要なモジュールのインストール

まずは、アプリケーション開発に必要なモジュールをインストールします。requirements.txtに以下の内容を記述します。

Flask==1.0.2
Flask-Sockets==0.2.1
gunicorn==19.9.0
gevent==1.4.0
gevent-websocket==0.10.1

そして、以下のコマンドでモジュールをインストールします。

$ pip install -r requirements.txt

Flask側の実装(サーバー側の実装)

次に、サーバー側であるFlaskの実装を行います。ファイル名はapp.pyとします。以下に必要なモジュールをインポートする部分のコードを示します。

# -*- coding: utf-8 -*-
import json
import datetime
import time
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler
from flask import Flask, request, render_template

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

URLエンドポイントは二つ用意します。WEBの画面部分であるhtmlのテンプレートを「/」から配信、「/pipe」でWebSocket部分を受け付けます。

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/pipe')
def pipe():
    if request.environ.get('wsgi.websocket'):
        ws = request.environ['wsgi.websocket']
        while True:
            time.sleep(1)
            message = ws.receive()
            if message is None:
                break
            datetime_now = datetime.datetime.now()
            data = {
                'time': str(datetime_now),
                'message': message
            }
            ws.send(json.dumps(data))
            print(message)
            print(data)
    return

単体でも動かせるように簡易的なWSGIミドルウェアを通せるようにします。これにより「python app.py」でも起動できるようになります。

if __name__ == '__main__':
    app.debug = True
    host = 'localhost'
    port = 8080
    host_port = (host, port)
    server = WSGIServer(host_port, app, handler_class=WebSocketHandler)
    server.serve_forever()

以上で、PythonとFlaskを使用した簡易的なチャットアプリケーションの開発についての基本的な説明を終わります。この情報が役立つことを願っています。.

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です