如何通过终端在 flask-socketio 服务器(聊天)上 post?

how to post on flask-socketio server (Chat) via terminal?

我正在与 flask-socketio 进行工作聊天。 我想通过从终端发送数据与服务器和视图进行交互。 我收到 200 条消息,但视图上没有任何反应。我看不到我的消息,聊天者看不到我。 这是我试过的终端命令。 (我更喜欢使用 python requests 或 flask-request command with idle 而不是 bash。)

curl -i -H "Content-Type: application/json" -X POST -d '{'user_name': 'terminal', 'message': 'hack'}' http://localhost:5000/terminal_post

curl -i -H "Content-Type: application/json" -X POST -d "user_name=terminal&message=hack" http://localhost:5000/terminal_post

这是我的代码(附有对我尝试的评论):

server.py

app = Flask(__name__, template_folder="templates", static_folder="static")

app.config['SECRET_KEY'] = 'jsbcfwbfjefezw666b3gdbdc'

socketio = SocketIO(app  , async_mode='eventlet')

@app.route('/', methods=['GET', 'POST'])
def hello():
  return render_template( './index.html' )

def messageRecived():
  print( 'message was received!!!' )

@socketio.on( 'my event' )
def handle_my_custom_event( json ):
  print( 'recived my event: ' + str( json ) )
  socketio.emit( 'my response', json, callback=messageRecived )



def transmitter_from_http_2_io(parameter):
  socketio.emit( 'my response', parameter) #how to go from http terminal to websocket on view?

@app.route('/terminal_post', methods=['POST'])
def terminal_post():
  #data = request.get_json() # Failed to decode JSON object: Expecting property name enclosed in double quotes
  data = request.form
  for foobar in data:
    print("-> ", foobar)
  print( 'recived terminal_post : ' + str( data ) )
  #socketio.emit( 'my response', data) # nothing happen
  transmitter_from_http_2_io(data)
  return "ok"

if __name__ == '__main__':
  #socketio.run( app, debug = True )
  socketio.run(app, host="0.0.0.0", port=5000, debug = True)

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Python Chat App Yo</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" 
    integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <style>
      div.msg_bbl {
        background-color: #ddd;
        padding: 5px 10px;
        border-radius: 10px;
        color: #555;
        margin-bottom: 5px;
      }
    </style>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>

    <div class="text-center well"><b>Mon Super Chat </b></div>



    <div class="container">
      <div class="col-sm-8">
        <div class="no_message">
          <h1 style='color: #ccc'>Pas encore de message...</h1>
          <div class="message_holder"></div>
        </div>
      </div>
      <div class="col-sm-4">
        <form action="" method="POST">
          <b>Ecrivez votre message <span class="glyphicon glyphicon-arrow-down"></span></b>
          <div class="clearfix" style="margin-top: 5px;"></div>
          <input type="text" class="username form-control" placeholder="Pseudo">
          <div style="padding-top: 5px;"></div>
          <input type="text" class="message form-control" placeholder="Messages">
          <div style="padding-top: 5px;"></div>
          <button type="submit" class="btn btn-success btn-block"><span class="glyphicon glyphicon-send"></span> Envoyer</button>
        </form>
      </div>
    </div>




    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>

    <script type="text/javascript" charset="utf-8">
      var socket = io.connect( 'http://' + document.domain + ':' + location.port )
      // broadcast a message
      socket.on( 'connect', function() {
        socket.emit( 'my event', {
          data: 'User Connected'
        } )
        var form = $( 'form' ).on( 'submit', function( e ) {
          e.preventDefault()
          let user_name = $( 'input.username' ).val()
          let user_input = $( 'input.message' ).val()
          socket.emit( 'my event', {
            user_name : user_name,
            message : user_input
          } )
          // empty the input field
          $( 'input.message' ).val( '' ).focus()
        } )
      } )

      // capture message
      socket.on( 'my response', function( msg ) {
        console.log( msg )
        if( typeof msg.user_name !== 'undefined' ) {
          $( 'h1' ).remove()
          $( 'div.message_holder' ).append( '<div class="msg_bbl"><b style="color: #000">'+msg.user_name+'</b> '+msg.message+'</div>' )
        }
      } )
    </script>
  </body>
</html>

试试这个:

curl -i -H "Content-Type: application/json" -X POST -d '{"user_name": "terminal", "message": "hack"}' http://localhost:5000/terminal_post

JSON 要求所有引号都是双引号,你用的是单引号。

然后在您的代码中返回到 JSON 负载:

data = request.get_json()
# data = request.form