Skip to content

Instantly share code, notes, and snippets.

@LouisdeBruijn
Last active December 18, 2019 23:26
Show Gist options
  • Select an option

  • Save LouisdeBruijn/55870491e234f2178ea920be052dc6dc to your computer and use it in GitHub Desktop.

Select an option

Save LouisdeBruijn/55870491e234f2178ea920be052dc6dc to your computer and use it in GitHub Desktop.
/contact route in Flask app
# rendering contact.html template and making JSON response
from flask import Flask, render_template, jsonify
# using Flask-WTF CSRF protection for AJAX requests
from flask_wtf.csrf import CSRFProtect
# initializing app
app = Flask(__name__)
# protecting our app
csrf = CSRFProtect(app)
@app.route('/contact', methods=['GET', 'POST'])
def contact():
"""User can send e-mail via contact form"""
if request.method == 'POST':
"""User sent an email request"""
msg = Message("Feedback", recipients=[app.config['MAIL_USERNAME']])
msg.body = "You have received new feedback from {0} {1} <{2}>.\n\n {3}".format(
request.form['first-name'],
request.form['last-name'],
request.form['mail-address'],
request.form['comment-field'])
try:
mail.send(msg)
msg = "We will respond as soon as possible."
category = "success"
except Exception as err:
msg = str(err)
category = "danger"
resp = {'feedback': msg, 'category': category}
return make_response(jsonify(resp), 200)
elif request.method == 'GET':
"""User is viewing the page"""
return render_template('pages/contact.html')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment