-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_dev.py
More file actions
185 lines (150 loc) · 6.14 KB
/
Copy pathserver_dev.py
File metadata and controls
185 lines (150 loc) · 6.14 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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 27 09:25:24 2018
@author: jlibor
"""
### Aktuelle Version als Hilfe ausgeben
import os
import sys
import time
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer # python 2
#from http.server import BaseHTTPRequestHandler, HTTPServer # python 3
import json
#from compute_embedding import compute_graph
"""
def format_string(graph):
s = str(graph)
s = s.replace("'", '"').replace(': ', ':').replace('False', 'false').replace('True', 'true')\
.replace(', ', ',').replace(':u"', ':"')
return s
"""
### prod server
def get_graph(userData=[]):
graph = compute_graph(userData)
return graph
#return userData
"""
### dev Server
def get_graph(userData = []):
filename = "data/response_data.txt"
with open(filename, "rb") as f:
return f.read()
"""
## MyHTTPHandler beschreibt den Umgang mit HTTP Requests
class MyHTTPHandler(BaseHTTPRequestHandler):
def do_OPTIONS(self):
self.send_response(200, "ok")
self.send_header('Access-Control-Allow-Origin', self.headers['origin'])
self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-type')
self.end_headers()
def do_GET(self):
"""
default route /
for fast checking if server is online
"""
if(self.path == "/"):
print("GET /")
self.send_response(200)
self.end_headers()
self.wfile.write('server online')
"""
example: /snapshots?userid=3&dataset=003
used for loading all saved snapshots for the given dataset
"""
if "/snapshots" in self.path:
print("GET /snapshot")
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
# get params
query = self.path.split('?')[1]
dataset = self.path.split('&')[0].split('=')[1]
userid = self.path.split('&')[1].split('=')[1]
print 'DEBUG: loading snapshots: ', userid, dataset
# path to jsons
json_dir = os.path.join(DATA_DIR, 'user_models', userid, dataset)
print 'DEBUG: ' ,json_dir # DEBUG
# send empty back if nothing is saved
if not os.path.isdir(json_dir):
print 'DEBUG: no files found' # DEBUG
self.wfile.write('[]')
return
# get all json files name
json_files = [pos_json for pos_json in os.listdir(json_dir) if pos_json.endswith('.json')]
content = []
for index, json_file in enumerate(json_files):
with open(os.path.join(json_dir, json_file)) as file:
content.append(json.load(file))
self.wfile.write(json.dumps(content))
def do_POST(self):
"""
definiert den Umgang mit POST Requests
Liest den Body aus - gibt in zum konvertieren weiter
"""
if(self.path == "/nodes"):
print("post /nodes")
### POST Request Header ###
self.send_response(200)
self.send_header('Content-type', 'application/json')
#self.send_header('Access-Control-Allow-Origin', self.headers['origin'])
self.end_headers()
# get body from request
content_len = int(self.headers['Content-Length'])
body = self.rfile.read(content_len)
# convert body to list
data = json.loads(str(body).decode('utf-8')) # python 2
#data = json.loads(str(body, encoding='utf-8')) # python 3
print(data)
## Katjas code goes here
#data = get_graph(data)
testDict = {}
testDict[0] = {'name': 'vincent-van-gogh_sower-1888-1', 'links': {1: 0.5}, 'x': 5, 'y': -5}
testDict[1] = {'name': 'vincent-van-gogh_sower-1888-1', 'links': {19: 0.5}, 'x': -10, 'y': 10}
testDict[2] = {'name': 'vincent-van-gogh_sower-1888-1', 'links': {}, 'x': -5, 'y': 5}
# make json
testDict = json.dumps(testDict).encode()
self.wfile.write(testDict) #body zurueckschicken
"""
Save a snapshot persistently
"""
if "/snapshots" in self.path:
print("POST /snapshots")
### POST Request Header ###
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
# get body from request
content_len = int(self.headers['Content-Length'])
body = self.rfile.read(content_len)
# convert body to list
data = json.loads(str(body).decode('utf-8')) # python 2
#data = json.loads(str(body, encoding='utf-8')) # python 3
userid = data["userid"] # userid of the logged in user
dataset = data["dataset"] # name of the dataset/or number
count = data["count"] # count of the images to separate snaps
print 'DEBUG: ', userid, dataset, count
#path for file to save snapshot
snapfile = os.path.join(DATA_DIR, '{}'.format(userid))
if not os.path.isdir(snapfile):
os.makedirs(snapfile)
# add dataset id to path
snapfile = os.path.join(snapfile, "{}".format(dataset))
if not os.path.isdir(snapfile):
os.makedirs(snapfile)
snapfile = os.path.join(snapfile, "{}.json".format(count))
with open(snapfile, 'w') as f:
json.dump(data, f)
self.wfile.write('ok')
return
if __name__ == "__main__":
# config
HOST_NAME = "localhost"
PORT_NUMBER = 8001
try:
http_server = HTTPServer((HOST_NAME, PORT_NUMBER), MyHTTPHandler)
print(time.asctime(), 'Server Starts - %s:%s' % (HOST_NAME, PORT_NUMBER), '- Beenden mit STRG+C')
http_server.serve_forever()
except KeyboardInterrupt:
print(time.asctime(), 'Server Stops - %s:%s' % (HOST_NAME, PORT_NUMBER), '- Beenden mit STRG+C')
http_server.socket.close()