Flask Web应用程序无法正确显示图像

时间:2016-07-14 17:59:47

标签: python html flask

我不知道为什么我的Flask应用程序在索引链接中显示图像但不显示在其他链接中。它在/index中正常工作,显示每个图像。但是,当打开/stream/posts/id链接应用不显示图片时,只显示文字。

Python代码

@app.route('/new_post', methods=['GET', 'POST'])
@login_required
def post():
    form = forms.PostForm()
    if form.validate_on_submit():
        filename = secure_filename(form.photo.data.filename)
        filePath=os.path.join(app.config['UPLOAD_FOLDER'], filename)

        form.photo.data.save(filePath)

        models.Post.create(user=g.user._get_current_object(),
                       content=form.content.data.strip(),
                       path = ("/uploads/"+ filename))

        flash("Message posted: Thanks!", "success")
        return redirect(url_for('index'))
    return render_template('post.html', form=form)

@app.route('/index')
@login_required
def index():
    stream = models.Post.select().limit(100)
    return render_template('stream.html', stream=stream)

@app.route('/stream')
@app.route('/stream/<username>')
def stream(username=None):
    template = 'stream.html'
    if username and username != current_user.username:
        try:
            user=models.User.select().where(models.User.username**username).get()
        except models.DoesNotExist:
            abort(404)
        else:
            stream = user.posts.limit(100)
    else:
        stream = current_user.get_stream().limit(100)
        user = current_user
    if username:
        template = 'user_stream.html'
    return render_template(template, stream=stream, user=user)

@app.route('/post/<int:post_id>')
def view_post(post_id):
    posts=models.Post.select().where(models.Post.id == post_id)
    if posts.count()==0:
        abort(404)
    return render_template('stream.html', stream=posts)

HTML代码

{% extends "layout.html" %}

{% block content %}
{% for post in stream %}
  <article>
    <h2>
      <a href="{{ url_for('stream', username=post.user.username) }}">
        {{ post.user.username }}
      </a>
    </h2>
    <i class="clock"></i>
    <time data-time="{{ post.timestamp }}" >
      {{ post.timestamp.strftime('%Y-%m-%d %H:%M:%S') }}
    </time>
    <a href="{{ url_for('view_post', post_id=post.id) }}" class="view">View</a>
    <div class="post">
      {{ post.content }}
    </div>
    <div class="image" >
        <a href="{{ url_for('view_post', post_id=post.id) }}" target="_blank"</a>
       <img src="{{ post.path }}" alt="" style="width:720px;height:720px;">
    </div>
  </article>
{% endfor %}
{% endblock %}

我做了与其他项目几乎相同的事情,但从未遇到过这类问题。可能是我做错了什么,但我找不到。

发布模型

class Post(Model):
    timestamp = DateTimeField(default=datetime.datetime.now)

    user = ForeignKeyField(
        rel_model=User, 
        related_name='posts'
    )
    content = CharField(max_length=120)
    path = CharField()

    class Meta:
        database = DATABASE
        order_by = ('-timestamp',)

0 个答案:

没有答案