Drkcore

02 10 2013 Python Flask Tweet

FlaskでリアルタイムWebアプリが作れるようになって素晴らしい

Flask-Socketsを入れればWebSocketが使えるようになって素敵です☆

早速echoサーバーを作ってみた。

Flask-Sockets

テスト環境構築

mkvirtualenv flask_sockets
mkdir echo_server
cd echo_server/
pip install Flask
pip install Flask-Sockets
pip install gunicorn

コードはこんな感じ

.
├── app.py
└── templates
    └── hello.html

app.py

from flask import Flask, render_template
from flask_sockets import Sockets

app = Flask(__name__)
sockets = Sockets(app)

@sockets.route('/echo')
def echo_socket(ws):
    while True:
        message = ws.receive()
        ws.send(message)

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

if __name__ == '__main__':
    app.run()

templates/hello.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <h1>Flaskでechoサーバー☆</h1>
  <input type="text" id="msg" value="_(:3 」∠)_"/>
  <button id="sendBtn">send</button>
  <ul id="rcv"></ul>
</body>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
  $(function(){
  var host = "ws://localhost:8000/echo";
  var socket = new WebSocket(host);

  socket.onmessage = function(message){
    $("#rcv").append("<li>" + message.data + "</li>")
    console.log(message.data);
  }

  $("#sendBtn").on("click",function(){
    message = $("#msg").val()
    socket.send(message);
  });
  })
</script>
</html>

動かすのはgunicornを使う

gunicorn -k flask_sockets.worker app:app

でlocalhost:8000にアクセスすればok

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021