• Как заменить символ новой строки на тег?

    @Ganki Автор вопроса
    Coding
    Решил проблему следующим образом:

    Поправил модель базы данных и добавил метод

    # model.py
    
    class Post(db.Model):
        __tablename__ = 'posts'
        id = db.Column(db.Integer, primary_key=True)
        body = db.Column(db.Text)
        body_html = db.Column(db.Text)
    
        @staticmethod
        def on_changed_body(target, value, oldvalue, initiator):
            value = value.replace('\r\n', '<br>')
            value = value.replace('\r', '<br>')
            value = value.replace('\n', '<br>')
            target.body_html = bleach.clean(value, tags=['br'], strip=True)
    
    
    db.event.listen(Post.body, 'set', Post.on_changed_body)


    Вывод результата

    # index.html
    
    <html>
      <head>
        <title>WWW Site</title>
      </head>
      <body>
        {% for post in posts %}
            {% if post.body_html %}
              {{ post.body_html | safe }}
            {% else %}
              {{ post.body }}
            {% endif %}
        {% endfor %}
      </body>
    </html>


    Подсказали более простое решение:

    <div style="white-space: pre-wrap">{{ post.body }}</div>
    Ответ написан
    Комментировать
  • Какой нужен валидатор для проверки типа и размера в MultipleFileField?

    @Ganki Автор вопроса
    Coding
    Понял что такого валидатора нет, написал свой валидатор для проверки типа файла. Но не могу понять почему flask перехватывает эту ошибку раньше моего валидатора и выдает ошибку 413:

    # config.py
    
    import os
    
    basedir = os.path.abspath(os.path.dirname(__file__))
    
    class Config(object):
        SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
        SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
            'sqlite:///' + os.path.join(basedir, 'app.db')
        SQLALCHEMY_TRACK_MODIFICATIONS = False
        UPLOADED_IMAGES_DEST = basedir + '/app/static/shoes'
        UPLOADED_IMAGES_URL = 'http://localhost:5000/static/shoes/'
        MAX_CONTENT_LENGTH = 5 * 1024 * 1024
    
        @staticmethod
        def init_app(app):
            pass
    
    
    # __init.py__
    
    import os
    from flask import Flask, request, current_app
    from flask_sqlalchemy import SQLAlchemy
    from flask_migrate import Migrate
    from config import Config
    from flask_uploads import UploadSet, IMAGES, configure_uploads, patch_request_class
    
    
    db = SQLAlchemy()
    migrate = Migrate()
    images = UploadSet('shoes', IMAGES)
    
    
    def create_app(config_class=Config):
        app = Flask(__name__)
        app.config.from_object(config_class)
        configure_uploads(app, images)
        patch_request_class(app, app.config['MAX_CONTENT_LENGTH'])
    
        db.init_app(app)
        migrate.init_app(app, db)
        login.init_app(app)
    
        from app.errors import bp as errors_bp
        app.register_blueprint(errors_bp)
    
        from app.albums import bp as albums_bp
        app.register_blueprint(albums_bp, url_prefix='/albums')
    
        return app
    
    
    from app import models
    
    
    # routes.py
    
    from flask import render_template, flash, redirect, url_for, request, current_app
    from flask_login import current_user, login_required
    from app import db, images
    from app.albums import bp
    from app.albums.forms import NewAlbumForm, UploadImages
    from app.models import Album, SImage, User
    
    @bp.route('/<username>/<int:id>', methods=['GET', 'POST'])
    @login_required
    def view_album(username, id):
        user = User.query.filter_by(username=username).first_or_404()
        album = Album.query.filter_by(author=user, id=id).first_or_404()
        shoe_images = SImage.query.filter_by(album=album).all()
        form = UploadImages()
        if form.validate_on_submit():
            for file in form.images.data:
                filename = images.save(file, name=file.filename.lower())
                url = images.url(filename)
                up_shoe_img = SImage(image_filename=filename, image_url=url, 
                                        author_id=user.id, album_id=album.id)
                db.session.add(up_shoe_img)
                db.session.commit()
            flash('Image uploaded!')
            return redirect(url_for('albums.view_album', 
                                    username=current_user.username, id=album.id))
    
    
    
    # forms.py
    
    from flask_wtf import FlaskForm
    from wtforms import SubmitField, MultipleFileField
    from wtforms.validators import Required, ValidationError
    from app import images
    
    
    class UploadImages(FlaskForm):
        images = MultipleFileField('Upload images', validators=[Required()])
        submit = SubmitField('Upload')
    
        def validate_images(self, images):
            for file in images.data:
                extension = file.filename.lower().split('.')[1]
                if extension not in images.extensions:
                    raise ValidationError('Images only!')
    Ответ написан