Herramientas de usuario

Herramientas del sitio


fw:flask

Diferencias

Muestra las diferencias entre dos versiones de la página.

Enlace a la vista de comparación

Ambos lados, revisión anterior Revisión previa
Próxima revisión
Revisión previa
fw:flask [2013/07/15 11:18]
alfred
fw:flask [2020/05/09 09:25] (actual)
Línea 12: Línea 12:
 def home(): def home():
     return redirect(url_for('​static',​ filename='​index.html'​))     return redirect(url_for('​static',​ filename='​index.html'​))
 +</​code>​
 +===== Cómo... =====
 +==== Utilizar websockets ====
 +Para ello necesitas el módulo ''​gevent-websocket''​. \\ 
 +Para mostrarlo usando el siguiente ejemplo:
 +<​code>​
 +  app/
 +  ├── html/
 +  │   ​├── test.html
 +  │   ​└── jquery.min.js
 +  └── test.py
 +</​code>​
 +En test.html:
 +<code html>
 +<​!doctype html>
 +<​html> ​                                                                          
 +<​head> ​                                                                          
 +    <​title>​Flask/​Gevent WebSocket Test</​title> ​                                                  
 +    <script type="​text/​javascript"​ src="​jquery.min.js"></​script>​
 +    <script type="​text/​javascript"​ charset="​utf-8"> ​                             ​
 +        $(document).ready(function(){ ​                                           ​
 +            var ws;
 +            $('​form'​).submit(function(event){ ​  
 +                ws.send($('#​data'​).val());​
 +                console.log('​2. message send: ' + $('#​data'​).val());​
 +                return false; ​                                                   ​
 +            });                                                                  ​
 +            if ("​WebSocket"​ in window) {                                         
 +                ws = new WebSocket("​ws://"​ + document.domain + ":​5000/​api"​);​
 +                console.log('​1. web socket created'​);​
 +                ws.onmessage = function (msg) {
 +                    console.log('​3. message received:'​ + msg);
 +                    $("#​log"​).append("<​p>"​+msg.data+"</​p>"​); ​                  
 +                };                                                               
 +            } else {                                                             
 +                alert("​WebSocket not supported"​); ​                               ​
 +            }                                                                    ​
 +        });                                                                      ​
 +    </​script> ​                                                                   ​
 +</​head> ​                                                                         ​
 +<​body> ​                                                                          
 +    <​h1>​Send:</​h1> ​                                                              
 +    <form method='​POST'​ action='#'>​
 +        <​textarea name='​data'​ id="​data"></​textarea>​
 +        <​div><​input type='​submit'></​div>​
 +    </​form>​
 +    <​h1>​Receive:</​h1>​
 +    <div id="​log"></​div>​
 +</​body>​
 +</​html>​
 +</​code>​
 +En ''​test.py'':​
 +<code python>
 +#​!/​usr/​bin/​python
 +# -*- coding: utf-8 *-*
 +
 +from geventwebsocket.handler import WebSocketHandler
 +from gevent.pywsgi import WSGIServer
 +from flask import Flask, request, redirect, url_for
 + 
 +app = Flask(__name__,​ static_folder='​html',​ static_url_path=''​)
 + 
 +@app.route('/'​)
 +def index():
 +    return redirect(url_for('​static',​ filename='​test.html'​))
 + 
 +@app.route('/​api'​)
 +def api():
 +    if request.environ.get('​wsgi.websocket'​):​
 +        ws = request.environ['​wsgi.websocket'​]
 +        while True:
 +            message = ws.receive()
 +            ws.send(message)
 +    else:
 +        print 'No support for websockets!'​
 +    return
 + 
 +if __name__ == '​__main__':​
 +    http_server = WSGIServer(('',​5000),​ app, handler_class=WebSocketHandler)
 +    http_server.serve_forever()
 +</​code>​
 +==== Notas ====
 +=== Apagar el server? ===
 +<code python>
 +def shutdown_server():​
 +    func = request.environ.get('​werkzeug.server.shutdown'​)
 +    if func is None:
 +        raise RuntimeError('​Not running with the Werkzeug Server'​)
 +    func()
 +</​code>​
 +El server está programado para finalizar la última petición y apagarse.
 +
 +=== Recibir JSON ===
 +<code javascript>​
 +$.ajax({
 +    type: '​POST',​
 +    contentType:​ '​application/​json',​
 +    data: JSON.stringify(post_obj),​
 +    dataType: '​json',​
 +    url: '/​some/​url',​
 +    success: function (e) {
 +        console.log(e);​
 +    }
 +});
 +</​code>​
 +<code python>
 +content = request.json['​content'​]
 </​code>​ </​code>​
fw/flask.1373887120.txt.gz · Última modificación: 2020/05/09 09:24 (editor externo)