How to pass HTML form data stored in a variable to a Python script in Flask?
我正在构建一个数据产品(一个NLP聊天应用程序),我正在为它学习flask,这样用户就可以有一个更好的UI来与我的产品交互。
我已经在flask中编写了以下代码,以获取用户输入并将其存储在变量中。
主.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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() |
初始.html
1 2 3 4 5 6 7 8 9 10 11 12 | <!DOCTYPE HTML> <html> <body> <form action="{{ url_for('handle_data') }}" method="post"> <input type="text" name="userQuestion"> <input type="submit"> </form> </body> </html> |
号
我已经处理了表单数据并将其存储在一个变量
文档2vec_main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 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"])) |
我的问题是,我找不到一种方法将
我在网上搜了很多东西,但没用。你能给我推荐一种方法吗?我完全是个新手,所以请原谅我的任何错误。
我找到了一个可能的解决办法。在python脚本文件中导入sys
当您像这样运行脚本时->python doc2vec_main.py"这里有问题"
您可以通过
1 2 3 | >>> import sys >>> print(sys.argv) >>>['doc2vec_main.py', 'question here'] |
所以你可以简单地用这个
1 | document = sys.argv[1] |
号
好吧,我们找到了手动的方法,但是你需要用烧瓶自动完成。
烧瓶内附件
然后当您想执行外部脚本时,请执行以下操作
1 | os.system("python doc2vec_main.py %s") % request.form['userQuestion'] |
你知道这会奏效,但只在一个应用程序中这样做会更好吗?这样会更好。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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() |
。
将脚本放入flask应用程序的另一个模块中,在一个函数下,将要处理的变量作为参数:
1 2 3 4 5 6 7 8 9 10 | 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流期间等待结果。