-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
162 lines (133 loc) · 5.36 KB
/
app.py
File metadata and controls
162 lines (133 loc) · 5.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#!/usr/bin/env python3
from flask import Flask, render_template, request, redirect, url_for, make_response
from markupsafe import escape
import pymongo
import datetime
from bson.objectid import ObjectId
import os
import subprocess
# instantiate the app
app = Flask(__name__)
# load credentials and configuration options from .env file
# if you do not yet have a file named .env, make one based on the template in env.example
import credentials
config = credentials.get()
# turn on debugging if in development mode
if config['FLASK_ENV'] == 'development':
# turn on debugging, if in development
app.debug = True # debug mnode
# make one persistent connection to the database
connection = pymongo.MongoClient(config['MONGO_HOST'], 27017,
username=config['MONGO_USER'],
password=config['MONGO_PASSWORD'],
authSource=config['MONGO_DBNAME'])
db = connection[config['MONGO_DBNAME']] # store a reference to the database
# set up the routes
@app.route('/')
def home():
"""
Route for the home page
"""
return render_template('index.html')
@app.route('/read')
def read():
"""
Route for GET requests to the read page.
Displays some information for the user with links to other pages.
"""
docs = db.reviews.find({}).sort("created_at", -1) # sort in descending order of created_at timestamp
return render_template('read.html', docs=docs) # render the read template
@app.route('/create')
def create():
"""
Route for GET requests to the create page.
Displays a form users can fill out to create a new document.
"""
return render_template('create.html') # render the create template
@app.route('/create', methods=['POST'])
def create_post():
"""
Route for POST requests to the create page.
Accepts the form submission data for a new document and saves the document to the database.
"""
name = request.form['fname']
school = request.form['fschool']
rating = request.form['frating']
message = request.form['fmessage']
# create a new document with the data the user entered
doc = {
"name": name,
"school": school,
"rating": rating,
"message": message,
"created_at": datetime.datetime.utcnow()
}
db.reviews.insert_one(doc) # insert a new document
return redirect(url_for('read')) # tell the browser to make a request for the /read route
@app.route('/edit/<mongoid>')
def edit(mongoid):
"""
Route for GET requests to the edit page.
Displays a form users can fill out to edit an existing record.
"""
doc = db.reviews.find_one({"_id": ObjectId(mongoid)})
return render_template('edit.html', mongoid=mongoid, doc=doc) # render the edit template
@app.route('/edit/<mongoid>', methods=['POST'])
def edit_post(mongoid):
"""
Route for POST requests to the edit page.
Accepts the form submission data for the specified document and updates the document in the database.
"""
name = request.form['fname']
school = request.form['fschool']
rating = request.form['frating']
message = request.form['fmessage']
doc = {
# "_id": ObjectId(mongoid),
"name": name,
"school": school,
"rating": rating,
"message": message,
"created_at": datetime.datetime.utcnow()
}
db.reviews.update_one(
{"_id": ObjectId(mongoid)}, # match criteria
{ "$set": doc }
)
return redirect(url_for('read')) # tell the browser to make a request for the /read route
@app.route('/delete/<mongoid>')
def delete(mongoid):
"""
Route for GET requests to the delete page.
Deletes the specified record from the database, and then redirects the browser to the read page.
"""
db.reviews.delete_one({"_id": ObjectId(mongoid)})
return redirect(url_for('read')) # tell the web browser to make a request for the /read route.
@app.route('/webhook', methods=['POST'])
def webhook():
"""
GitHub can be configured such that each time a push is made to a repository, GitHub will make a request to a particular web URL... this is called a webhook.
This function is set up such that if the /webhook route is requested, Python will execute a git pull command from the command line to update this app's codebase.
You will need to configure your own repository to have a webhook that requests this route in GitHub's settings.
Note that this webhook does do any verification that the request is coming from GitHub... this should be added in a production environment.
"""
# run a git pull command
process = subprocess.Popen(["git", "pull"], stdout=subprocess.PIPE)
pull_output = process.communicate()[0]
# pull_output = str(pull_output).strip() # remove whitespace
process = subprocess.Popen(["chmod", "a+x", "flask.cgi"], stdout=subprocess.PIPE)
chmod_output = process.communicate()[0]
# send a success response
response = make_response('output: {}'.format(pull_output), 200)
response.mimetype = "text/plain"
return response
@app.errorhandler(Exception)
def handle_error(e):
"""
Output any errors - good for debugging.
"""
return render_template('error.html', error=e) # render the edit template
if __name__ == "__main__":
#import logging
#logging.basicConfig(filename='/home/ak8257/error.log',level=logging.DEBUG)
app.run(debug = True)