我对web框架的了解相当差。我用python建立了一个机器学习模型,它接受一组字符串作为输入并返回结果。在网上搜索后,我遇到了Flask
。但我不知道的是如何创建一个flask应用程序来获取字符串并允许用户提交并将该字符串传递给我的机器学习python脚本并返回结果。这是目前为止我写的所有内容
import threading
import subprocess
import os
import sys
from flask import Flask
from flask import render_template, abort
app = Flask(__name__)
app.debug = True
def run_script():
theproc = subprocess.Popen([sys.executable, "ML_script.py"])
theproc.communicate()
if __name__ == "__main__":
app.run()
如果你能指出一个例子或提供一个解决方案/框架,那将是非常棒的
你可以像使用任何其他Python函数一样使用你的机器学习函数,不需要subprocess
。设置应用程序:
from flask import Flask
from flask import render_template, abort, jsonify, request,redirect, json
from my_app.machine_learning import analyzer
app = Flask(__name__)
app.debug = True
@app.route('/')
def index():
return render_template('index.html')
@app.route('/learning', methods=['POST'])
def learning():
data = json.loads(request.data)
# data == {"userInput": "whatever text you entered"}
response = analyzer(data)
return jsonify(response)
if __name__ == '__main__':
app.run()
我为你的机器学习模块使用了一个名称,但analyzer()
应该是该模块中的一个函数,它调用所有其他函数来进行计算,并返回一个包含结果的字典。像这样:
def analyzer(data):
vocab = build_vocab(training_data)
cl = train_classifier(vocab, trianing_data)
results = cl.predict(data)
results = format_results_to_dict()
return results
模板非常简单:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="../static/script.js"></script>
</script>
</head>
<body>
<h1>Calculation</h1>
<h1>Test Page</h1>
<input id="user-input" placeholder="Text to be analyzed"></input>
<p id="results">Results will go here<p>
<button id="submit">Submit</button>
</body>
</html>
和JS脚本将它们连接在一起:
$(document).ready(function(){
$("#submit").click(function(event){
var uInput = $("#user-input").val();
$.ajax({
type: "POST",
url: '/learning',
data: JSON.stringify({userInput: uInput}),
contentType: 'application/json',
success: function(response){
$("#results").text(response.results);
},
});
});
});