Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何向Flask视图公开WTForms自定义验证函数变量?_Python_Python 3.x_Flask_Wtforms_Flask Wtforms - Fatal编程技术网

Python 如何向Flask视图公开WTForms自定义验证函数变量?

Python 如何向Flask视图公开WTForms自定义验证函数变量?,python,python-3.x,flask,wtforms,flask-wtforms,Python,Python 3.x,Flask,Wtforms,Flask Wtforms,我有一个WTForms自定义验证函数,它返回一个包含哈希的变量: def dupe_check(self, field): """ Check for duplicate images. """ def get_hash(): """ Get hash of image. """ f = field.data img = Image.open(f) imghash =

我有一个WTForms自定义验证函数,它返回一个包含哈希的变量:

def dupe_check(self, field):
    """
    Check for duplicate images.
    """
    def get_hash():
        """
        Get hash of image.
        """
        f = field.data
        img = Image.open(f)
        imghash = imagehash.dhash(img)
        f.seek(0) 
        return imghash
    imghash = str(get_hash())
    hashcheck = str(Sights.query.filter(Sights.image_hash == imghash).first())
    if hashcheck == imghash:
        raise ValidationError('Duplicate image detected!')

class AddImageForm(FlaskForm):
    sights_image = FileField('image', validators=[FileRequired(), FileAllowed(images, 'Images only!'), dupe_check])
将位于
forms.py
中的
imghash
变量公开到位于
views.py
中的烧瓶视图的最佳方法是什么

imghash
是否应进入WT表格?我应该创建一个会话变量吗?我是否应该将
dupe\u check
函数转换为类


我的目标是在Flask view期间将哈希写入DB,但不必重新生成哈希,因为它已在验证期间创建。

在这种情况下,您可以将函数
get\u hash()
转换为form类的方法:

class AddImageForm(FlaskForm):
    sights_image = FileField('image', validators=[...])

    def get_hash(self):
        f = self.sights_image.data
        img = Image.open(f)
        imghash = imagehash.dhash(img)
        f.seek(0) 
        return imghash
然后,在view函数中,您可以简单地使用表单调用它,例如:

from flask import request

@app.route('/', methods=['GET', 'POST'])
def test():
    form = AddImageForm()
    if request.method == 'POST':
        hash = form.get_hash()

在这种情况下,您可以将函数
get\u hash()
转换为form类的方法:

class AddImageForm(FlaskForm):
    sights_image = FileField('image', validators=[...])

    def get_hash(self):
        f = self.sights_image.data
        img = Image.open(f)
        imghash = imagehash.dhash(img)
        f.seek(0) 
        return imghash
然后,在view函数中,您可以简单地使用表单调用它,例如:

from flask import request

@app.route('/', methods=['GET', 'POST'])
def test():
    form = AddImageForm()
    if request.method == 'POST':
        hash = form.get_hash()
在您的
重复检查(self,field)
self
是表单实例,因此您可以将计算出的哈希值存储在表单中,并在以后的处理中使用它

这里是一个自包含的示例,请注意,我创建了一个类验证器,而不是使用一个简单的方法

from flask import Flask, request, flash, render_template_string, redirect
from flask_wtf import FlaskForm
from wtforms import ValidationError, StringField

app = Flask(__name__)

app.config['SECRET_KEY'] = '0123456789'


def get_hash(data):
    # Use data to compute hash
    image_hash = 1000000
    return image_hash


class HashValidator(object):
    def __init__(self, message=None):
        if not message:
            message = u'Duplicate image detected!'
        self.message = message

    def __call__(self, form, field):
        # Pass field data to hash function
        _img_hash = get_hash(field.data)
        # Store the hash in the form
        form.imghash = _img_hash
        # calculate if existing hash exists
        # hashcheck = str(Sights.query.filter(Sights.image_hash == _img_hash).first())
        hashcheck = 1000000
        if hashcheck == _img_hash:
            raise ValidationError(self.message)


class AddImageForm(FlaskForm):
    # sights_image = FileField('image', validators=[HashValidator()])
    # Use an Stringfield to make the sample easier
    sights_image = StringField('image', validators=[HashValidator()])


_template = '''
    {% with messages = get_flashed_messages() %}
      {% if messages %}
        <ul class=flashes>
        {% for message in messages %}
          <li>{{ message }}</li>
        {% endfor %}
        </ul>
      {% endif %}
    {% endwith %}
    <form action="/" method="POST">
        {{form.csrf_token}}
        {{form.sights_image}}
        {% if form.sights_image.errors %}
            <ul>{% for error in form.sights_image.errors %}<li>{{ error }}</li>{% endfor %}</ul>
        {% endif %}        
        <button type='submit'>Submit</button>
    </form>
'''


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        _image_form = AddImageForm()
        if _image_form.validate_on_submit():
            flash("Validated: get_hash returned {}".format(_image_form.imghash))
            return redirect('/')
        else:
            # didn't validate template will show error
            flash("Error. get_hash returned {}".format(_image_form.imghash))
            return render_template_string(_template, form=_image_form)
    else:
        _image_form = AddImageForm()
        return render_template_string(_template, form=_image_form)


if __name__ == '__main__':
    app.run(port=9876, debug=True)
从烧瓶导入烧瓶、请求、闪存、呈现模板字符串、重定向
来自flask_wtf进口FlaskForm
从wtforms导入ValidationError,StringField
app=烧瓶(名称)
app.config['SECRET_KEY']='0123456789'
def get_散列(数据):
#使用数据计算散列
图像\u散列=1000000
返回图像散列
类HashValidator(对象):
定义初始化(self,message=None):
如果没有,请发送消息:
message=u'检测到重复图像!'
self.message=消息
定义调用(自身、表单、字段):
#将字段数据传递给哈希函数
_img\u hash=get\u hash(field.data)
#将散列存储在表单中
form.imghash=\u img\u散列
#计算是否存在现有哈希
#hashcheck=str(Sights.query.filter(Sights.image\u hash==\u img\u hash.first())
hashcheck=1000000
如果hashcheck==\u img\u hash:
引发验证错误(self.message)
类别AddImageForm(烧瓶形式):
#sights\u image=FileField('image',validator=[HashValidator()]))
#使用Stringfield可以简化示例
sights\u image=StringField('image',validator=[HashValidator()]))
_模板=“”
{%with messages=get_flashed_messages()%}
{%if消息%}

{消息%中的消息为%s}
  • {{message}}
  • {%endfor%} {%endif%} {%endwith%} {form.csrf_token} {{form.sights_image} {%if form.sights\u image.errors%}
      {%for form.sights\u image.errors%}
    • {{{error}
    • {%endfor%}
    {%endif%} 提交 ''' @app.route('/',方法=['GET','POST']) def index(): 如果request.method==“POST”: _图像形式=AddImageForm() 如果_image_form.validate_on_submit(): flash(“Validated:get_hash returned{}”.format(_image_form.imghash)) 返回重定向(“/”) 其他: #未验证模板将显示错误 flash(“Error.get_hash returned{}”.format(_image_form.imghash)) 返回渲染模板字符串(\u模板,形式=\u图像\u形式) 其他: _图像形式=AddImageForm() 返回渲染模板字符串(\u模板,形式=\u图像\u形式) 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': 运行(端口=9876,调试=True)
    在您的
    重复检查(self,field)
    self
    是表单实例,因此您可以将计算出的哈希值存储在表单中,并在以后的处理中使用它

    这里是一个自包含的示例,请注意,我创建了一个类验证器,而不是使用一个简单的方法

    from flask import Flask, request, flash, render_template_string, redirect
    from flask_wtf import FlaskForm
    from wtforms import ValidationError, StringField
    
    app = Flask(__name__)
    
    app.config['SECRET_KEY'] = '0123456789'
    
    
    def get_hash(data):
        # Use data to compute hash
        image_hash = 1000000
        return image_hash
    
    
    class HashValidator(object):
        def __init__(self, message=None):
            if not message:
                message = u'Duplicate image detected!'
            self.message = message
    
        def __call__(self, form, field):
            # Pass field data to hash function
            _img_hash = get_hash(field.data)
            # Store the hash in the form
            form.imghash = _img_hash
            # calculate if existing hash exists
            # hashcheck = str(Sights.query.filter(Sights.image_hash == _img_hash).first())
            hashcheck = 1000000
            if hashcheck == _img_hash:
                raise ValidationError(self.message)
    
    
    class AddImageForm(FlaskForm):
        # sights_image = FileField('image', validators=[HashValidator()])
        # Use an Stringfield to make the sample easier
        sights_image = StringField('image', validators=[HashValidator()])
    
    
    _template = '''
        {% with messages = get_flashed_messages() %}
          {% if messages %}
            <ul class=flashes>
            {% for message in messages %}
              <li>{{ message }}</li>
            {% endfor %}
            </ul>
          {% endif %}
        {% endwith %}
        <form action="/" method="POST">
            {{form.csrf_token}}
            {{form.sights_image}}
            {% if form.sights_image.errors %}
                <ul>{% for error in form.sights_image.errors %}<li>{{ error }}</li>{% endfor %}</ul>
            {% endif %}        
            <button type='submit'>Submit</button>
        </form>
    '''
    
    
    @app.route('/', methods=['GET', 'POST'])
    def index():
        if request.method == 'POST':
            _image_form = AddImageForm()
            if _image_form.validate_on_submit():
                flash("Validated: get_hash returned {}".format(_image_form.imghash))
                return redirect('/')
            else:
                # didn't validate template will show error
                flash("Error. get_hash returned {}".format(_image_form.imghash))
                return render_template_string(_template, form=_image_form)
        else:
            _image_form = AddImageForm()
            return render_template_string(_template, form=_image_form)
    
    
    if __name__ == '__main__':
        app.run(port=9876, debug=True)
    
    从烧瓶导入烧瓶、请求、闪存、呈现模板字符串、重定向
    来自flask_wtf进口FlaskForm
    从wtforms导入ValidationError,StringField
    app=烧瓶(名称)
    app.config['SECRET_KEY']='0123456789'
    def get_散列(数据):
    #使用数据计算散列
    图像\u散列=1000000
    返回图像散列
    类HashValidator(对象):
    定义初始化(self,message=None):
    如果没有,请发送消息:
    message=u'检测到重复图像!'
    self.message=消息
    定义调用(自身、表单、字段):
    #将字段数据传递给哈希函数
    _img\u hash=get\u hash(field.data)
    #将散列存储在表单中
    form.imghash=\u img\u散列
    #计算是否存在现有哈希
    #hashcheck=str(Sights.query.filter(Sights.image\u hash==\u img\u hash.first())
    hashcheck=1000000
    如果hashcheck==\u img\u hash:
    引发验证错误(self.message)
    类别AddImageForm(烧瓶形式):
    #sights\u image=FileField('image',validator=[HashValidator()]))
    #使用Stringfield可以简化示例
    sights\u image=StringField('image',validator=[HashValidator()]))
    _模板=“”
    {%with messages=get_flashed_messages()%}
    {%if消息%}
    
    {消息%中的消息为%s}
    
  • {{message}}
  • {%endfor%} {%endif%} {%endwith%} {form.csrf_token} {{form.sights_image} {%if form.sights\u image.errors%}
      {%for form.sights\u image.errors%}
    • {{{error}
    • {%endfor%}
    {%endif%} 提交 ''' @app.route('/',方法=['GET','POST']) def index(): 如果request.method==“POST”: _图像形式=AddImageForm() 如果_image_form.validate_on_submit(): flash(“Validated:get_hash returned{}”.format(_image_form.imghash)) 返回重定向(“/”) 其他: #未验证模板将显示错误 flash(“Error.get_hash returned{}.”格式