pythonhtmlflask

Flask together with `POST` method doesn't yield any output from slovnik.seznam.cz


I have a flask structure as below:

root@k2:/mnt/c/Users/k2/myenvGPU32/myflaskapp# ls -lR . .: total 8
-rwxrwxrwx 1 root root  128 Jun 10 10:59 T.py
-rwxrwxrwx 1 root root  128 Jun 10 10:55 T.py~
-rwxrwxrwx 1 root root  926 Jun 10 20:17 app.py
-rwxrwxrwx 1 root root 2969 Jun 10 19:57 app.py~ drwxrwxrwx 1 root root 4096 Jun 10 20:17 templates

./templates: total 12
-rwxrwxrwx 1 root root 1283 Jun 10 20:17 index.html
-rwxrwxrwx 1 root root 6104 Jun 10 19:58 index.html~

(but the button Translate doesn't produce any results) with these files app.py:

from flask import Flask, render_template, request, jsonify
import requests
from bs4 import BeautifulSoup

app = Flask(__name__)

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

@app.route('/translate', methods=['POST'])
def translate():
    term = request.json.get('term')
    url = f'https://slovnik.seznam.cz/preklad/anglicky_cesky/{term}'
    response = requests.get(url)
    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')
        translation_div = soup.find('div', class_='entry')
        if translation_div:
            translation = translation_div.text.strip()
            return jsonify(success=True, translation=translation)
        else:
            return jsonify(success=False, error='Translation not found')
    return jsonify(success=False, error='Translation service unavailable')

if __name__ == '__main__':
    app.run(port=5000, debug=True)

and

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Translate</title>
    <script>
        function translate() {
            const term = document.getElementById('translateTerm').value;
            fetch('/translate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ term })
            })
            .then(response => response.json())
            .then(data => {
                const translationDiv = document.getElementById('translation');
                if (data.success) {
                    translationDiv.textContent = data.translation;
                    translationDiv.style.display = 'block';
                } else {
                    translationDiv.textContent = data.error;
                    translationDiv.style.display = 'block';
                }
            });
        }
    </script>
</head>
<body>
    <h1>Translate</h1>
    <textarea id="translateTerm" placeholder="Enter term to translate"></textarea>
    <button onclick="translate()">Translate</button>
    <div id="translation" style="display:none;"></div>
</body>
</html>

EDIT

C:\Users\k2\myenvGPU32\myflaskapp>python app.py

EDIT2

enter image description here

EDIT3

enter image description here

EDIT4 enter image description here

EDIT5 A bit better but still the output doesn't go to browser but to the Anaconda prompt:

enter image description here

EDIT6 works quite good but not 100% perfect; 2nd snippet below is our target but I'm getting only first one

enter image description here

enter image description here

EDIT7: still unstructured enter image description here

EDIT8: too many spaces in between rowsenter image description here


Solution

  • In the fetch part, try changing to:

    ...
        <script>
            function translate() {
                const term = document.getElementById('translateTerm').value;
                fetch('/translate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({term: term})
                })
                .then(response => response.json())
                .then(data => {
                    const translationDiv = document.getElementById('translation');
                    if (data.success) {
                        translationDiv.innerHTML = data.translation;
                        translationDiv.style.display = 'block';
                    } else {
                        translationDiv.innerHTML= data.translation;
                        translationDiv.style.display = 'block';
                    }
                });
            }
        </script>
    ...
    

    Python:

    @app.route('/translate', methods=['POST'])
    def translate():
        term = request.json.get('term')
        url = f'https://slovnik.seznam.cz/preklad/anglicky_cesky/{term}'
        response = requests.get(url)
        if response.status_code == 200:
            if response:
                translation = response.text
                return jsonify(success=True, translation=translation)
            else:
                return jsonify(success=False, error='Translation not found')
        return jsonify(success=False, error='Translation service unavailable')