-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.py
96 lines (81 loc) · 3.2 KB
/
client.py
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
import requests
import os
# This class is for communicating between the server and the editor
# The server is simply used for saving the games so they can be played
class Client():
VERBOSE = False
SERVER_ADDRESS = 'http://localhost:5000'
ROUTES = {
"upload": '/upload'
}
# Main function for uploading game files to the server
# Will construct a dict of the files, read them, and
# send to the server using a HTTP POST
def upload_game_files(self, game_root):
if self.VERBOSE:
print("Client :: upload_game_files")
# Get a list of the files we want to upload
file_list = self.get_list_of_game_files(game_root)
# Build a dictionary using the file_list
files = self.build_file_dictionary(file_list)
# Post the list to the server
if self.VERBOSE:
print("Client :: Attempting to POST")
try:
# Send the files dict to the server in
# Also send the "game root" in a variable
# game root is ./gamedata/<game_name>, but we drop the ./
response = requests.post(
self.SERVER_ADDRESS + self.ROUTES['upload'],
files=files, params={"root": game_root[2:]})
if self.VERBOSE:
print(
"Client :: Response status code: " +
str(response.status_code))
# Return the response so we can access,
# for example the status code elsewhere
return response
except requests.ConnectionError as e:
print("Client :: ERROR!! Could not connect to server")
print(" " + str(e))
return None
# Find the game files from the given folder, and save
# their names into a { <folder>: [<full_path>, <full_path>, ..]}
def get_list_of_game_files(self, game_root):
if self.VERBOSE:
print("Client :: get_list_of_game_files in " + game_root)
struct = os.walk(game_root)
ret = {}
# Root is the "current" folder, dirs is folders in that folder,
# files is files in that folder
for root, dirs, files in struct:
ret[root] = []
for f in files:
ret[root].append(root+'/'+f)
if self.VERBOSE:
print("Client :: Found the following files")
for root in ret:
print("* " + root)
for f in ret[root]:
print(' - ' + f)
return ret
# Gets the list of files from get_list_of_game_files,
# opens the files, and returns a dict:
# { <full_path>: <opened_file> }
def build_file_dictionary(self, file_list):
if self.VERBOSE:
print("Client :: build_file_dictionary")
ret = {}
for root in file_list:
for f in file_list[root]:
path = f
if path[:1] == '.':
path = path[1:]
if path[:1] == '/':
path = path[1:]
ret[path] = open(f, 'rb')
if self.VERBOSE:
print("Client :: Built the following dictionary:")
for name in ret:
print("* " + name)
return ret