【问题标题】:How to fix: jinja2.exceptions.UndefinedError: 'csrf_token' is undefined如何修复:jinja2.exceptions.UndefinedError: 'csrf_token' 未定义
【发布时间】:2019-10-07 11:02:42
【问题描述】:

我在 Python 中运行代码(我发现它已经从教程构建)。我想在网络应用程序上部署模型(使用 Flask)

当我运行我的应用程序时,我收到以下错误,请参阅下面的回溯:

jinja2.exceptions.UndefinedError: 'csrf_token' 未定义

追溯:

  File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/jinja2/environment.py", line 780, in handle_exception

reraise(exc_type, exc_value, tb)

  File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/jinja2/_compat.py", line 37, in reraise

    raise value.with_traceback(tb)

  File "/Users/usersname/Desktop/flaskSaaS-master/app/templates/uploaded.html", line 1, in top-level template code

    {% extends "layout.html" %}

  File "/Users/usersname/Desktop/flaskSaaS-master/app/templates/layout.html", line 94, in top-level template code

    {% block content %}{% endblock %}

  File "/Users/usersname/Desktop/flaskSaaS-master/app/templates/uploaded.html", line 8, in block "content"

    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>

jinja2.exceptions.UndefinedError: 'csrf_token' is undefined

127.0.0.1 - - [06/Oct/2019 19:57:32] "GET /upload.php?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -

127.0.0.1 - - [06/Oct/2019 19:57:32] "GET /upload.php?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -

127.0.0.1 - - [06/Oct/2019 19:57:32] "GET /upload.php?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200
-

127.0.0.1 - - [06/Oct/2019 19:57:32] "GET /upload.php?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200
-

127.0.0.1 - - [06/Oct/2019 19:57:32] "GET /upload.php?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200
-

127.0.0.1 - - [06/Oct/2019 19:57:32] "GET /upload.php?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -

我无法弄清楚为什么索引页面现在无法加载。

这里是有问题的 uploaded.html 页面的代码,已经由其他人构建。

{% extends "layout.html" %}

{% block head %}
    {{ super() }}
{% endblock %}

{% block content %}

<!DOCTYPE html>
<html>
<head>
    <body>
    <img src="http://diagnijmegen.nl/images/b/bd/Xray.jpg" alt="Italian Trulli">

                    <!-- {{ predictions }} -->
                    <style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>
</head>
<body>

<h2>Results</h2>

<table>
  <tr>
    <th>Disease</th>
    <th>Percent Likelihood</th>
  </tr>
  <tr>
    <td>Pneumonia</td>
    <td>98%</td>
  </tr>
  <tr>
    <td>Fibrosis</td>
    <td>43%</td>
  </tr>
</table>

</body>
</html>
    <title>Index</title>
</head>
<body>
</body>
</html>


{% endblock %}

这是视图的代码(ma​​in.py):

from flask import render_template, jsonify, Flask, redirect, url_for, request
from app import app
import random
import os
from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np


@app.route('/')

#disease_list = ['Atelectasis', 'Consolidation', 'Infiltration', 'Pneumothorax', 'Edema', 'Emphysema', \
                  # 'Fibrosis', 'Effusion', 'Pneumonia', 'Pleural_Thickening', 'Cardiomegaly', 'Nodule', 'Mass', \
                  # 'Hernia']

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

@app.route('/uploaded', methods = ['GET', 'POST'])
def upload_file():
   if request.method == 'POST':
      f = request.files['file']
      path = os.path.join(app.config['UPLOAD_FOLDER'], f.filename)
      model= ResNet50(weights='imagenet')
      img = image.load_img(path, target_size=(224,224))
      x = image.img_to_array(img)
      x = np.expand_dims(x, axis=0)
      x = preprocess_input(x)
      preds = model.predict(x)
      preds_decoded = decode_predictions(preds, top=3)[0] 
      print(decode_predictions(preds, top=3)[0])
      f.save(path)
      return render_template('uploaded.html', title='Success', predictions=preds_decoded, user_image=f.filename)


@app.route('/index')
def index():
    return render_template('index.html', title='Home')

@app.route('/map')
def map():
    return render_template('map.html', title='Map')


@app.route('/map/refresh', methods=['POST'])
def map_refresh():
    points = [(random.uniform(48.8434100, 48.8634100),
               random.uniform(2.3388000, 2.3588000))
              for _ in range(random.randint(2, 9))]
    return jsonify({'points': points})


@app.route('/contact')
def contact():
    return render_template('contact.html', title='Contact')

我已多次阅读该教程,但我不知道为什么它不起作用。 显然错误在 uplodaded.html 文件上,但我不知道我必须在哪里修改代码。如果我更改某些内容,或者我使用其他练习中的其他 .html 作为参考,我会得到更多(和不同的)错误。

我正在发布“原始”代码,即教程中使用的代码。他们向我们展示了它的工作原理。提前感谢您的帮助。

【问题讨论】:

    标签: python html flask


    【解决方案1】:

    启用模块:

    from flask_wtf.csrf import CsrfProtect
    CsrfProtect(app)
    

    documentation 中了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-24
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-11
      相关资源
      最近更新 更多