来自FLASK通过AJAX调用的结果在网页上的警报通知中没有返回结果

huangapple go评论63阅读模式
英文:

No return of result from FLASK call via AJAX in an alert notifcation on the web page

问题

以下是你要翻译的内容:

基本上,我正在比较两个文本,一个输入是PDF,另一个是基本文本。我已经创建了一个包含另一个HTML的索引HTML,以提高清晰度,使用了Python的FLASK功能。所有代码都是分开运行的,所有提到的有关无效输入的错误都很好地一起运行,只是主要结果输出,我认为我在调用和执行主函数时出了问题,因为所有警报和文件检查都在工作,Flask内部的逻辑也在工作。

我的带有Ajax和表单的HTML文件:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    
    function submitForm() {
      // 显示加载屏幕
      document.getElementById("loading").style.display = "block";

      // 获取输入值
      var JD = document.getElementById("JD").value;
      var file = document.getElementById("FL").file[0];

      // 检查是否已选择文件且为PDF
      if (!file || file.type !== 'application/pdf') {
        alert("请选择有效的PDF文件");
        return;
      }

      // 检查文件大小是否小于5 MB
      if (file.size > 5000000) {
        alert("文件大小不应超过5 MB");
        return;
      }

      // 创建一个FormData对象,以发送文件和jd到API
      var formData = new FormData($('#upload_form')[0]);
      formData.append("FL", FL);
      formData.append("JD", JD);

      // 进行API调用
      $.ajax({
        url: base_url + "api/Analyze",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function(result) {
          // 隐藏加载屏幕
          document.getElementById("loading").style.display = "none";
          alert(result);
        },
        error: function () {
          // 隐藏加载屏幕
          document.getElementById("loading").style.display = "none";

          // 显示错误
          alert("API调用期间出现错误");
        }
      });
    }
</script>
</head>
<body>
  <h2>分析</h2>
  <form id="upload_form" enctype="multipart/form-data">
    <p>
      <label for="JD">描述:</label>
      <textarea name="JD" id="JD" rows="4" cols="50"></textarea>
    </p>
    <p>
      <label for="FL">文件:</label>
      <input type="file" name="FL" id="FL" accept="application/pdf">
    </p>
    <p>
      <input type="button" value="提交" onclick="submitForm()">
    </p>
  </form>
  <div id="loading" style="display: none;">加载中...</div>

这是app.py Flask文件:

from flask import Flask, render_template, redirect, request, jsonify
import fitz
import re
import sys
#(请忽略不相关的导入)


app = Flask(__name__)

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

@app.route('/Analyze', methods=['GET'])
def analyze():
    return render_template('analyze.html')

#(忽略这个大块的代码)
@app.route('/BulkAnalyze', methods=['GET'])
def bulk_analyze():
    return render_template('Bulk.html')


@app.route('/api/Analyze', methods=['POST'])
def Submit():
    pdf_file = request.files['FL']
    jd_text = request.form['JD']
    
    jd_text = " ".join(jd_text.split('\n'))

    with fitz.open(pdf_file) as doc:
        text = ''
        for page in doc:
            text += page.get_text()
    text = ' '.join(text.split('\n'))

    # 执行文本比较
    matching_words = [word for word in jd_text.split() if word in text.split()]
    match = 100 * len(matching_words) / len(jd_text.split())
    return jsonify({'result': '匹配百分比为:' + match })

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

我试图比较这两个文本输入以获得一个百分比输出作为警报。我知道我可以在页面上显示输出来规避这个问题,但这不是一个实际的问题,我想从中学习。

英文:

Basically I a comparing two texts one input is a pdf, another basic text.
I have created index html and within is another html for a bit clarity. using python FLASK feature.
All the code runs separately, all mentioned errors for invalid input run very fine together, its just the main result output, I presume I am messing up somehow in calling and executing the main function because all the alerts and file checks are working , and the logic inside of flask is working too.

My html file with ajax and form :

&lt;script src=&quot;https://code.jquery.com/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
function submitForm() {
// Show the loading screen
document.getElementById(&quot;loading&quot;).style.display = &quot;block&quot;;
// Get the input values
var JD = document.getElementById(&quot;JD&quot;).value;
var file = document.getElementById(&quot;FL&quot;).file[0];
// Check if a file has been selected and is a pdf
if (!file || file.type !== &#39;application/pdf&#39;) {
alert(&quot;Please select a valid PDF file&quot;);
return;
}
// Check if file size is less than 5 MB
if (file.size &gt; 5000000) {
alert(&quot;File size should not exceed 5 MB&quot;);
return;
}
// Create a FormData object to send both the file and the jd to the API
var formData = new FormData($(&#39;#upload_form&#39;)[0]);
formData.append(&quot;FL&quot;, FL);
formData.append(&quot;JD&quot;, JD);
// Make the API call
$.ajax({
url: base_url + &quot;api/Analyze&quot;,
type: &quot;POST&quot;,
data: formData,
processData: false,
contentType: false,
success: function(result) {
// Hide the loading screen
document.getElementById(&quot;loading&quot;).style.display = &quot;none&quot;;
alert(result);
},
error: function () {
// Hide the loading screen
document.getElementById(&quot;loading&quot;).style.display = &quot;none&quot;;
// Display the error
alert(&quot;Error during API call&quot;);
}
});
}
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h2&gt;Analysis&lt;/h2&gt;
&lt;form id=&quot;upload_form&quot; enctype=&quot;multipart/form-data&quot;&gt;
&lt;p&gt;
&lt;label for=&quot;JD&quot;&gt;Description:&lt;/label&gt;
&lt;textarea name = &quot;JD&quot; id=&quot;JD&quot; rows=&quot;4&quot; cols=&quot;50&quot;&gt;&lt;/textarea&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;label for=&quot;FL&quot;&gt;FILE:&lt;/label&gt;
&lt;input type=&quot;file&quot; name=&quot;FL&quot; id=&quot;FL&quot; accept=&quot;application/pdf&quot;&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;input type=&quot;button&quot; value=&quot;Submit&quot; onclick=&quot;submitForm()&quot;&gt;
&lt;/p&gt;
&lt;/form&gt;
&lt;div id=&quot;loading&quot; style=&quot;display: none;&quot;&gt;Loading...&lt;/div&gt;

And this is the app.py flask file -

from flask import Flask, render_template, redirect, request, jsonify
import fitz
import re
import sys
#(please ignore irrelevant imports)
app = Flask(__name__)
@app.route(&#39;/&#39;, methods=[&#39;GET&#39;])
def index():
return render_template(&#39;index.html&#39;)
@app.route(&#39;/Analyze&#39;, methods=[&#39;GET&#39;])
def analyze():
return render_template(&#39;analyze.html&#39;)
#(ignore this bulk one)
@app.route(&#39;/BulkAnalyze&#39;, methods=[&#39;GET&#39;])
def bulk_analyze():
return render_template(&#39;Bulk.html&#39;)
@app.route(&#39;/api/Analyze&#39;, methods=[&#39;POST&#39;])
def Submit():
pdf_file = request.files[&#39;FL&#39;]
jd_text = request.form[&#39;JD&#39;]
jd_text = &quot; &quot;.join(jd_text.split(&#39;\n&#39;))
with fitz.open(pdf_file) as doc:
text = &#39;&#39;
for page in doc:
text += page.get_text()
text = &#39; &#39;.join(text.split(&#39;\n&#39;))
# Perform text comparison
matching_words = [word for word in jd_text.split() if word in text.split()]
match = 100 * len(matching_words) / len(jd_text.split())
return jsonify({&#39;result&#39;: &#39;The matching percentage is :&#39; + match })
if __name__ == &quot;__main__&quot;:
app.run()

I was trying to compare those two text input to get a percentage output as an alert.
I am aware i could display output on page or another webpage to circumnavigate this issue, but this is not some irl problem and i would love to learn from this.

答案1

得分: 0

以下是您要翻译的内容:

"An uploaded file results in an object of type FileStorage on the server side. It is a file-like object for the loaded PDF file. It is not possible to extract the text directly from the FileStorage object. The data must first be read into a stream."

以下是基于您的代码稍作修改后的示例。

from flask import (
	Flask, 
	jsonify, 
	redirect, 
	render_template, 
	request
)
import fitz
import io
import re

app = Flask(__name__)

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

@app.post('/api/analyze')
def api_analyze():
	pcnt = 0
	try:
		desc = request.form['desc']
		file = request.files['file']

		with io.BytesIO(file.read()) as fh, fitz.open(stream=fh, filetype='pdf') as doc:
			text = ' '.join(page.get_text() for page in doc)
		
		tokens_desc = set(re.findall(r'\b\w+\b', desc))
		tokens_text = set(re.findall(r'\b\w+\b', text))
		tokens_match = tokens_text & tokens_desc

		pcnt = len(tokens_match) / len(tokens_desc) * 100
	finally:
		return jsonify(result=f'The matching percentage is: {pcnt}%')
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Index</title>
</head>
<body>

	<form name="upload-form">
		<div>
			<label for="file">选择文件:</label>
			<input type="file" name="file" id="file" accept="application/pdf" />
		</div>
		<div>
			<label for="desc">描述:</label>
			<textarea name="desc" id="desc" rows="4" cols="50"></textarea>
		</div>
		<div>
			<input type="submit" value="提交" />
		</div>
	</form>

	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<script>
		$(function() {
			$('form[name="upload-form"]').submit(function(event) {
				event.preventDefault();

				const file = this['file'].files[0];
				if (!file || file.type !== 'application/pdf') {
					alert('请选择有效的PDF文件');
					return;
				}

				if (file.size > 5000000) {
					alert('文件大小不应超过5MB');
					return;
				}

				$.ajax({
					url: '/api/analyze', 
					type: 'post', 
					data: new FormData(this), 
					processData: false, 
					contentType: false
				}).done(function(data) {
					alert(data.result);
				}).fail(function() {
					alert('API调用期间出现错误。');
				});
			})
		});
	</script>
	
</body>
</html>
英文:

An uploaded file results in an object of type FileStorage on the server side. It is a file-like object for the loaded PDF file. It is not possible to extract the text directly from the FileStorage object. The data must first be read into a stream.

The following is the slightly modified example based on your code.

from flask import (
	Flask, 
	jsonify, 
	redirect, 
	render_template, 
	request
)
import fitz
import io
import re

app = Flask(__name__)

@app.route(&#39;/&#39;)
def index():
	return render_template(&#39;index.html&#39;)

@app.post(&#39;/api/analyze&#39;)
def api_analyze():
	pcnt = 0
	try:
		desc = request.form[&#39;desc&#39;]
		file = request.files[&#39;file&#39;]

		with io.BytesIO(file.read()) as fh, fitz.open(stream=fh, filetype=&#39;pdf&#39;) as doc:
			text = &#39; &#39;.join(page.get_text() for page in doc)
		
		tokens_desc = set(re.findall(r&#39;\b\w+\b&#39;, desc))
		tokens_text = set(re.findall(r&#39;\b\w+\b&#39;, text))
		tokens_match = tokens_text &amp; tokens_desc

		pcnt = len(tokens_match) / len(tokens_desc) * 100
	finally:
		return jsonify(result=f&#39;The matching percentage is: {pcnt}%&#39;)
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
	&lt;meta charset=&quot;utf-8&quot;&gt;
	&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
	&lt;title&gt;Index&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

	&lt;form name=&quot;upload-form&quot;&gt;
		&lt;div&gt;
			&lt;label for=&quot;file&quot;&gt;Choose a file:&lt;/label&gt;
			&lt;input type=&quot;file&quot; name=&quot;file&quot; id=&quot;file&quot; accept=&quot;application/pdf&quot; /&gt;
		&lt;/div&gt;
		&lt;div&gt;
			&lt;label for=&quot;desc&quot;&gt;Description:&lt;/label&gt;
			&lt;textarea name=&quot;desc&quot; id=&quot;desc&quot; rows=&quot;4&quot; cols=&quot;50&quot;&gt;&lt;/textarea&gt;
		&lt;/div&gt;
		&lt;div&gt;
			&lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;
		&lt;/div&gt;
	&lt;/form&gt;

	&lt;script src=&quot;https://code.jquery.com/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt;
	&lt;script&gt;
		$(function() {
			$(&#39;form[name=&quot;upload-form&quot;]&#39;).submit(function(event) {
				event.preventDefault();

				const file = this[&#39;file&#39;].files[0];
				if (!file || file.type !== &#39;application/pdf&#39;) {
					alert(&#39;Please select a valid PDF file&#39;);
					return;
				}

				if (file.size &gt; 5000000) {
					alert(&#39;File size should not exceed 5 MB&#39;);
					return;
				}

				$.ajax({
					url: &#39;/api/analyze&#39;, 
					type: &#39;post&#39;, 
					data: new FormData(this), 
					processData: false, 
					contentType: false
				}).done(function(data) {
					alert(data.result);
				}).fail(function() {
					alert(&#39;Error during API call.&#39;);
				});
			})
		});
	&lt;/script&gt;
	
&lt;/body&gt;
&lt;/html&gt;

huangapple
  • 本文由 发表于 2023年2月14日 01:49:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75439517.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定