Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将存储在变量中的HTML表单数据传递给Flask中的Python脚本?_Python_Flask_Nlp - Fatal编程技术网

如何将存储在变量中的HTML表单数据传递给Flask中的Python脚本?

如何将存储在变量中的HTML表单数据传递给Flask中的Python脚本?,python,flask,nlp,Python,Flask,Nlp,我正在构建一个数据产品(一个NLP聊天应用程序),我正在学习它,以便用户可以有更好的UI与我的产品交互 我在Flask中写下了以下代码,以获取用户输入并将其存储在变量中 main.py from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def index(): return render_template('init.html') @app.route('/ha

我正在构建一个数据产品(一个NLP聊天应用程序),我正在学习它,以便用户可以有更好的UI与我的产品交互

我在Flask中写下了以下代码,以获取用户输入并将其存储在变量中

main.py

from flask import Flask, render_template, request
app = Flask(__name__)

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

@app.route('/handle_data', methods = ['POST', 'GET'])
def handle_data():
    userQuestion = request.form['userQuestion']
    print(userQuestion)
    return render_template('init.html', userQuestion = userQuestion)

if __name__ == '__main__':
   app.run()
import gensim
import nltk
import numpy
from gensim import models
from gensim import utils
from gensim import corpora
from nltk.stem import PorterStemmer
ps = PorterStemmer()

sentence0 = models.doc2vec.LabeledSentence(words=[u'sampling',u'what',u'is',u'sampling'],tags=["SENT_0"])
sentence1 = models.doc2vec.LabeledSentence(words=[u'sampling',u'tell',u'me',u'about',u'sampling'],tags=["SENT_1"])
sentence2 = models.doc2vec.LabeledSentence(words=[u'elig',u'what',u'is',u'my',u'elig'],tags=["SENT_2"])
sentence3 = models.doc2vec.LabeledSentence(words=[u'eligiblity',u'limit', u'what',u'is',u'my'],tags=["SENT_3"])
sentence4 = models.doc2vec.LabeledSentence(words=[u'eligiblity',u'claim',u'how',u'much',u'can',u'I'],tags=["SENT_4"])
sentence5 = models.doc2vec.LabeledSentence(words=[u'retir',u'eligibility',u'claim',u'i',u'am',u'how',u'much',u'can',u'i'],tags=["SENT_5"])
# ... list of all the training set.

# User inputs a question
document = input("Ask a question:")
tokenized_document = list(gensim.utils.tokenize(document, lowercase = True, deacc = True))
stemmed_document = []
for w in tokenized_document:
    stemmed_document.append(ps.stem(w))

sentence19 = models.doc2vec.LabeledSentence(words= stemmed_document, tags=["SENT_19"])

sentences = [sentence0,sentence1,sentence2,sentence3, sentence4, sentence5,sentence6, sentence7, sentence8, sentence9, sentence10, sentence11, sentence12, sentence13, sentence14, sentence15, sentence16, sentence17, sentence18, sentence19]

model = models.Doc2Vec(size=4, alpha=0.25, min_alpha=.025, min_count=1)
model.build_vocab(sentences)
for epoch in range(30):
    model.train(sentences, total_examples=model.corpus_count, epochs = 
    model.iter)
    model.alpha -= 0.002
    model.min_alpha = model.alpha
model.save("my_model.doc2vec")
model_loaded = models.Doc2Vec.load('my_model.doc2vec')
print (model.docvecs.most_similar(["SENT_19"]))
init.html

<!DOCTYPE HTML>
<html>
<body>


<form action="{{ url_for('handle_data') }}" method="post">
    <input type="text" name="userQuestion">
    <input type="submit">
</form>

</body>
</html>
我的问题是我找不到方法将
doc2vec_main.py
连接到
main.py
并将
userQuestion
的值传递到
doc2main.py
剧本也就是说,当用户在表单中输入一个问题并单击submit时,表单的值将传递到
doc2vec_main.py
中的
document
,剩下的脚本将运行


我在网上搜索了很多,但都没用。你能给我一个建议吗?我是烧瓶的初学者,请原谅我的错误。

我找到了一个可能的解决方案。 在python脚本文件中导入sys

当您像这样运行脚本->python doc2vec_main.py“这里的问题”

您可以通过以下方式访问该变量:

>>> import sys
>>> print(sys.argv)
>>>['doc2vec_main.py', 'question here']
那么你可以简单地使用这个

document = sys.argv[1]
好的,我们找到了手动的方法,但你需要用烧瓶自动完成

内置烧瓶应用程序
导入操作系统

然后,当您想要执行外部脚本时,请执行以下操作

os.system("python doc2vec_main.py %s") % request.form['userQuestion']

你知道这会起作用,但在一个应用程序中这样做不是更好吗?那会更好。

我找到了一个可能的解决办法。
import gensim
import nltk
import numpy
from gensim import models
from gensim import utils
from gensim import corpora
from nltk.stem import PorterStemmer
ps = PorterStemmer()

# load the model here
model_loaded = models.Doc2Vec.load('my_model.doc2vec')

from flask import Flask, render_template, request
app = Flask(__name__)

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

@app.route('/handle_data', methods = ['POST', 'GET'])
def handle_data():
    userQuestion = request.form['userQuestion']
    print(userQuestion)
    q_vector = doc2vec_main(userQuestion)
    return render_template('init.html', userQuestion = userQuestion)

def doc2vec_main(document):
    """whatever you want to do with your pre-trained doc2vec model can go here. I assume that doc2vec_main meant to return vector for a given document. for training part of the code you should write a separate function."""
    # your code here!
    return "replace this with your vector"

if __name__ == '__main__':
   app.run()
在python脚本文件中导入sys

当您像这样运行脚本->python doc2vec_main.py“这里的问题”

您可以通过以下方式访问该变量:

>>> import sys
>>> print(sys.argv)
>>>['doc2vec_main.py', 'question here']
那么你可以简单地使用这个

document = sys.argv[1]
好的,我们找到了手动的方法,但你需要用烧瓶自动完成

内置烧瓶应用程序
导入操作系统

然后,当您想要执行外部脚本时,请执行以下操作

os.system("python doc2vec_main.py %s") % request.form['userQuestion']

你知道这会起作用,但在一个应用程序中这样做不是更好吗?更好。

将脚本放在Flask应用程序的另一个模块中,放在一个函数下,该函数以要处理的变量作为参数:

import gensim
import nltk
import numpy
from gensim import models
from gensim import utils
from gensim import corpora
from nltk.stem import PorterStemmer
ps = PorterStemmer()

# load the model here
model_loaded = models.Doc2Vec.load('my_model.doc2vec')

from flask import Flask, render_template, request
app = Flask(__name__)

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

@app.route('/handle_data', methods = ['POST', 'GET'])
def handle_data():
    userQuestion = request.form['userQuestion']
    print(userQuestion)
    q_vector = doc2vec_main(userQuestion)
    return render_template('init.html', userQuestion = userQuestion)

def doc2vec_main(document):
    """whatever you want to do with your pre-trained doc2vec model can go here. I assume that doc2vec_main meant to return vector for a given document. for training part of the code you should write a separate function."""
    # your code here!
    return "replace this with your vector"

if __name__ == '__main__':
   app.run()
import gensim
import nltk
import numpy
from gensim import models
from gensim import utils
from gensim import corpora
from nltk.stem import PorterStemmer

def doc2vec(user_question):
    # your code here...

在handle_data Flask视图中,只需将值从窗体传递到函数。考虑到如果您的函数很昂贵,因此无法在正常的请求/响应http流期间等待结果,则此操作无法工作。

将脚本放在Flask应用程序的另一个模块中,放在以要处理的变量为参数的函数下:

import gensim
import nltk
import numpy
from gensim import models
from gensim import utils
from gensim import corpora
from nltk.stem import PorterStemmer

def doc2vec(user_question):
    # your code here...

在handle_data Flask视图中,只需将值从窗体传递到函数。考虑到如果您的函数很昂贵,因此无法在正常的请求/响应http流中等待结果,则此功能无法工作。

可能重复,因此您想这样做吗?python doc2vec_main.py arg1=来自?flask???@Craicerjack在函数handle_data()中使用userQuestion会抛出一个错误“userQuestion not defined”。@Δημήτρηηφιλίππο,我不这么认为。我的目标是构建一个应用程序,在这个应用程序中,用户通过表单输入问题,并在同一网页中得到返回的答案。应该在后台自动调用doc2vec_main.py。它应该接受输入并给出输出。然后将你的应用程序集成到flask中,你为什么要将其分离?烧瓶的延展性很好。将您的文件导入flask主应用程序并执行您的操作,加上handledata不是一个全局函数,它是一个flask规则,仅在用户发送请求时触发,可能是的副本,所以您想这样做吗?python doc2vec_main.py arg1=来自?flask???@Craicerjack在函数handle_data()中使用userQuestion会抛出一个错误“userQuestion not defined”。@Δημήτρηηφιλίππο,我不这么认为。我的目标是构建一个应用程序,在这个应用程序中,用户通过表单输入问题,并在同一网页中得到返回的答案。应该在后台自动调用doc2vec_main.py。它应该接受输入并给出输出。然后将你的应用程序集成到flask中,你为什么要将其分离?烧瓶的延展性很好。将您的文件导入flask主应用程序并执行您的操作,另外handledata不是一个全局函数,它是一个仅在用户发送请求时触发的flask规则。我认为此方法不适合我的目的。我接受了你的建议,将我的python脚本集成到flask中,它成功了。我认为这种方法不适合我的目的。我采纳了你的建议,将我的python脚本集成到flask中,它成功了。