Skip to content

Commit a806e60

Browse files
committed
Initial commit
0 parents  commit a806e60

10 files changed

+290
-0
lines changed

Diff for: .gitattributes

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Auto detect text files and perform LF normalization
2+
* text=auto

Diff for: docker-compose.yaml

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
version: "3.9"
2+
3+
services:
4+
backend:
5+
build: .
6+
container_name: flaskbackend
7+
image: flaskbackend:v1
8+
ports:
9+
- "5000:5000"
10+
depends_on:
11+
- mongo
12+
13+
mongo:
14+
container_name: mongo
15+
image: mongo:4.2.0
16+
environment:
17+
MONGO_INITDB_DATABASE: flask-database
18+
ports:
19+
- "1048:27017"
20+
21+

Diff for: exercise.zip

4.96 KB
Binary file not shown.

Diff for: exercise/Dockerfile

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
FROM python:3.8.5-alpine3.12
2+
WORKDIR /usr/app
3+
ENV FLASK_APP=app.py
4+
ENV FLASK_RUN_HOST=0.0.0.0
5+
EXPOSE 5000
6+
RUN apk add --no-cache gcc libc-dev linux-headers zlib-dev jpeg-dev libjpeg
7+
COPY requirements.txt requirements.txt
8+
RUN pip install -r requirements.txt
9+
COPY . .
10+
CMD flask run --host 0.0.0.0

Diff for: exercise/app.py

+215
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
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+

Diff for: exercise/database/__pycache__/db.cpython-38.pyc

339 Bytes
Binary file not shown.

Diff for: exercise/database/__pycache__/models.cpython-38.pyc

755 Bytes
Binary file not shown.

Diff for: exercise/database/db.py

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
from flask_mongoengine import MongoEngine
2+
db = MongoEngine()
3+
def initialize_db(app):
4+
db.init_app(app)

Diff for: exercise/database/models.py

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from .db import db
2+
3+
class Album(db.Document):
4+
name = db.StringField(unique=True)
5+
description=db.StringField()
6+
class Photo(db.Document):
7+
name = db.StringField(required=True)
8+
tags=db.ListField(db.StringField())
9+
location=db.StringField()
10+
image_file=db.ImageField()
11+
albums= db.ListField(db.ReferenceField('Album',reverse_delete_rule=2))
12+

Diff for: exercise/requirements.txt

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
######################################################################
2+
## This includes all the modules and the fixed version dependencies #
3+
## You can add more modules below if required #
4+
######################################################################
5+
bson==0.5.10
6+
certifi==2020.6.20
7+
chardet==3.0.4
8+
click==7.1.2
9+
docker==4.3.0
10+
Flask==1.1.2
11+
flask-mongoengine==0.9.5
12+
Flask-WTF==0.14.3
13+
idna==2.10
14+
itsdangerous==1.1.0
15+
Jinja2==2.11.2
16+
MarkupSafe==1.1.1
17+
mongoengine==0.20.0
18+
pymongo==3.11.0
19+
python-dateutil==2.8.1
20+
requests==2.24.0
21+
six==1.15.0
22+
urllib3==1.25.10
23+
websocket-client==0.57.0
24+
Werkzeug==1.0.1
25+
WTForms==2.3.3
26+
Pillow==8.2.0

0 commit comments

Comments
 (0)