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

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

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文件:

  1. <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  2. <script>
  3. function submitForm() {
  4. // 显示加载屏幕
  5. document.getElementById("loading").style.display = "block";
  6. // 获取输入值
  7. var JD = document.getElementById("JD").value;
  8. var file = document.getElementById("FL").file[0];
  9. // 检查是否已选择文件且为PDF
  10. if (!file || file.type !== 'application/pdf') {
  11. alert("请选择有效的PDF文件");
  12. return;
  13. }
  14. // 检查文件大小是否小于5 MB
  15. if (file.size > 5000000) {
  16. alert("文件大小不应超过5 MB");
  17. return;
  18. }
  19. // 创建一个FormData对象,以发送文件和jd到API
  20. var formData = new FormData($('#upload_form')[0]);
  21. formData.append("FL", FL);
  22. formData.append("JD", JD);
  23. // 进行API调用
  24. $.ajax({
  25. url: base_url + "api/Analyze",
  26. type: "POST",
  27. data: formData,
  28. processData: false,
  29. contentType: false,
  30. success: function(result) {
  31. // 隐藏加载屏幕
  32. document.getElementById("loading").style.display = "none";
  33. alert(result);
  34. },
  35. error: function () {
  36. // 隐藏加载屏幕
  37. document.getElementById("loading").style.display = "none";
  38. // 显示错误
  39. alert("API调用期间出现错误");
  40. }
  41. });
  42. }
  43. </script>
  44. </head>
  45. <body>
  46. <h2>分析</h2>
  47. <form id="upload_form" enctype="multipart/form-data">
  48. <p>
  49. <label for="JD">描述:</label>
  50. <textarea name="JD" id="JD" rows="4" cols="50"></textarea>
  51. </p>
  52. <p>
  53. <label for="FL">文件:</label>
  54. <input type="file" name="FL" id="FL" accept="application/pdf">
  55. </p>
  56. <p>
  57. <input type="button" value="提交" onclick="submitForm()">
  58. </p>
  59. </form>
  60. <div id="loading" style="display: none;">加载中...</div>

这是app.py Flask文件:

  1. from flask import Flask, render_template, redirect, request, jsonify
  2. import fitz
  3. import re
  4. import sys
  5. #(请忽略不相关的导入)
  6. app = Flask(__name__)
  7. @app.route('/', methods=['GET'])
  8. def index():
  9. return render_template('index.html')
  10. @app.route('/Analyze', methods=['GET'])
  11. def analyze():
  12. return render_template('analyze.html')
  13. #(忽略这个大块的代码)
  14. @app.route('/BulkAnalyze', methods=['GET'])
  15. def bulk_analyze():
  16. return render_template('Bulk.html')
  17. @app.route('/api/Analyze', methods=['POST'])
  18. def Submit():
  19. pdf_file = request.files['FL']
  20. jd_text = request.form['JD']
  21. jd_text = " ".join(jd_text.split('\n'))
  22. with fitz.open(pdf_file) as doc:
  23. text = ''
  24. for page in doc:
  25. text += page.get_text()
  26. text = ' '.join(text.split('\n'))
  27. # 执行文本比较
  28. matching_words = [word for word in jd_text.split() if word in text.split()]
  29. match = 100 * len(matching_words) / len(jd_text.split())
  30. return jsonify({'result': '匹配百分比为:' + match })
  31. if __name__ == "__main__":
  32. 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 :

  1. &lt;script src=&quot;https://code.jquery.com/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt;
  2. &lt;script&gt;
  3. function submitForm() {
  4. // Show the loading screen
  5. document.getElementById(&quot;loading&quot;).style.display = &quot;block&quot;;
  6. // Get the input values
  7. var JD = document.getElementById(&quot;JD&quot;).value;
  8. var file = document.getElementById(&quot;FL&quot;).file[0];
  9. // Check if a file has been selected and is a pdf
  10. if (!file || file.type !== &#39;application/pdf&#39;) {
  11. alert(&quot;Please select a valid PDF file&quot;);
  12. return;
  13. }
  14. // Check if file size is less than 5 MB
  15. if (file.size &gt; 5000000) {
  16. alert(&quot;File size should not exceed 5 MB&quot;);
  17. return;
  18. }
  19. // Create a FormData object to send both the file and the jd to the API
  20. var formData = new FormData($(&#39;#upload_form&#39;)[0]);
  21. formData.append(&quot;FL&quot;, FL);
  22. formData.append(&quot;JD&quot;, JD);
  23. // Make the API call
  24. $.ajax({
  25. url: base_url + &quot;api/Analyze&quot;,
  26. type: &quot;POST&quot;,
  27. data: formData,
  28. processData: false,
  29. contentType: false,
  30. success: function(result) {
  31. // Hide the loading screen
  32. document.getElementById(&quot;loading&quot;).style.display = &quot;none&quot;;
  33. alert(result);
  34. },
  35. error: function () {
  36. // Hide the loading screen
  37. document.getElementById(&quot;loading&quot;).style.display = &quot;none&quot;;
  38. // Display the error
  39. alert(&quot;Error during API call&quot;);
  40. }
  41. });
  42. }
  43. &lt;/script&gt;
  44. &lt;/head&gt;
  45. &lt;body&gt;
  46. &lt;h2&gt;Analysis&lt;/h2&gt;
  47. &lt;form id=&quot;upload_form&quot; enctype=&quot;multipart/form-data&quot;&gt;
  48. &lt;p&gt;
  49. &lt;label for=&quot;JD&quot;&gt;Description:&lt;/label&gt;
  50. &lt;textarea name = &quot;JD&quot; id=&quot;JD&quot; rows=&quot;4&quot; cols=&quot;50&quot;&gt;&lt;/textarea&gt;
  51. &lt;/p&gt;
  52. &lt;p&gt;
  53. &lt;label for=&quot;FL&quot;&gt;FILE:&lt;/label&gt;
  54. &lt;input type=&quot;file&quot; name=&quot;FL&quot; id=&quot;FL&quot; accept=&quot;application/pdf&quot;&gt;
  55. &lt;/p&gt;
  56. &lt;p&gt;
  57. &lt;input type=&quot;button&quot; value=&quot;Submit&quot; onclick=&quot;submitForm()&quot;&gt;
  58. &lt;/p&gt;
  59. &lt;/form&gt;
  60. &lt;div id=&quot;loading&quot; style=&quot;display: none;&quot;&gt;Loading...&lt;/div&gt;

And this is the app.py flask file -

  1. from flask import Flask, render_template, redirect, request, jsonify
  2. import fitz
  3. import re
  4. import sys
  5. #(please ignore irrelevant imports)
  6. app = Flask(__name__)
  7. @app.route(&#39;/&#39;, methods=[&#39;GET&#39;])
  8. def index():
  9. return render_template(&#39;index.html&#39;)
  10. @app.route(&#39;/Analyze&#39;, methods=[&#39;GET&#39;])
  11. def analyze():
  12. return render_template(&#39;analyze.html&#39;)
  13. #(ignore this bulk one)
  14. @app.route(&#39;/BulkAnalyze&#39;, methods=[&#39;GET&#39;])
  15. def bulk_analyze():
  16. return render_template(&#39;Bulk.html&#39;)
  17. @app.route(&#39;/api/Analyze&#39;, methods=[&#39;POST&#39;])
  18. def Submit():
  19. pdf_file = request.files[&#39;FL&#39;]
  20. jd_text = request.form[&#39;JD&#39;]
  21. jd_text = &quot; &quot;.join(jd_text.split(&#39;\n&#39;))
  22. with fitz.open(pdf_file) as doc:
  23. text = &#39;&#39;
  24. for page in doc:
  25. text += page.get_text()
  26. text = &#39; &#39;.join(text.split(&#39;\n&#39;))
  27. # Perform text comparison
  28. matching_words = [word for word in jd_text.split() if word in text.split()]
  29. match = 100 * len(matching_words) / len(jd_text.split())
  30. return jsonify({&#39;result&#39;: &#39;The matching percentage is :&#39; + match })
  31. if __name__ == &quot;__main__&quot;:
  32. 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."

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

  1. from flask import (
  2. Flask,
  3. jsonify,
  4. redirect,
  5. render_template,
  6. request
  7. )
  8. import fitz
  9. import io
  10. import re
  11. app = Flask(__name__)
  12. @app.route('/')
  13. def index():
  14. return render_template('index.html')
  15. @app.post('/api/analyze')
  16. def api_analyze():
  17. pcnt = 0
  18. try:
  19. desc = request.form['desc']
  20. file = request.files['file']
  21. with io.BytesIO(file.read()) as fh, fitz.open(stream=fh, filetype='pdf') as doc:
  22. text = ' '.join(page.get_text() for page in doc)
  23. tokens_desc = set(re.findall(r'\b\w+\b', desc))
  24. tokens_text = set(re.findall(r'\b\w+\b', text))
  25. tokens_match = tokens_text & tokens_desc
  26. pcnt = len(tokens_match) / len(tokens_desc) * 100
  27. finally:
  28. return jsonify(result=f'The matching percentage is: {pcnt}%')
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <title>Index</title>
  7. </head>
  8. <body>
  9. <form name="upload-form">
  10. <div>
  11. <label for="file">选择文件:</label>
  12. <input type="file" name="file" id="file" accept="application/pdf" />
  13. </div>
  14. <div>
  15. <label for="desc">描述:</label>
  16. <textarea name="desc" id="desc" rows="4" cols="50"></textarea>
  17. </div>
  18. <div>
  19. <input type="submit" value="提交" />
  20. </div>
  21. </form>
  22. <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  23. <script>
  24. $(function() {
  25. $('form[name="upload-form"]').submit(function(event) {
  26. event.preventDefault();
  27. const file = this['file'].files[0];
  28. if (!file || file.type !== 'application/pdf') {
  29. alert('请选择有效的PDF文件');
  30. return;
  31. }
  32. if (file.size > 5000000) {
  33. alert('文件大小不应超过5MB');
  34. return;
  35. }
  36. $.ajax({
  37. url: '/api/analyze',
  38. type: 'post',
  39. data: new FormData(this),
  40. processData: false,
  41. contentType: false
  42. }).done(function(data) {
  43. alert(data.result);
  44. }).fail(function() {
  45. alert('API调用期间出现错误。');
  46. });
  47. })
  48. });
  49. </script>
  50. </body>
  51. </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.

  1. from flask import (
  2. Flask,
  3. jsonify,
  4. redirect,
  5. render_template,
  6. request
  7. )
  8. import fitz
  9. import io
  10. import re
  11. app = Flask(__name__)
  12. @app.route(&#39;/&#39;)
  13. def index():
  14. return render_template(&#39;index.html&#39;)
  15. @app.post(&#39;/api/analyze&#39;)
  16. def api_analyze():
  17. pcnt = 0
  18. try:
  19. desc = request.form[&#39;desc&#39;]
  20. file = request.files[&#39;file&#39;]
  21. with io.BytesIO(file.read()) as fh, fitz.open(stream=fh, filetype=&#39;pdf&#39;) as doc:
  22. text = &#39; &#39;.join(page.get_text() for page in doc)
  23. tokens_desc = set(re.findall(r&#39;\b\w+\b&#39;, desc))
  24. tokens_text = set(re.findall(r&#39;\b\w+\b&#39;, text))
  25. tokens_match = tokens_text &amp; tokens_desc
  26. pcnt = len(tokens_match) / len(tokens_desc) * 100
  27. finally:
  28. return jsonify(result=f&#39;The matching percentage is: {pcnt}%&#39;)
  1. &lt;!DOCTYPE html&gt;
  2. &lt;html&gt;
  3. &lt;head&gt;
  4. &lt;meta charset=&quot;utf-8&quot;&gt;
  5. &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
  6. &lt;title&gt;Index&lt;/title&gt;
  7. &lt;/head&gt;
  8. &lt;body&gt;
  9. &lt;form name=&quot;upload-form&quot;&gt;
  10. &lt;div&gt;
  11. &lt;label for=&quot;file&quot;&gt;Choose a file:&lt;/label&gt;
  12. &lt;input type=&quot;file&quot; name=&quot;file&quot; id=&quot;file&quot; accept=&quot;application/pdf&quot; /&gt;
  13. &lt;/div&gt;
  14. &lt;div&gt;
  15. &lt;label for=&quot;desc&quot;&gt;Description:&lt;/label&gt;
  16. &lt;textarea name=&quot;desc&quot; id=&quot;desc&quot; rows=&quot;4&quot; cols=&quot;50&quot;&gt;&lt;/textarea&gt;
  17. &lt;/div&gt;
  18. &lt;div&gt;
  19. &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;
  20. &lt;/div&gt;
  21. &lt;/form&gt;
  22. &lt;script src=&quot;https://code.jquery.com/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt;
  23. &lt;script&gt;
  24. $(function() {
  25. $(&#39;form[name=&quot;upload-form&quot;]&#39;).submit(function(event) {
  26. event.preventDefault();
  27. const file = this[&#39;file&#39;].files[0];
  28. if (!file || file.type !== &#39;application/pdf&#39;) {
  29. alert(&#39;Please select a valid PDF file&#39;);
  30. return;
  31. }
  32. if (file.size &gt; 5000000) {
  33. alert(&#39;File size should not exceed 5 MB&#39;);
  34. return;
  35. }
  36. $.ajax({
  37. url: &#39;/api/analyze&#39;,
  38. type: &#39;post&#39;,
  39. data: new FormData(this),
  40. processData: false,
  41. contentType: false
  42. }).done(function(data) {
  43. alert(data.result);
  44. }).fail(function() {
  45. alert(&#39;Error during API call.&#39;);
  46. });
  47. })
  48. });
  49. &lt;/script&gt;
  50. &lt;/body&gt;
  51. &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:

确定