Возможно ли иметь два разных действия / кнопки под одним маршрутом во Flask? - PullRequest
0 голосов
/ 16 октября 2019

Я пытаюсь создать простое веб-приложение, в котором пользователь загружает два документа и имеет два варианта действий с ними: найти лексические различия или семантические сходства. Кнопка «Различия» работает нормально, но я не могу заставить работать кнопку «Сходство», или даже, кажется, ее признают.

Я пытался возиться с утверждениями if, чтобы увидеть, будут ли какие-либо изменения иметь значение, но в настоящий момент я не вижу проблем с моей логикой. Тем не менее, я могу определенно ошибаться в этом

rout.py

#snippet of code with relevant function
@app.route("/uploading", methods=["GET","POST"])
def uploading():
    if request.method =="POST":
        file1 = request.files['file1']
        file2 = request.files['file2']
        if request.form['differences']:
            result = dif(file1.filename,file2.filename)
            item = serve_pil_image(result)
            return item
        if request.form['similarity']:
            doc = (file1.filename).read()
            doc = gensim.utils.simple_preprocess(doc)
            doc2 = (file2.filename).read()
            doc2 = gensim.utils.simple_preprocess(doc2)
            new_vector1 = model.infer_vector(doc)
            new_vector2 = model.infer_vector(doc2)
            dot = np.dot(new_vector1, new_vector2)
            norma = np.linalg.norm(new_vector1)
            normb = np.linalg.norm(new_vector2)
            cos = dot / (norma * normb)
            return 'The similarity score between file one and file two is: ', str(cos)

 return render_template('upload.html')

upload.html

<html>
    <head>
        <title>Simple file upload using Python Flask</title>
    </head>
    <body>
        <form action="{{ url_for('uploading') }}" method="post" enctype="multipart/form-data">
            Choose the first file: <input type="file" name="file1" value="file one"/><BR>
            Choose the second file: <input type="file" name="file2" value="file two"/><BR>
            <input type="submit" name="differences" value="Find Differences">
            <input type="submit" name="similarity" value="Similarity Score (Percentage)">
        </form>
</html>

edit

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 2463, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 2449, in wsgi_app
    response = self.handle_exception(e)
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1866, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.6/dist-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.6/dist-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/sozube/PycharmProjects/pdf-diff/app/routes.py", line 108, in uploading
    if request.form['differences']:
  File "/usr/local/lib/python3.6/dist-packages/werkzeug/datastructures.py", line 442, in __getitem__
    raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'differences'

Я получаю сообщение об ошибке werkzeug.exceptions.BadRequestKeyError, с KeyError: 'разности'

1 Ответ

0 голосов
/ 16 октября 2019

Вам нужно учесть, что один из двух ключей не будет присутствовать.

if request.form.get('differences'):
    # the body of if block here
if request.form.get('similarity'):
    # the body of if block here

или

if request.form.get('differences'):
    # the body of if block here
else:
    # the body of else block here
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...