1
+ #import sys
2
+ #import database
3
+ #sys.path.append('/home/netcamo/css/module4/Assignment/database')
4
+ from flask import Flask , jsonify , request , Response
5
+ from flask_mongoengine import MongoEngine
6
+ from database .db import initialize_db
7
+ from database .models import Photo ,Album
8
+ from flask import request , jsonify
9
+ from bson .objectid import ObjectId
10
+ #from database.db import initialize_db
11
+ #from database.models import Photo, Album
12
+ import json
13
+ import os
14
+ import urllib
15
+ import base64
16
+ import codecs
17
+
18
+
19
+ app = Flask (__name__ )
20
+ app .config ['MONGODB_SETTINGS' ] = {
21
+ 'host' :'mongodb://mongo/flask-database'
22
+ }
23
+ db = initialize_db (app )
24
+
25
+ def object_list_as_id_list (obj_list ):
26
+ return list ( map (lambda obj : str (obj .id ), obj_list ))
27
+ def str_list_to_objectid (str_list ):
28
+ return list (map (lambda str_item : ObjectId (str_item ),str_list ))
29
+
30
+ if __name__ == '__main__' :
31
+ app .run ()
32
+
33
+
34
+
35
+
36
+ class bcolors :
37
+ HEADER = '\033 [95m'
38
+ OKBLUE = '\033 [94m'
39
+ OKCYAN = '\033 [96m'
40
+ OKGREEN = '\033 [92m'
41
+ WARNING = '\033 [93m'
42
+ FAIL = '\033 [91m'
43
+ ENDC = '\033 [0m'
44
+ BOLD = '\033 [1m'
45
+ UNDERLINE = '\033 [4m'
46
+
47
+
48
+ @app .route ('/listPhoto' , methods = ['POST' ])
49
+ def add_photo ():
50
+ posted_image = request .files ['file' ]
51
+ posted_data = request .form .to_dict () #"use request.form to obtain the associated immutable dict and convert it into dict"
52
+ default_album = Album .objects (name = "Default" )
53
+ if (len (default_album )== 0 ) :
54
+ default_album = Album (name = "Default" ).save ()
55
+ print ("Saved" )
56
+
57
+ albums = ["Default" ];
58
+ albums_id = []
59
+ for album in albums :
60
+ albums_id .append (str (Album .objects (name = album )[0 ].id ))
61
+
62
+
63
+ print (f"{ bcolors .FAIL } START COMMENT{ bcolors .ENDC } " )
64
+ print (albums_id )
65
+ print (f"{ bcolors .WARNING } END COMMENT{ bcolors .ENDC } " )
66
+
67
+ photo = Photo (** posted_data , image_file = posted_image )
68
+ if "tags" in posted_data .keys ():
69
+ photo .tags = list (map (str .strip , json .loads ( posted_data ['tags' ])))
70
+
71
+ photo .albums = str_list_to_objectid (albums_id )
72
+ print (photo .tags )
73
+ photo .save ()
74
+ output = {'message' : "Photo successfully created" , 'id' : str (photo .id )}
75
+ status_code = 201
76
+ return output ,status_code
77
+
78
+
79
+
80
+
81
+ @app .route ('/listPhoto/<photo_id>' , methods = ['GET' , 'PUT' , 'DELETE' ])
82
+ def get_photo_by_id (photo_id ):
83
+ if request .method == "GET" :
84
+ photo = Photo .objects .get (id = photo_id )
85
+ "Get the photo with photo_id from the db"
86
+ if photo :
87
+ ## Photos should be encoded with base64 and decoded using UTF-8 in all GET requests with an image before sending the image as shown below
88
+ base64_data = codecs .encode (photo .image_file .read (), 'base64' )
89
+ image = base64_data .decode ('utf-8' )
90
+ ##########
91
+ output = {"name" : photo .name , "location" :photo .location ,
92
+ "tags" :photo .tags ,"albums" : photo .albums , "file" : image }
93
+ status_code = 200
94
+ return output , status_code
95
+ elif request .method == "PUT" :
96
+ photo = Photo .objects (id = photo_id )
97
+ body = request .get_json ()
98
+ # if "albums" in keys:
99
+ # # print(f"{bcolors.FAIL}START COMMENT{bcolors.ENDC}")
100
+ # # print(body["albums"])
101
+ # # print(f"{bcolors.WARNING}END COMMENT{bcolors.ENDC}")
102
+ # albums=["Default"]
103
+ # for al in body["albums"]:
104
+ # if(len(Album.objects(name=al))==0):
105
+ # Album(name=al).save()
106
+ # albums.append(al)
107
+ # albums_id=[]
108
+ # for album in albums:
109
+ # albums_id.append(str(Album.objects(name=album)[0].id))
110
+ # body["albums"]=str_list_to_objectid(albums_id)
111
+ # print(body["albums"])
112
+
113
+ # photo.albums
114
+ #body["albums"]= # ALBUM duzelt
115
+
116
+ albums = ["Default" ];
117
+ albums_id = []
118
+ for album in albums :
119
+ albums_id .append (str (Album .objects (name = album )[0 ].id ))
120
+ print (Album .objects (name = album )[0 ].id )
121
+ body ["albums" ]= str_list_to_objectid (albums_id )
122
+ Photo .objects .get (id = photo_id ).update (** body )
123
+ output = {'message' : "Photo successfully updated" , 'id' : str (photo_id )}
124
+ status_code = 200
125
+ return output ,status_code
126
+
127
+ elif request .method == "DELETE" :
128
+ photo = Photo .objects .get_or_404 (id = photo_id )
129
+ photo .delete ()
130
+ output = {'message' : "Photo successfully deleted" , 'id' : str (photo_id )}
131
+ status_code = 200
132
+ return output ,status_code
133
+
134
+
135
+ @app .route ('/listPhotos' , methods = ['GET' ])
136
+ def get_photos ():
137
+
138
+ tag = request .args .get ("tag" ) #"Get the tag from query parameters"
139
+ albumName = request .args .get ("albumName" ) #"Get albumname from query parameters"
140
+ if albumName is not None :
141
+ albums = Album .objects (name = albumName )
142
+ photo_objects = Photo .objects (albums__in = albums )
143
+ photo_objects = []
144
+ photo_objects .append (Photo .objects ()[0 ])
145
+ photo_objects .append (Photo .objects ()[1 ])
146
+
147
+
148
+ elif tag is not None :
149
+ photo_objects = Photo .objects (tags = tag )
150
+ else :
151
+ photo_objects = Photo .objects
152
+
153
+ photos = []
154
+ for photo in photo_objects :
155
+ base64_data = codecs .encode (photo .image_file .read (), 'base64' )
156
+ image = base64_data .decode ('utf-8' )
157
+ photos .append ({'name' : photo .name , 'location' : photo .location ,
158
+ "albums" : photo .albums , "id" : object_list_as_id_list ([photo ]) ,
159
+ "file" : image
160
+ })
161
+ return jsonify (photos ), 200
162
+
163
+
164
+
165
+
166
+
167
+
168
+
169
+ @app .route ('/listAlbum' , methods = ['POST' ])
170
+ def add_album ():
171
+ posted_data = request .form .to_dict () #"use request.form to obtain the associated immutable dict and convert it into dict"
172
+ print (f"{ bcolors .FAIL } START COMMENT{ bcolors .ENDC } " )
173
+ print (posted_data )
174
+ print (f"{ bcolors .WARNING } END COMMENT{ bcolors .ENDC } " )
175
+
176
+
177
+ album = Album (** posted_data )
178
+ album .save ()
179
+ output = {'message' : "Album successfully created" , 'id' : str (album .id )}
180
+ status_code = 201
181
+ return output ,status_code
182
+ return "Got it" , 201
183
+
184
+ @app .route ('/listAlbum/<album_id>' , methods = ['GET' , 'PUT' , 'DELETE' ])
185
+ def get_album_by_id (album_id ):
186
+ if request .method == "GET" :
187
+ album = Album .objects .get (id = album_id )
188
+
189
+ if album :
190
+ print (f"{ bcolors .FAIL } START COMMENT{ bcolors .ENDC } " )
191
+ output = {"id" : str (album_id ), "name" : album .name }
192
+ status_code = 200
193
+ return output , status_code
194
+
195
+ elif request .method == "PUT" :
196
+ album = Album .objects (id = album_id )
197
+ body = request .get_json ()
198
+ print (f"{ bcolors .FAIL } START COMMENT{ bcolors .ENDC } " )
199
+ album .name = body ['name' ]
200
+ print ({"name" : album .name })
201
+ print (f"{ bcolors .WARNING } END COMMENT{ bcolors .ENDC } " )
202
+ keys = body .keys ()
203
+
204
+ Album .objects .get (id = album_id ).update (** body )
205
+ output = {'message' : "Album successfully updated" , 'id' : str (album_id )}
206
+ status_code = 200
207
+ return output ,status_code
208
+
209
+ elif request .method == "DELETE" :
210
+ album = Album .objects .get_or_404 (id = album_id )
211
+ album .delete ()
212
+ output = {'message' : "Album successfully deleted" , 'id' : str (album_id )}
213
+ status_code = 200
214
+ return output ,status_code
215
+
0 commit comments