|
8 | 8 | # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION |
9 | 9 | # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
10 | 10 |
|
11 | | -import os |
12 | 11 | import json |
13 | | -import cgi |
14 | | -from BaseHTTPServer import HTTPServer |
15 | | -from SimpleHTTPServer import SimpleHTTPRequestHandler |
| 12 | +from flask import Flask, Response, request |
16 | 13 |
|
17 | | -PUBLIC_PATH = "public" |
| 14 | +app = Flask(__name__, static_url_path='', static_folder='public') |
| 15 | +app.add_url_rule('/', 'root', lambda: app.send_static_file('index.html')) |
18 | 16 |
|
19 | | -file = open('_comments.json', 'r+') |
20 | | -comments = json.loads(file.read()) |
21 | | -file.close() |
| 17 | +@app.route('/comments.json', methods=['GET', 'POST']) |
| 18 | +def comments_handler(): |
22 | 19 |
|
23 | | -def sendJSON(res): |
24 | | - res.send_response(200) |
25 | | - res.send_header('Content-type', 'application/json') |
26 | | - res.end_headers() |
27 | | - res.wfile.write(json.dumps(comments)) |
| 20 | + with open('_comments.json', 'r') as file: |
| 21 | + comments = json.loads(file.read()) |
28 | 22 |
|
29 | | -class MyHandler(SimpleHTTPRequestHandler): |
30 | | - def translate_path(self, path): |
31 | | - root = os.getcwd() |
32 | | - path = PUBLIC_PATH + path |
33 | | - return os.path.join(root, path) |
| 23 | + if request.method == 'POST': |
| 24 | + comments.append(request.form.to_dict()) |
34 | 25 |
|
35 | | - def do_GET(self): |
36 | | - if (self.path == "/comments.json"): |
37 | | - sendJSON(self) |
38 | | - else: |
39 | | - SimpleHTTPRequestHandler.do_GET(self) |
| 26 | + with open('_comments.json', 'w') as file: |
| 27 | + file.write(json.dumps(comments, indent=4, separators=(',', ': '))) |
40 | 28 |
|
41 | | - def do_POST(self): |
42 | | - if (self.path == "/comments.json"): |
43 | | - form = cgi.FieldStorage( |
44 | | - fp=self.rfile, |
45 | | - headers=self.headers, |
46 | | - environ={'REQUEST_METHOD':'POST', |
47 | | - 'CONTENT_TYPE':self.headers['Content-Type']} |
48 | | - ) |
49 | | - |
50 | | - # Save the data |
51 | | - comments.append({u"author": form.getfirst("author"), u"text": form.getfirst("text")}) |
52 | | - # Write to file |
53 | | - file = open('_comments.json', 'w+') |
54 | | - file.write(json.dumps(comments)) |
55 | | - file.close() |
56 | | - |
57 | | - sendJSON(self) |
58 | | - else: |
59 | | - SimpleHTTPRequestHandler.do_POST(self) |
| 29 | + return Response(json.dumps(comments), mimetype='application/json') |
60 | 30 |
|
61 | 31 | if __name__ == '__main__': |
62 | | - print "Server started: http://localhost:3000/" |
63 | | - httpd = HTTPServer(('127.0.0.1', 3000), MyHandler) |
64 | | - httpd.serve_forever() |
| 32 | + app.run(port=3000) |
0 commit comments