Skip to content

Instantly share code, notes, and snippets.

@henryfjordan
Last active January 5, 2021 15:20
Show Gist options
  • Save henryfjordan/f24a9ac40ce59159e555 to your computer and use it in GitHub Desktop.
Save henryfjordan/f24a9ac40ce59159e555 to your computer and use it in GitHub Desktop.
Python Contact Form Handler
from flask import Flask, request
import httplib, urllib
import psycopg2
#Helper Function to send a push notification using Pushover
def _pushover(name, email, message):
http_connection = httplib.HTTPSConnection("api.pushover.net:443")
http_connection.request("POST", "/1/messages.json",
urllib.urlencode({
"token": "INSERT_TOKEN_HERE",
"user": "INSERT_USER_HERE",
"message": name + " -- " + email + " -- " + message
}), { "Content-type": "application/x-www-form-urlencoded" })
http_connection.getresponse()
return
application = Flask(__name__)
@application.route('/api/')
def index():
return "Hi there, I'm not sure how you got here but you should go <a href=\"http://henryfjordan.duckdns.org\">back</a>."
@application.route('/api/contact/', methods = ['POST'])
def contact():
if request.method == 'POST':
_pushover(request.form.get('name'), request.form.get('email'), request.form.get('message'))
try:
db_connection = psycopg2.connect(database='postgres', user='postgres')
cursor = db_connection.cursor()
cursor.execute("INSERT INTO messages (name, email, message) VALUES (%s, %s, %s);", (request.form.get('name'), request.form.get('email'), request.form.get('message')))
db_connection.commit()
cursor.close()
db_connection.close()
except psycopg2.DatabaseError, e:
print "database error"
return "Something broke in the DB"
return "Thank you for your message, <b>" + request.form.get('name') + "</b>. I'll get back to you as soon as I can."
if __name__ == "__main__":
application.run(host='0.0.0.0', port=8081)
#!/sbin/runscript
# Copyright 1999-2015 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: $
PYTHON=/usr/bin/python
PIDFILE=/var/run/website.pid
SCRIPT=/home/henry/website/contact.py
depend() {
need net
need postgresql
}
start() {
ebegin "Starting website"
start-stop-daemon --background --start -m --pidfile ${PIDFILE} --exec ${PYTHON} ${SCRIPT}
eend $?
}
stop() {
ebegin "Stopping website"
start-stop-daemon --stop --pidfile ${PIDFILE}
eend $?
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment