【问题标题】:Flask - Not allowed to load local resource - image issueFlask - 不允许加载本地资源 - 图像问题
【发布时间】:2020-07-20 17:10:40
【问题描述】:

我有以下代码为我拥有的图像生成正确的文件路径,它还在浏览器中生成的 HTML 中正确填充它们,但我的浏览器拒绝加载说,它是“不允许加载本地资源” .

这是我的代码: Python3:

@app.route("/", methods=["GET", "POST"])
def main():
    conn = sqlite3.connect('mydb.db')
    c = conn.cursor()
    
    #Defines what to do when the request is GET
    if request.method == 'GET':
        allPosts = c.execute('SELECT * FROM posts ORDER BY time DESC')
        return render_template('index.html', allPosts = allPosts)

    #Defines what to do when the request is POST
    if request.method == 'POST':
        pass

@app.route("/upload", methods=["GET", "POST"])
def upload():
    conn = sqlite3.connect('mydb.db')
    c = conn.cursor()
    #Define what to do if method is GET
    if request.method == 'GET':
        return render_template('upload.html')
#Define what to do if method is POST
    if request.method == 'POST':
        #Get the data from the form
        #image = request.files['image']
        username = request.form['username']
        title = request.form['nadpis']
        post = request.form['prispevok']
        
        #Get a random ID of post
        randomIdOfPost = random.randrange(99999999)
        
        #Get current timestamp
        actualTime = datetime.now()
        actualTimeForInsertingIntoDB = str(actualTime.day) + '.' + str(actualTime.month) + '.' + str(actualTime.year) + ' ' + str(actualTime.hour) + ':' + str(actualTime.minute) + ':' + str(actualTime.second)
        
        if 'image' not in request.files:
            flash('No image part')
            return redirect('/upload', code=302)
        image = request.files['image']
        # if user does not select file, browser also
        # submit an empty part without filename
        if image.filename == '':
            flash('No selected image')
            return redirect('/upload', code=302)
        if image and allowed_file(image.filename):
            filename = secure_filename(image.filename)
            filename = str(randomIdOfPost) + '_' + filename
            image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            imageName = str(filename)
        
        
        #Save the post into DB
        data = [(randomIdOfPost, actualTimeForInsertingIntoDB, username, title, post, imageName)]
        c.executemany('INSERT INTO posts VALUES (?,?,?,?,?,?)', data)
        conn.commit()
      
        return redirect('/', code=302)

HTML:

{% for row in allPosts %}
    <div class="container-fluid" align="center">
    <span class="badge badge-info">#{{ row[0] }} / Pridané dňa {{ row[1] }}<br>používateľom {{ row[2] }}</span>
    <h6>{{ row[3] }}</h6>
    <p>{{ row[4] }}</p>
    <img src="{{ url_for('static', filename='{{ row[5] }}') }}" alt="my text">
</div>
<p>&nbsp;</p>   
{% endfor %}

在我的 Python3 代码之上,我还有:

UPLOAD_FOLDER = os.getcwd() + r'\static'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__, template_folder=os.getcwd(), static_folder=os.getcwd() + r'\static')
#Set the route to the static folder (folder containing css stylesheet)
app._static_folder = os. getcwd() + "\\css"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

我唯一的问题是,我的浏览器不允许我显示某人上传的图片

非常感谢所有帮助。

编辑 1:

{% for row in allPosts %}
    <div class="container-fluid" align="center">
    <span class="badge badge-info">#{{ row[0] }} / Pridané dňa {{ row[1] }}<br>používateľom {{ row[2] }}</span>
    <h6>{{ row[3] }}</h6>
    <p>{{ row[4] }}</p>
    
    <!-- I tried both <img> tags below, none of them works.. -->
    <img src="{{ row[5] }}" alt="my text">
    <!-- <img src="{{ url_for('static', filename='{{ row[5] }}') }}" alt="my text"> -->
</div>
<p>&nbsp;</p>   
{% endfor %}

【问题讨论】:

  • 请发布完整的错误信息,包括行号
  • Flask 没有给出任何错误,只有在我的浏览器控制台中我才能看到它说:不允许加载本地资源。然后,在我的 标签所在的地方,只有一个“损坏的图像”是可见的......
  • 请给我看HTML源代码。尤其是 img 标签被渲染的部分。请把它放在问题的上面,正确格式化为代码
  • @J.G.我已经添加了使用 Jinja2 填充图像的 HTML 代码。它在我上面的问题中的 EDIT 1 之下。谢谢
  • 建议:因为看起来你在Windows上,所以不要使用` with file paths in your code. Use os.path.join`等。只。你可能不想这样做app._static_folder = os. getcwd() + "\\css"

标签: html python-3.x flask jinja2


【解决方案1】:

这个:

<img src="{{ url_for('static', filename='{{ row[5] }}') }}" alt="my text">

应该是:

<img src="{{ url_for('static', filename=row[5]) }}" alt="my text">

【讨论】:

  • 这成功了。我实际上将其更改为:&lt;img src="{{ url_for('static', filename='images/'+row[5]) }}" alt="my text"&gt;,它工作了谢谢!
【解决方案2】:

您确实需要在浏览器中查看源代码,以查看正在呈现的 img 路径。不要嵌套花括号。试试这个看看是不是路径问题:

<img src="/path/to/static/{{ row[5] }}" alt="my text">

您想取消嵌套变量,例如:

{{ url_for('static', filename=row[5]) }}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 2016-11-04
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    相关资源
    最近更新 更多