Last active
October 31, 2018 14:27
-
-
Save robotenique/8f2be55ab4c09a318aa48a3e6177f0be to your computer and use it in GitHub Desktop.
How to: (1) Parse json snack object (2) open the image and add the image into the Model (3) save the new data (4) Iterate and access the snacks and images from the mongodb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@app.route("/display-snack") | |
@login_required | |
def display_snack(): | |
my_database = mongo[DATABASE] | |
my_file = open("snacks/snacks.json", "rb") | |
parsed = json.loads(my_file.read().decode('unicode-escape')) | |
snacks = parsed | |
s = snacks | |
Snack.objects.delete() | |
for s in snacks: | |
# Always delete a document before inserting it again | |
new_snack = Snack(snack_name=s["title"], available_at_locations=[s["country"]]) | |
if s.get("description"): | |
new_snack.description = s["description"] | |
if s.get("company"): | |
new_snack.snack_brand = s["company"] | |
else: | |
continue | |
new_snack.avg_overall_rating = 0 | |
new_snack.avg_bitterness = 0 | |
new_snack.avg_saltiness = 0 | |
new_snack.avg_sourness = 0 | |
new_snack.avg_spiciness = 0 | |
new_snack.avg_sweetness = 0 | |
new_snack.review_count = 0 | |
if s.get("folder_name"): | |
i = SnackImage() | |
for entry in os.scandir("snacks/image/"+s.get("folder_name")): | |
with open(entry.path, "rb") as image_file: | |
img_name = os.path.basename(image_file.name) | |
i.img.put(image_file, filename=img_name) | |
new_snack.photo_files.append(i) | |
try: | |
new_snack.save() | |
except Exception as e: | |
print("Error \n %s" % e, file=sys.stdout) | |
max_show = 100 # Maximum number of snacks to send to view | |
sl = [] | |
for s in Snack.objects[:max_show]: | |
if s.photo_files: | |
sl.append(s) | |
for file in s.photo_files: | |
photo = file.img | |
# Guess the type of the mimetype to send a good response | |
# mimetype = mimetypes.MimeTypes().guess_type(photo.filename)[0] | |
# resp=Response(photo.read(), mimetype=mimetype) | |
# photo.read() # This is image itself | |
# photo.filename # This is the name of the image | |
# photo.format # This is the format of the image (png, jpg, etc) | |
# photo.thumbnail.read() # This is the thumbnail of the image """ | |
print("Finished.") | |
print(f"{len(sl)}") | |
return render_template('display_snack.html', snack_list=sl) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment