~mateo-salta/touch-rss-scope/utfeed1

« back to all changes in this revision

Viewing changes to tests/server/server.py

  • Committer: Mateo Salta
  • Date: 2014-11-30 22:43:28 UTC
  • Revision ID: mateo_salta@yahoo.com-20141130224328-1bshkjh7chb1kwvs
- Added 4 more custom feeds

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python3
 
2
 
 
3
import http.server
 
4
import os
 
5
import socketserver
 
6
import sys
 
7
from urllib.parse import urlparse,parse_qs
 
8
 
 
9
def read_file(path):
 
10
    file = os.path.join(os.path.dirname(__file__), path)
 
11
    if os.path.isfile(file):
 
12
        with open(file, 'r') as fp:
 
13
            content = fp.read()
 
14
    else:
 
15
        content = ''
 
16
 
 
17
    return content
 
18
 
 
19
class MyRequestHandler(http.server.BaseHTTPRequestHandler):
 
20
    def do_GET(self):
 
21
        sys.stderr.write("GET: %s\n" % self.path)
 
22
        sys.stderr.flush()
 
23
 
 
24
        parse = urlparse(self.path)
 
25
        path = parse.path
 
26
        query = parse_qs(parse.query)
 
27
        
 
28
        if path == '/data/2.5/weather':
 
29
            self.send_response(200)
 
30
            self.send_header("Content-type", "text/html")
 
31
            self.end_headers()
 
32
 
 
33
            mode = 'json'
 
34
            if 'mode' in query:
 
35
                mode = query['mode'][0]
 
36
 
 
37
            self.wfile.write(bytes(read_file('weather/%s.%s' % (query['q'][0], mode)), 'UTF-8'))
 
38
        elif path == '/data/2.5/forecast/daily':
 
39
            self.send_response(200)
 
40
            self.send_header("Content-type", "text/html")
 
41
            self.end_headers()
 
42
 
 
43
            mode = 'json'
 
44
            if 'mode' in query:
 
45
                mode = query['mode'][0]
 
46
 
 
47
            self.wfile.write(bytes(read_file('forecast/daily/%s.%s' % (query['q'][0], mode)), 'UTF-8'))
 
48
        else:
 
49
            self.send_response(404)
 
50
            self.send_header("Content-type", "text/html")
 
51
            self.end_headers()
 
52
            self.wfile.write(bytes('ERROR', 'UTF-8'))
 
53
 
 
54
if __name__ == "__main__":
 
55
    Handler = MyRequestHandler
 
56
    httpd = socketserver.TCPServer(("127.0.0.1", 0), Handler)
 
57
 
 
58
    sys.stdout.write('%d\n' % httpd.server_address[1])
 
59
    sys.stdout.flush()
 
60
 
 
61
    httpd.serve_forever()
 
62
 
 
63