def addImage(mime,description,bf,name): 'Add Image' image=Images(mime=mime,description=description,bf=bf,name=name) image.size=len(image.bf) image.filetype,image.width,image.height=getImageInfo(bf) image.put() return image
def backup(self): images = Images.all().fetch(PAGESIZE) while images: for image in images: self.save(image) images = Images.all().filter('__key__ >', images[-1].key()).fetch(PAGESIZE)
def home(request): posts = Blog.objects.all()[:10] for post in posts: html = django_markdown.utils.markdown(value=post.body) soup = BeautifulSoup(html) try: ex = soup.p.string imgs = soup.findAll('img', {'src': True}) if len(imgs) > 1: post.type = 4 for img in imgs: url = img['src'] imglist = Images.objects.filter(link=url) if len(imglist) == 0: image = Images(link=url) image.save() else: image = imglist[0] post.imagelinks.add(image) post.save() post.excerpt = ex[0:330] + '...' post.save() except: pass return render_to_response('alwaysblue/index.html', { 'tags': Tag.objects.all(), 'posts': posts })
def xmlparse(): #pagecode = urllib.urlopen("http://www.esmadrid.com/opendata/alojamientos_v1_es.xml") pagecode = urllib.urlopen( "http://cursosweb.github.io/etc/alojamientos_es.xml") xmlsheet = pagecode.read() noticias = xmlsheet.split("<service ") for noticia in noticias[1:-1]: url = noticia.split("<web>")[1].split("</web>")[0] try: alojamiento = Alojamientos.objects.get(url=url) except Alojamientos.DoesNotExist: name = noticia.split("<name><![CDATA[")[1].split("]]></name>")[0] address = noticia.split("<address>")[1].split("</address>")[0] zipcode = noticia.split("<zipcode>")[1].split("</zipcode>")[0] country = noticia.split("<country>")[1].split("</country>")[0] latitude = noticia.split("<latitude>")[1].split("</latitude>")[0] longitude = noticia.split("<longitude>")[1].split( "</longitude>")[0] city = noticia.split("<subAdministrativeArea>")[1].split( "</subAdministrativeArea>")[0] alojamiento = Alojamientos(name=name, url=url, address=address, zipcode=zipcode, country=country, latitude=latitude, longitude=longitude, city=city) alojamiento.save() images = noticia.split('<url>') for image in images[1:6]: image_url = image.split('</url>')[0] image = Images(url=image_url, alojamiento=alojamiento) image.save()
def add_image(request): if 'token' in request.POST: token = request.POST['token'] userdetail = UserDetail(request).getLoginUser() user_id = userdetail['id'] data = {} if 'file' in request.FILES: image = request.FILES.get('file') file_type = image.content_type.split('/')[0] print "\n\n type of image : ", type(file_type) if str(file_type) != "image": data = {'is_valid': False, 'message': 'Please upload Images Only.'} return HttpResponse(json.dumps(data)) try: images = Images(user_id=user_id, image=request.FILES.get('file')) images.save() token = images.token image_id = images.id image_name = images.image_name url = "http://" + request.META['HTTP_HOST'] + "/images/view/" + str( token) + "/" + str(image_id) data = { 'is_valid': True, 'name': image_name, 'url': url, 'token': token } except: data = {'is_valid': False, 'message': 'Cannot Be Uploaded.'} return HttpResponse(json.dumps(data))
def _save_image(image): existing_uuid = Images.insert_if_not_exists(image) image_id = existing_uuid or uuid.uuid1() filename = Images.generate_filename(image_id) url = url_for('static', face_images="face_images", filename=filename) save_image_in_filesystem(image, filename) return (url, image_id)
def delete(self, id): image = Images.first(id=id) msg = "The image could not be deleted." if image and Images.delete(image): msg = "Image deleted" cherrypy.session['flash'] = msg raise cherrypy.HTTPRedirect('/images')
def addImage(name, mime,description,tag,bf): 'Add Image' image=Images(name=name, mime=mime,description=description,tag=tag.split(','), bf=bf) image.size=len(image.bf) image.filetype,image.width,image.height=getImageInfo(bf) image.put() AddTags(image.tag) return image
def AddImageByUrl(url,fileName,tag): result = urlfetch.fetch(url) if result.status_code == 200: name = fileName mtype = result.headers.get('Content-Type', '') bits = result.content gf=GaeFile() gf.open(name,mtype); gf.write(bits) id=gf.close() image=Images(description="/media/?key="+str(id)) image.mime=result.headers.get('Content-Type', '') image.filetype=image.mime # if image.mime.find('image')==-1: # return None image.size=len(bits) image.width=-1; image.height=-1; # image.name=fileName # image.filetype,image.width,image.height=getImageInfo(image.bf) image.tag=tag.split(',') image.put() AddTags(image.tag) return image else: return None
def addImage(mime,description,bf): 'Add Image' image=Images(mime=mime,description=description) image.size=len(image.bf) image.filetype,image.width,image.height=getImageInfo(bf) image.put() imageblob = ImageBlob(image=image, bf=bf) imageblob.put() prependToRSS([image]) return image
def get(self): #logging.info("T!!!!!!!!!!!!!!!!!!!!!!HE value of contention is %s", self.request.get("entity_id")) type = self.request.get("type") the_ID = self.request.get("entity_id") if not the_ID == None: if type == "con": con = Images.get_by_id(int(the_ID)) self.response.headers['Content-Type'] = 'image/jpeg' self.response.out.write(con.image) elif type == "elem": elem = Images.get_by_id(int(the_ID)) self.response.headers['Content-Type'] = 'image/jpeg' self.response.out.write(elem.image) else: self.redirect('/static/ok.png')
def edit_photos(): upload = FileForm() set_loop = Set.query.order_by(Set.id.desc()).all() if upload.validate_on_submit(): for loop in set_loop: if request.form["select_set"] == loop.tag: file = request.files['file'] bucket.put_object(Key='Tractor Show/' + loop.name + '/' + file.filename, Body=file) newFile = Images(name=file.filename, set=loop) db.session.add(newFile) db.session.commit() return redirect('/dashboard/photos#' + loop.tag) add_set = AddSet() if add_set.validate_on_submit(): render_tag = tag_generator(request.form["set"]) new_set = Set(name=request.form["set"], tag=render_tag) db.session.add(new_set) db.session.commit() return redirect(url_for('edit_photos')) return render_template('authentication/edit-photos.html', upload=upload, add_set=add_set, set_loop=set_loop, s3projects=s3projects)
def get_image_id(request): # Get our desired filename. uploading_filename = request.form.get("imageFileName") if not uploading_filename: return exceptions.BadRequest() # Ensure we have an image. if "jpegData" not in request.files: return exceptions.BadRequest() # Sanitize for when we write to disk. filename = secure_filename(uploading_filename) # Necessary as render templates require the original filename with ".jpg" appended. # Nobody here is fond of this. filename += ".jpg" # An image ID has a maximum size of 7. unique_id = generate_unique_id(Images, Images.image_id, 7) if unique_id == "": return exceptions.InternalServerError() # Next, save our file to disk. jpeg_image = request.files["jpegData"] jpeg_image.save(determine_path(current_order.order_id, filename)) # Finally, save state to the database. added_image = Images( image_id=unique_id, order_id=current_order.order_id, filename=filename ) db.session.add(added_image) db.session.commit() return { "imageID": unique_id, }
def delImage(key): image=Images.get(key) if image: imageblob = db.GqlQuery("SELECT * FROM ImageBlob WHERE image = :1", image).get() if imageblob: imageblob.delete() image.delete()
def add_image(): link = request.json["link"] user_id = request.json["user_id"] new_image = Images(link=link,user_id=user_id) db.session.add(new_image) db.session.commit() return jsonify(success=True)
def get_image_id(request): # Get our desired filename. uploading_filename = request.form.get("imageFileName") if not uploading_filename: return exceptions.BadRequest() # Ensure we have an image. if "jpegData" not in request.files: return exceptions.BadRequest() # An image ID has a maximum size of 7. unique_id = generate_unique_id(Images, Images.image_id, 7) if unique_id == "": return exceptions.InternalServerError() filename = f"{unique_id}.jpg" # Next, save our file to disk. jpeg_image = request.files["jpegData"] jpeg_image.save(determine_path(current_order.order_id, filename)) # Finally, save state to the database. added_image = Images(image_id=unique_id, order_id=current_order.order_id, filename=filename) db.session.add(added_image) db.session.commit() return { "imageID": unique_id, }
def setUp(self): self.engine = create_engine('mysql+pymysql://') self.session = Session(engine) Base.metadata.create_all(self.engine) self.characters_instance = Characters(1009610, "Spider-Man") self.session.add(self.character_instance) self.comics_instance = Comics(30885, "Age of Heroes (Trade Paperback)") self.session.add(self.comics_instance) self.creators_instance = Creators(9799, "David Baldeon") self.session.add(self.creators_instance) self.events_instance = Events(116, "Acts of Vengeance!") self.session.add(self.events_instance) self.series_instance = Series(10235, "Age of Heroes (2011)") self.session.add(self.series_instance) self.stories_instance = Stories(483, "Interior #483") self.session.add(self.stories_instance) self.images_instance = Images( 1, 0, "http://i.annihil.us/u/prod/marvel/i/mg/3/40/4c06c8261544e") self.session.add(self.images_instance) self.session.commit()
def upload(): #---make static file if not exists target = os.path.join(APP_ROOT, 'static/') print(target) if not os.path.isdir(target): os.mkdir(target) else: print("Couldn't create upload directory {}".format(target)) #---get image print(request.files.getlist("file")) for upload in request.files.getlist("file"): print(upload) print("{} is the filename".format(upload.filename)) name = upload.filename destination = "/".join([target, name]) print("Accept incoming file:", name) print("Save it to:", destination) upload.save(destination) #---and store.. user_id = current_user.user_id name = upload.filename username = Users.query.filter_by(user_id=user_id).first().username image = str('www.doc.gold.uk/usr/340/static/' + str(name)) new_image = Images(user_id=user_id, username=username, image=image, name=name) db.session.add(new_image) db.session.commit() #result = Images.query.filter_by(name=name).first() return redirect(vs_url_for('add_image')) return render_template('complete.html', name=name)
def get(self): collector = CloudFetch.CloudFetch() urllist = collector.getUrlList() #url = 'http://www.technobuffalo.com/wp-content/uploads/2012/12/Google-Apps.jpeg' #urllist = urllist.append(url) images = Images.all() for url in urllist: bf = urllib.urlopen(url).read() #bf=self.request.get("file") if not bf: return self.redirect('/') #name=self.request.body_file.vars['file'].filename #mime = self.request.body_file.vars['file'].headers['content-type'] #if mime.find('image')==-1: # return self.redirect('/admin/upload/') #description=self.request.get("description") mime = 'image' description = 'Fetched From Cloud' name = url.split('/')[len(url.split('/'))-1] #DETECT DUPLICATE flag = False; for i in images: if(i.name == name): flag = True break if(flag == True): continue image=methods.addImage( mime, description, bf, name) self.redirect('/')
def delImageByid(id): image=Images.get_by_id(int(id)) if image: imageblob = db.GqlQuery("SELECT * FROM ImageBlob WHERE image = :1", image).get() if imageblob: imageblob.delete() image.delete()
def upload_file(id=""): JSON = {} if request.method == 'POST': files = request.files.getlist('upload') if files: # load_photo(files, path_image, 768, path_thumbnail, 150) filename = secure_filename( utilites.transliterate(files[0].filename, ".")) input_image_folder = Config.full_images_folder + "/articles/" + str( id) + "/" if os.path.exists(input_image_folder): files[0].save(input_image_folder + filename) else: os.mkdir(input_image_folder) files[0].save(input_image_folder + filename) path = "/articles/" + str(id) + "/" + filename JSON["fileName"] = filename JSON["uploaded"] = 1 JSON["url"] = Config.images_folder + path image = Images(filename, path, "", utilites.timeNow("u"), id) db.session.add(image) db.session.commit() JSON = json.dumps(JSON, ensure_ascii=True, indent=None, sort_keys=False) return JSON, {'Content-Type': 'text/json'}
def post(self): data = request.get_json() try: user_id = data['user_id'] name = data['name'] sex = data['sex'] filename = data['filename'] b64image = data['b64image'] decoded_image = base64.b64decode(b64image) except Exception as e: abort(400, e) file_data = BytesIO(decoded_image) file = FileStorage(file_data, filename=filename) img_uri = os.path.join("static", BaseConfig.IMAGE_URI, filename) file.save(img_uri) new_image = Images(img_uri) db.session.add(new_image) try: db.session.commit() except Exception as e: abort(500, e) # PREDICTION #### return jsonify()
def index(self): user_id = cherrypy.session.get('user.id') vms = VirtualMachines.find(user_id=user_id) env = dict( virtual_machines=vms, images=Images.all(), instance_types=InstanceTypes.all() ) return self.render("virtual_machines/index.html", self.crumbs, **env)
def addImage2(bf): image = Images(bf=bf) image.size = len(bf) image.filetype, image.width, image.height = getImageInfo(bf) if not image.filetype: return None image.mime = image.filetype image.put() return image
def create_image_record(bucket, key): ''' Creates an Image object to store in DB. Record stored in Images table. :param bucket: S3 bucket to use :param key: path to image in specified S3 bucket :returns: Images Object ''' return Images(bucket=bucket, filename=PurePath(key).name, key=key)
def gallery(request,imagename=None): print imagename if request.method == 'POST': title = request.POST['pname'] img_data = request.POST['pdata'] p = Images(title = title, img_data = img_data) p.save() if request.method == 'GET': image = Images.objects.filter(title = imagename) for i in image: data = i.img_data print json.dumps(data) t = get_template('paint.html') html = t.render(Context({})) if data: html="""<script>var data=JSON.parse(' """+data+""" ');</script>"""+html else: html="""<script>alert("Image not found")</script>"""+html return HttpResponse(html)
def edit(self, id, **post): image = Images.first(id=id) if not image: cherrypy.session['flash'] = "404 Image Not Found" raise cherrypy.HTTPRedirect('/images') if post: fields = ['name', 'backend_id', 'description'] data = self._get_data('image', fields, post) if image.update(data, fields): cherrypy.session['flash'] = "Image successfully updated." raise cherrypy.HTTPRedirect('/images') cherrypy.session['flash'] = 'Invalid data' backend_images = Images.get_backend_images() env=dict(image = image, backend_images=backend_images) return self.render("/images/edit.html", crumbs=self.crumbs, **env)
def add(self, **post): image = Images.new(name="", backend_id="", description="") if post: fields = ['name', 'backend_id', 'description'] data = self._get_data('image', fields, post) self._set_data(image, data) if image.validates() and Images.add(image): cherrypy.session['flash'] = "Image added" raise cherrypy.HTTPRedirect('/images') cherrypy.session['flash'] = 'Invalid data' backend_images = Images.get_backend_images() env = dict( image = image, backend_images = backend_images ) return self.render("/images/add.html", crumbs=self.crumbs, **env)
def gallery(request, imagename=None): print imagename if request.method == 'POST': title = request.POST['pname'] img_data = request.POST['pdata'] p = Images(title=title, img_data=img_data) p.save() if request.method == 'GET': image = Images.objects.filter(title=imagename) for i in image: data = i.img_data print json.dumps(data) t = get_template('paint.html') html = t.render(Context({})) if data: html = """<script>var data=JSON.parse(' """ + data + """ ');</script>""" + html else: html = """<script>alert("Image not found")</script>""" + html return HttpResponse(html)
def add_image(request): form = ImageForm() if request.POST: form = ImageForm(request.POST, request.FILES) if form.is_valid(): image = request.FILES['image_file'] comment = form.cleaned_data['comment'] format = image.name.split('.')[-1] p = Images(comment = comment, name = '', useragent = request.META['HTTP_USER_AGENT'], ip = request.META['REMOTE_ADDR'], views = 0 ,views_last_hour = 0, md5 = 0, format = format) p.save() save_image(image, p.id) return HttpResponseRedirect('/%s' % to_62(p.id)) else: form = ImageForm() return render_to_response("forms/add_image.html", {'form': form}) else: return render_to_response("forms/add_image.html", {'form': form})
def addImage(title, bf, referer): 'Add Image' image = Images(description=title, bf=bf, referer=referer) image.size = len(image.bf) image.filetype, image.width, image.height = getImageInfo(bf) if not image.filetype: return None image.mime = image.filetype image.put() return image
def running(self): creds = cherrypy.session.get('credentials') vms = VirtualMachines.all() images = Images.all() instances = VirtualMachines.get_instances(creds) env = dict( virtual_machines=vms, instances=instances, images=images, ) return self.render("virtual_machines/running.html", self.crumbs,**env)
def addImage(mime, description, bf, name): 'Add Image' image = Images(mime=mime, description=description, bf=bf, name=name) image.size = len(image.bf) image.filetype, image.width, image.height = getImageInfo(bf) image.put() return image
def save_update_db(load_info): latinput = load_info['lat_input'] lnginput = load_info['lng_input'] datepicker = load_info['datepicker'] tipo = load_info['tipo'] notes = load_info['notes'] print('entrou update', latinput, lnginput) newsub = Submission(latinput=latinput, lnginput=lnginput, type_S=tipo, temp=datepicker, notes=notes) db.session.add(newsub) db.session.flush() print('ppppp ', newsub, newsub.id) file_urls = [] image_list = load_info['images'] for k, image in enumerate(image_list): print(allowed_image(image.filename)) if allowed_image(image.filename): ext = image.filename.rsplit(".", 1)[1] new_filename = image.filename.rsplit(".", 1)[0] + '_sub' + str( newsub.id) + '.' + ext filename = photos.save(image, name=new_filename) print('rrr', filename) file_urls.append(photos.url(filename)) newfile = Images(sub=newsub, img_data=image.read(), img_name=new_filename, stamp_save=date.today()) db.session.add(newfile) print('aaaa ', newfile) print(file_urls) db.session.commit() session['images_urls'] = file_urls print('saved to database') return 'Saved to database'
def add_image(request): #last_image_id = Images.objects.order_by('-id')[0].id else last_image_id = 0 form = ImageForm() if request.POST: form = ImageForm(request.POST, request.FILES) if form.is_valid(): image = request.FILES['image_file'] save_image(image) #thumb_image = thumbnail(image) #save_image(thumb_image) p = Images(comment=request.POST['comment'], name = file.name, useragent=request.META['HTTP_USER_AGENT'], ip=request.META['REMOTE_ADDR'], views=0, md5=0 ) p.save() return HttpResponse(image.name) #return render_to_response("forms/add_image.html", {'form': form}) else: return render_to_response("forms/add_image.html", {'form': form}) else: return render_to_response("forms/add_image.html", {'form': form})
def addImage2(bf): image=Images(bf=bf) image.size=len(bf) image.filetype,image.width,image.height=getImageInfo(bf) if not image.filetype:return None image.mime=image.filetype image.put() return image
def get(self, request, *args, **kwargs): conditions = dict(request.query_params) for key, value in conditions.iteritems(): conditions[key] = conditions[key][0] if "number_of_data" in conditions.keys(): number_of_data = conditions["number_of_data"][0] conditions.pop('number_of_data', None) images = MongoConnection.find_lastest_data("Images", conditions, int(number_of_data)) else: images = MongoConnection.find_data("Images", conditions=conditions) serializer = serializers.ImageSerializer( instance=[Images(**element) for element in images], many=True) return Response(serializer.data)
def AddImageByUrlBak(url,fileName,tag): result = urlfetch.fetch(url) if result.status_code == 200: image=Images(description=url,bf=result.content) image.mime=result.headers.get('Content-Type', '') if image.mime.find('image')==-1: return None image.size=len(image.bf) image.name=fileName image.filetype,image.width,image.height=getImageInfo(image.bf) image.tag=tag.split(',') image.put() AddTags(image.tag) return image else: return None
def xmlparse(): #pagecode = urllib.urlopen("http://www.esmadrid.com/opendata/alojamientos_v1_es.xml") pagecode = urllib.urlopen("http://cursosweb.github.io/etc/alojamientos_es.xml") xmlsheet = pagecode.read() noticias=xmlsheet.split("<service ") for noticia in noticias[1:-1]: url = noticia.split("<web>")[1].split("</web>")[0] try: alojamiento = Alojamientos.objects.get(url=url) except Alojamientos.DoesNotExist: name = noticia.split("<name><![CDATA[")[1].split("]]></name>")[0] address = noticia.split("<address>")[1].split("</address>")[0] zipcode = noticia.split("<zipcode>")[1].split("</zipcode>")[0] country = noticia.split("<country>")[1].split("</country>")[0] latitude = noticia.split("<latitude>")[1].split("</latitude>")[0] longitude = noticia.split("<longitude>")[1].split("</longitude>")[0] city = noticia.split("<subAdministrativeArea>")[1].split("</subAdministrativeArea>")[0] alojamiento = Alojamientos(name=name, url=url, address=address, zipcode=zipcode, country=country, latitude=latitude, longitude=longitude, city=city) alojamiento.save() images = noticia.split('<url>') for image in images[1:6]: image_url = image.split('</url>')[0] image = Images(url=image_url, alojamiento=alojamiento) image.save()
def initdb_command(): db.create_all() f = open("static/images.csv", "r") for line in f: images = [x.strip() for x in line.split(',')] if (len(images) != 4): continue db.session.add(Images(images[0], images[1], images[2], images[3])) db.session.commit() print('Initialized the database.')
def addImage(title,bf,referer): 'Add Image' image=Images(description=title,bf=bf,referer=referer) image.size=len(image.bf) image.filetype,image.width,image.height=getImageInfo(bf) if not image.filetype:return None image.mime=image.filetype image.put() return image
def insert_default_entries(db): # Create users for name, email in DEFAULT_USERS_LIST: hashed_password = generate_password_hash(DEFAULT_PASSWORD, method='sha256') u = User(username=name, email=email, password=hashed_password) db.session.add(u) for node in COMPUTE_NODES: default_status = COMPUTE_NODE_STATUS_DICT[0] c = ComputeNode(ip_addr=node[0], compute_node_status=default_status, compute_node_wt=node[1]) db.session.add(c) # Create Images for i, (name, desc, wt) in enumerate(DEFAULT_IMAGES_LIST): im = Images(image_name=name, image_wt=wt, description=desc) db.session.add(im) db.session.commit()
def addImage2(bf): image=Images() image.size=len(bf) image.filetype,image.width,image.height=getImageInfo(bf) if not image.filetype:return None image.mime=image.filetype image.put() imageblob = ImageBlob(image=image, bf=bf) imageblob.put() prependToRSS([image]) return image
def start(self, **post): if post: self._validate_start_post_data(post) creds = cherrypy.session.get('credentials') image = Images.first(id=post['image.id']) instance_type = self._get_instance_type(post) self._validate_start_args(image, instance_type) vm = VirtualMachines.new(status="new") if VirtualMachines.add(vm): if not vm.start_instance(image, instance_type, creds): cherrypy.session['flash'] = 'The virtual machine could not be started.' raise cherrypy.HTTPRedirect("/virtual_machines") else: cherrypy.session['flash'] = 'Missing image id.' raise cherrypy.HTTPRedirect("/virtual_machines")
def get_upload_url(): # query param filename = request.openapi.parameters.query['filename'] content_type = request.openapi.parameters.query['content-type'] # values used for S3 presigned-url file_uuid = str(uuid.uuid4()) stem = path(filename).stem # key is a PurePosixPath object so be mindful it's not a string key = path(UPLOAD_FOLDER, file_uuid) # key = f'{UPLOAD_FOLDER}/{file_uuid}' try: # upload image in database image_record = Images(bucket=BUCKET_NAME, filename=filename, key=str(key)) db.session.add(image_record) db.session.commit() except DBAPIError as db_error: print(f'DB API Error: {db_error.statement}') raise except SQLAlchemyError as alchemy_error: print(f'SQL Alchemy Error: {alchemy_error}') raise # params for s3 put_object method # tag + uuid s3_params = { 'Bucket': BUCKET_NAME, 'Key': f'{key}', 'ContentType': content_type, 'Tagging': f'{stem}={file_uuid}' } url = s3.generate_presigned_url('put_object', Params=s3_params, HttpMethod="PUT", ExpiresIn=10) payload = {'presigned_url': url} return jsonify(payload)
def initdb_command(): db.create_all() paths = { "filetofish.jpg": ["Yes, a filet-o-fish", "Image description here"], "insomnia.jpg": ["Sugar We Are Going Down Swinging", "Image description here"], "jesusisking.jpg": ["Jesus is King", "Image description here"], "lite.jpg": ["Mr. Miller", "Image description here"], "miley.jpg": ["Literally No One:", "Image description here"], "pennstate.jpg": ["How Tough Are You?", "Image description here"], "pizza.jpg": ["A Big Waste of Money", "Image description here"], "pizza2.jpg": ["Where's the Ranch?", "Image description here"], "pumpkin.jpg": ["Smashing Pumkpins", "Image description here"], "rat.jpg": ["Oh Rats", "Image description here"], } for path in paths: db.session.add(Images(path, paths[path][0], paths[path][1])) db.session.commit() print('Initialized the database.')
def post(self): bf = self.request.get("file") if not bf: return self.redirect('/admin/find/') name = self.request.body_file.vars['file'].filename mime = self.request.body_file.vars['file'].headers['content-type'] if mime.find('image') == -1: return self.redirect('/admin/find/') description = descriptor.dhash(bf) images = Images.all().order('-created_at').fetch(30, 0) max = -1 git = None for image in images: if descriptor.compare_hash(image.description, description) > max: max = descriptor.compare_hash(image.description, description) gid = image image = methods.addImage(mime, description, bf, name) template_value = {"git": gid, "simil": max, "image": image} self.render('views/gausshow.html', template_value)
def delImage(key): image=Images.get(key) if image:image.delete()
def delImageByid(id): image=Images.get_by_id(int(id)) if image:image.delete()
def delImageByid(id): image = Images.get_by_id(int(id)) if image: image.delete()
def getAllImages(index=0): return Images.all().order('-created_at').fetch(11, index * 10)
def delImage(key): image=Images.get(key) if image: DelTags(image.tag) image.delete()
def delImageByid(id): image=Images.get_by_id(int(id)) if image: DelTags(image.tag) image.delete()
def getAllImages(index=0): return Images.all().order('-created_at').fetch(25,index*24)
def index(self): #Images.add(Images.new(id="test", name="test")) env = dict( images=Images.all(), ) return self.render("images/index.html", self.crumbs, **env)
def getImage(id): id = int(id) return Images.get_by_id(id)
def delImage(key): image = Images.get(key) if image: image.delete()
def getImage(id): id=int(id) return Images.get_by_id(id)
def getAllImagesByTag(tag): #return db.GqlQuery(u"SELECT * FROM Images WHERE tag=:1",unicode(tag, 'UTF-8')) return Images.all().filter('tag =', unicode(tag, 'UTF-8')).order('-created_at')
def backup(self): images=Images.all().fetch(PAGESIZE) while images: for image in images: self.save(image) images = Images.all().filter('__key__ >', images[-1].key()).fetch(PAGESIZE)