Skip to content

Commit 8e78f6c

Browse files
committed
Switch python server to use Flask
1 parent 558e0c7 commit 8e78f6c

File tree

3 files changed

+15
-45
lines changed

3 files changed

+15
-45
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ node server.js
1616
### Python
1717

1818
```sh
19+
pip install -r requirements.txt
1920
python server.py
2021
```
2122

requirements.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Flask==0.10.1

server.py

+13-45
Original file line numberDiff line numberDiff line change
@@ -8,57 +8,25 @@
88
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
99
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1010

11-
import os
1211
import json
13-
import cgi
14-
from BaseHTTPServer import HTTPServer
15-
from SimpleHTTPServer import SimpleHTTPRequestHandler
12+
from flask import Flask, Response, request
1613

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'))
1816

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():
2219

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())
2822

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())
3425

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=(',', ': ')))
4028

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')
6030

6131
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

Comments
 (0)