好的,我已经为这个问题苦苦挣扎了两天。当我在浏览器中手动在表单中发布数据时,一切正常,并且我收到了显示为“谢谢...”的提示消息。在测试我的Flask应用程序时,此测试未通过,因为在我的Flask表单上发送发布请求时收到400错误请求错误。需要明确的是,我使用的是Flask-Mail和WTForms表单,并且我的应用程序已泊坞窗化并运行redis和celery。我对这些东西还是有点陌生,所以如果我的问题还不够清楚,请好心告诉我是否应该提供更详细的信息。谢谢,这是相关的代码,以及使用py.test测试时显示的错误。很抱歉,我仍然不允许我在StackOverflow上发布图片。
错误代码: Pytest Assertion Error
contact / forms.py:
from flask_wtf import FlaskForm
from wtforms import TextAreaField, StringField
from wtforms.validators import DataRequired, Length, Email
class ContactForm(FlaskForm):
email = StringField("What's your e-mail address?",
[Email(), DataRequired(), Length(3, 254)])
message = TextAreaField("What's your question or issue?",
[DataRequired(), Length(1, 8192)])
contact / views.py:
from flask import (
Blueprint,
flash,
redirect,
request,
url_for,
render_template)
from flexio.blueprints.contact.forms import ContactForm
contact = Blueprint('contact', __name__, template_folder='templates')
@contact.route('/contact', methods=['GET', 'POST'])
def index():
form = ContactForm()
if form.validate_on_submit():
# This prevents circular imports.
from flexio.blueprints.contact.tasks import deliver_contact_email
deliver_contact_email(request.form.get('email'),
request.form.get('message'))
flash('Thanks, expect a response shortly.', 'success')
return redirect(url_for('contact.index'))
return render_template('contact/index.html', form=form)
contact / tasks.py:
from lib.flask_mailplus import send_template_message
from flexio.app import create_celery_app
celery = create_celery_app()
@celery.task()
def deliver_contact_email(email, message):
"""
Send a contact e-mail.
:param email: E-mail address of the visitor
:type user_id: str
:param message: E-mail message
:type user_id: str
:return: None
"""
ctx = {'email': email, 'message': message}
send_template_message(subject='[Flexio] Contact',
sender=email,
recipients=[celery.conf.get('MAIL_USERNAME')],
reply_to=email,
template='contact/mail/index', ctx=ctx)
return None
lib / tests.py:
def assert_status_with_message(status_code=200, response=None, message=None):
"""
Check to see if a message is contained within a response.
:param status_code: Status code that defaults to 200
:type status_code: int
:param response: Flask response
:type response: str
:param message: String to check for
:type message: str
:return: None
"""
assert response.status_code == status_code
assert message in str(response.data)
测试/联系人/test_views.py:
from flask import url_for
from lib.tests import assert_status_with_message
class TestContact(object):
def test_contact_page(self, client):
""" Contact page should respond with a success 200. """
response = client.get(url_for('contact.index'))
assert response.status_code == 200
def test_contact_form(self, client):
""" Contact form should redirect with a message. """
form = {
'email': 'foo@bar.com',
'message': 'Test message from Flexio.'
}
response = client.post(url_for('contact.index'), data=form,
follow_redirects=True)
assert_status_with_message(200, response, 'Thanks')
答案 0 :(得分:1)
您的浏览器将通过GET
请求 first 来请求表单,因此被授予CSRF token作为cookie和表单中的隐藏表单元素。然后,当您提交表单时,CSRF保护就会通过。
您的测试既不会发出GET
请求,也不会使用这种请求所产生的表单中的表单字段,因此您的POST
请求既缺少cookie,也没有隐藏字段。
在测试中,您可以通过将WTF_CSRF_ENABLED
参数设置为False
来禁用CSRF保护:
app.config['WTF_CSRF_ENABLED'] = False