简体   繁体   English

如何让JavaScript和Python通过Flask进行持续通信?

[英]How do I get JavaScript and Python to communicate continuously via Flask?

I am very new to JavaScript, Python, and web development, but I am trying to create a webpage that takes in data whenever a key is pressed and sends it to a python back end for processing. 我对JavaScript,Python和Web开发非常陌生,但是我试图创建一个网页,每当按下一个键时就会接收数据,并将其发送到python后端进行处理。 The Python back end will then send information back to the JavaScript page, and the JavaScript page will respond to it. 然后,Python后端将信息发送回JavaScript页面,而JavaScript页面将对此作出响应。 This process needs to happen continuously, or until it is terminated by a certain response from the Python portion. 这个过程需要连续发生,或者直到被Python部分的某个响应终止为止。 I already have a script written that gathers all of the data I need on the Javascript end, and I have a Python application that processes it (it needs a little editing to take in one array at a time, but that is not the question). 我已经编写了一个脚本,可以在Javascript端收集我需要的所有数据,并且我有一个处理它的Python应用程序(它需要进行一点编辑才能一次放入一个数组,但这不是问题) 。 Currently, my trouble has centered around getting them to communicate. 目前,我的麻烦集中在让他们进行沟通上。 I am using Flask as this is in the early stages of development, and I've read it makes for an easy and efficient tool. 我正在使用Flask,因为它处于开发的早期阶段,并且我读过它使它成为一种简单而有效的工具。

I started by trying to follow tutorials on how to get the thing up and running, without too much success. 我首先尝试遵循有关如何启动和运行该产品的教程,但并没有取得太大的成功。 All of the tutorials I've found online are centered around an example, leaving me rather confused about the general. 我在网上找到的所有教程都以一个示例为中心,这让我对常规感到困惑。 The code I am showing below is what I have to work with from one of the tutorials. 我在下面显示的代码是我必须从其中一个教程中使用的代码。 I know that render_template opens up the file given (in this case index.html). 我知道render_template会打开给定的文件(在本例中为index.html)。 My first question is: would I put the JavaScript portion as a script within that index file? 我的第一个问题是:我是否会将JavaScript部分作为脚本放入该索引文件中? I've read that logic should generally be kept out of the templates, but I'm not sure how else I'd run this script- it is supposed to run continually underneath what the user is doing on the website. 我读过,逻辑通常应该放在模板之外,但是我不确定我还要如何运行该脚本-它应该在用户在网站上进行的操作下连续运行。 Some other tutorials have indicated that perhaps the answer is to use multiple @app.route statements, but I am not even certain what @app.route is doing exactly. 其他一些教程已经表明,答案可能是使用多个@ app.route语句,但是我什至不确定@ app.route到底在做什么。 I know it is a decorator, but for what function and what it is changing it to eludes me even after basic research. 我知道它是一个装饰器,但是即使经过基础研究,对于它的功能和它所发生的变化,我仍然难以理解。 What does @app.route do? @ app.route有什么作用? Another tutorial I followed gave me something like what is shown below, but I'm a little confused as to what each @app.route is doing. 我遵循的另一个教程给了我类似如下所示的内容,但是我对每个@ app.route的功能有些困惑。 I'm also not sure what request.get_json() is. 我也不确定什么是request.get_json()。 From what I have read, JSON is a way of describing data by its attributes rather than including all of the data itself, but I'm not sure what request does (I know it was imported from flask). 据我所读,JSON是一种通过其属性描述数据的方式,而不是包括所有数据本身,但是我不确定请求是做什么的(我知道它是从flask导入的)。

From here, the JavaScript needs to have a post function, right? 从这里开始,JavaScript需要具有post函数,对吗? I am assuming that Python would "get" what JavaScript "posted", but the second tutorial's code seems to indicate otherwise (as the function that requests the data (I assume) via request.get_json() is also listed as methods = ['POST']). 我假设Python将“获取” JavaScript“发布”的内容,但是第二篇教程的代码似乎表明其他情况(因为通过request.get_json()请求数据(我假设)的函数也被列为method = [' POST'])。 I am also assuming that I am able to run a 'POST' request on the front-end as part of a function that responds to an Event Listener (on keypress). 我还假设我能够在前端运行“ POST”请求,作为响应事件监听器(在按键上)的功能的一部分。 After Python gets what JavaScript posted Python would post a response and JavaScript would get that and respond to it in kind. 在Python获取JavaScript发布的内容之后,Python将发布响应,JavaScript将获取响应并以实物方式响应。 I am assuming that is how that all works. 我假设这就是所有方法。

Finally, does someone have an explanation or resource on how JavaScript posts or gets requests? 最后,有人对JavaScript如何发布或获取请求有解释或资源吗? I have some resources I can try, but I haven't had much time to fully explore them yet. 我有一些资源可以尝试,但是我还没有很多时间来充分探索它们。 I have included in the code section what I have tried so far. 我在代码部分中包含了到目前为止我已经尝试过的内容。

In summary, I feel a bit overwhelmed as I rush into the world of front-end and back-end development. 总而言之,当我进入前端和后端开发领域时,我感到有些不知所措。 I feel as if I understand the overarching ideas behind it, but many of the specifics have been very confusing to me. 我感觉好像我了解它背后的总体思想,但是许多细节对我来说非常混乱。 Let me know if there's anything I need to know that I have no clue about yet- thank you for the help, I'm sorry this isn't as specific as it could be. 让我知道是否有什么我不知道的线索-谢谢您的帮助,很抱歉,这还不够具体。

// Tutorial Python code
import os
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html", message = "Hello Flask!", contacts = ['c1', 'c2', 'c3', 'c4', 'c5']);


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

// Corresponding Tutorial HTML
<!DOCTYPE html>
<html>
  <head>
    <title>Flask Template Example</title>
  </head>

  <body>
    <div>
      <p>{{ message }}</p>

      <p>{{ contacts }}</p>
      <p>My Contacts:</p>
      <ul>
        {% for contact in contacts %}
        <li>{{ contact }}</li>
        {% endfor %}
      </ul>
    </div>
  </body>

</html>

// Second tutorial Python, two @app.route

import sys

from flask import Flask, render_template, request, redirect, Response
import random, json

app = Flask(__name__)

@app.route('/')
def output():
  return render_template('index.html', name='Joe')

@app.route('/reciever', methods = ['POST'])
def worker():
  data = request.get_json()
  result = ''

  for item in data:
    result += str(item['make']) + '\n'

  return result

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

// JavaScript communication first attempt (I was sending them to the second tutorial's Python code)

var sentArray = {"array" : [key, start, finish, holdtime, ud, uu, dd, 1]};
$.post("reciever",sentArray,function(){
});
    event.preventDefault();

// JavaScript communication second attempt

var sentArray = {"array" : [key, start, finish, holdtime, ud, uu, dd, 1]};
fetch('/typing', {
  method: 'POST',

  headers: {
    'Content-Type': 'application/json'
  }

  body: 
     {"array" : [key, start, finish, holdtime, ud, uu, dd, 1]}
}
});
event.preventDefault();

Currently, I receive a 500 error, indicating I'm not handling something properly. 目前,我收到500错误消息,表明我没有正确处理某些问题。 I'm not sure what, frankly there are hundreds of ways I could be doing this wrong. 我不确定是什么,坦率地说,有数百种方法可以解决这个问题。 Thanks for the help! 谢谢您的帮助!

尝试使用ajax,它允许您在后台发送帖子或获取请求,我通过以下方式学习了ajax: vid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM