def posts(): sortby = request.args.get('sortby', '') resp = {} data = [] if sortby == 'liked': # 按liked排序 postlist = ImageFile.get_hot(100) else: # 直接查询 postlist = ImageFile.get_all() if not postlist: return jsonify({ 'empty': 'true' }) for index, item in enumerate(postlist): post = {} post['filehash'] = item.filehash post['imgname'] = item.imgname post['nickname'] = item.nickname post['uploadtime'] = item.uploadtime post['liked'] = item.liked post['dorm'] = item.dorm data.append(post) resp['data'] = data return jsonify(resp)
def my(): if request.method == 'GET': # 获取该用户的上传记录 openid = request.args.get('openid', '') imglist = ImageFile.get_by_openid(openid) resp = {} data = [] if not imglist: return jsonify({'empty': 'true'}) else: for index, item in enumerate(imglist): post = {} post['filehash'] = item.filehash post['imgname'] = item.imgname post['uploadtime'] = item.uploadtime post['liked'] = item.liked data.append(post) resp['data'] = data return jsonify(resp) elif request.method == 'POST': # 上传 postname = request.form['postname'] nickname = request.form['nickname'] openid = request.form['openid'] dorm = request.form['dorm'] serverids = request.form.getlist('serverids[]') # logger.info(serverids) for serverid in serverids: url = client.media.get_url(serverid) # logger.info(url) data = client.media.download(serverid) logger.info(data.headers) filename = get_filename_from_header( data.headers['Content-disposition']) image_file = ImageFile.create_by_upload_file( data.content, postname, filename, nickname, openid, dorm) # logger.info(image_file) db.session.add(image_file) db.session.commit() return jsonify({'openid': openid}) elif request.method == 'DELETE': # 删除一条记录 filehash = request.args.get('filehash') choosen_img = ImageFile.get_by_filehash(filehash) try: db.session.delete(choosen_img) os.remove(choosen_img.path) os.remove(choosen_img.nail_path) db.session.commit() return jsonify({'deleted': 'true'}) except: return jsonify({'deleted': 'false'})
def upload_image(request): if request.method == "POST": if request.POST.get('add_button') is not None: errors = {} if not errors: image = ImageFile(name=request.POST['image_name'], category='', likes=0, path=request.FILES['image_path']) image.save() return HttpResponseRedirect(reverse('images')) else: return render(request, 'upload_image.html', {})
def full_page(self, **kwargs): key = kwargs['key'] price_data_operation = kwargs['oper'] property = get_or_404(key) price = property.price_sell cur = property.price_sell_currency if int(price_data_operation) == Property._OPER_RENT: price = property.price_rent cur = property.price_rent_currency context = { 'property': property, 'Property': Property, 'price': price, 'cur': cur, 'config_array': config_array, 'price_data_operation': price_data_operation } context_ex = dict({'form': self.form}, **context) context_ex = dict( { 'images': ImageFile.all().filter('property =', db.Key(key)).order('position') }, **context_ex) return self.render_response('frontend/ficha.html', **context_ex)
def upload(request): # Handle file upload if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): image = ImageFile(imagefile = request.FILES['imagefile']) image.save() return HttpResponseRedirect(reverse('frontpage.views.upload')) else: form = ImageForm() return render_to_response( 'index.html', {'form': form}, context_instance=RequestContext(request) )
def remove(self, keys): fimgs = ImageFile.get(keys) key = fimgs[0].property.key() property = self.mine_or_404(str(key)) # Get all blobkeys blobkeys = [] for fimg in fimgs: # Verifico que sean mias las fotines por 'silas' hacker if not self.has_role('ultraadmin') and str( fimg.realestate.key()) != self.get_realestate_key(): self.abort(500) blobkeys.append(fimg.file.key()) # Delete fileimages db.delete(fimgs) # Delete blobs blobstore.delete(blobkeys) #Update images_count if property.images_count: property.images_count = property.images_count - len(blobkeys) if property.images_count > 0: fi = ImageFile.all().filter( 'property =', property.key()).order('position').get() property.main_image_url = fi.title if fi else None else: property.main_image_url = None else: property.images_count = 0 property.main_image_url = None result = property.save(build_index=False) if result != 'nones': taskqueue.add(url=self.url_for('property/update_index'), params={ 'key': str(property.key()), 'action': result })
def get(self, **kwargs): property = self.mine_or_404(kwargs['key']) images = ImageFile.all().filter('property =', property.key()).order('position') params = { 'current_tab' : 'pictures', 'title' : 'Fotos de la propiedad', 'key' : kwargs['key'], 'mnutop' : 'propiedades', 'images' : images} return self.render_response('backend/includes/pictures.html', **params)
def actions(): action = request.form['action'] logger.info('action: ' + action) if action == 'like': filehash = request.form['filehash'] s = ImageFile.like_handler(filehash) if s: db.session.commit() return jsonify({'liked': 'true'}) else: return jsonify({'liked': 'false'})
def get(self, **kwargs): re = get_or_404(kwargs['key']) blobs = [] imgs = [] props = [] for img in ImageFile.all().filter('realestate', re.key()): blobs.append(img.file.key()) imgs.append(img.key()) blobstore.delete(blobs) db.delete(imgs) props = [] for prop in Property.all().filter('realestate', re.key()): props.append(prop.key()) db.delete(props) pis = [] for pi in PropertyIndex.all().filter('realestate', re.key()): pis.append(pi.key()) db.delete(pis) invs = [] pays = [] for inv in Invoice.all().filter('realestate', re.key()): invs.append(inv) if inv.payment: pays.append(inv.payment.key()) db.delete(invs) db.delete(pays) usrs = [] for usr in User.all().filter('realestate', re.key()): usrs.append(usr) db.delete(usrs) mRealEstateFriendship = [] for fr in RealEstateFriendship.all().filter('realestates', str(re.key())): mRealEstateFriendship.append(fr) db.delete(mRealEstateFriendship) re.delete() self.response.write('borrado %s' % kwargs['key'])
def get(self, **kwargs): key = kwargs['key'] bubble_css = kwargs['bubble_css'] price_data_operation = int(kwargs['oper']) property = get_or_404(key) images = ImageFile.all().filter('property =', db.Key(key)).order('position') context = { 'images': images, 'property': property, 'Property': Property, 'bubble_css': bubble_css, 'price_data_operation': price_data_operation } return self.render_response('frontend/templates/_bubble.html', **context)
def get(self, **kwargs): realestate = get_or_404( self.get_realestate_key_ex(kwargs.get('realestate'))) # Ponemos la pantalla de disabled si esta en NO_PAYMENT if realestate.status == RealEstate._NO_PAYMENT or realestate.plan.allow_website == 0: return self.render_response('realestate/disabled.html', realestate=realestate) kwargs['realestate'] = realestate kwargs['realestate_logo'] = realestate.logo_url key = kwargs['key'] price_data_operation = kwargs['oper'] property = db.get(key) property.visits = property.visits + 1 property.save(build_index=False) price = property.price_sell cur = property.price_sell_currency if int(price_data_operation) == Property._OPER_RENT: price = property.price_rent cur = property.price_rent_currency kwargs['property'] = property kwargs['Property'] = Property kwargs['price'] = price kwargs['cur'] = cur kwargs['config_array'] = config_array kwargs['menu_item'] = 'ficha' kwargs['form'] = self.form kwargs['oper'] = price_data_operation kwargs['images'] = ImageFile.all().filter( 'property =', db.Key(key)).order('position') return self.render_response('realestate/_ficha.html', **kwargs)
def post(self, **kwargs): self.request.charset = 'utf-8' keys = self.request.POST['keys'].split(',') to_save = [] for i,fi in enumerate(ImageFile.get(keys)): fi.position = i+1 # Verifico que sean mias las fotines por 'silas' hacker if not self.has_role('ultraadmin') and str(fi.realestate.key()) != self.get_realestate_key(): self.abort(500) to_save.append(fi) db.save(to_save) property = self.mine_or_404(str(to_save[0].property.key())) property.main_image_url = to_save[0].title property.save(build_index=False) self.response.write('ok')
def get(self, **kwargs): key = kwargs['key'] price_data_operation = kwargs['oper'] property = get_or_404(key) property.visits = property.visits + 1 property.save(build_index=False) price = property.price_sell cur = property.price_sell_currency if int(price_data_operation) == Property._OPER_RENT: price = property.price_rent cur = property.price_rent_currency context = { 'property': property, 'Property': Property, 'price': price, 'cur': cur, 'config_array': config_array, 'price_data_operation': price_data_operation } context_ex = dict({'form': self.form}, **context) context_ex = dict( { 'images': ImageFile.all().filter('property =', db.Key(key)).order('position') }, **context_ex) ficha = self.render_template('frontend/templates/_ficha.html', **context_ex) tab = self.render_template('frontend/templates/_prop_tab.html', **context) return self.render_json_response({'ficha': ficha, 'tab': tab})
def list(request): # Handle file upload if request.method == 'POST': successcount = 0 totalcount = len(request.FILES.getlist('file')) for f in request.FILES.getlist('file'): try: if f.size > 20*1024*1024: return HttpResponseRedirect(reverse('eqnsolver.views.list')) newfile = ImageFile() newfile.original_name = f.name newfile.save() saved_path = os.path.join(unicode(configs.BASE_FILE_PATH), unicode(newfile.id)) saved_path = os.path.realpath(saved_path) handle_uploaded_file(f, saved_path) newfile.real_path = saved_path newfile.save() # notify to redis redis_server.rpush(u"image", unicode(newfile.id) + u"," + unicode(saved_path)) redis_server.publish(u"request", u"image") result_key, result_text = redis_server.blpop(u"result" + unicode(newfile.id)) # some kind of error occurred if result_text is None or len(result_text) == 0: remove_by_object(newfile) continue newfile.parsed = result_text newfile.save() successcount = successcount + 1 except: continue files = ImageFile.objects.all() # Redirect to the file list after POST if successcount == 0: msg_class = 'danger' elif successcount < totalcount: msg_class = 'warning' else: msg_class = 'success' return render_to_response( 'l.html', {'files': files, 'message': 'Processed {} files out of {} files!'.format(successcount, totalcount), 'messageclass': msg_class}, context_instance=RequestContext(request) ) # Load files for the list page files = ImageFile.objects.all() # Render list page return render_to_response( 'l.html', {'files': files}, context_instance=RequestContext(request) )
def get(self, **kwargs): keys = kwargs['keys'] oper = int(kwargs['oper']) if keys is None or len(keys) < 1: abort(404) properties = get_or_404(kwargs['keys'][:-1].split(',')) data = { #'price': {'value':9999999999.9, 'key':'', 'comp':'<'} , 'area_indoor': { 'value': 0.0, 'key': '', 'comp': 'major_than' }, 'area_outdoor': { 'value': 0.0, 'key': '', 'comp': 'major_than' }, 'area_total': { 'value': 0.0, 'key': '', 'comp': 'major_than' }, 'rooms': { 'value': 0, 'key': '', 'comp': 'major_than' }, 'bedrooms': { 'value': 0, 'key': '', 'comp': 'major_than' }, 'bathrooms': { 'value': 0, 'key': '', 'comp': 'major_than' }, 'year_built': { 'value': 9999999999, 'key': '', 'comp': 'minor_than' }, 'prop_state_id': { 'value': 9999999999, 'key': '', 'comp': 'minor_than' } } if int(oper) == Property._OPER_SELL: price_field = 'price_sell' data[price_field] = { 'value': 9999999999.9, 'key': '', 'comp': 'minor_than' } else: price_field = 'price_rent' data[price_field] = { 'value': 9999999999.9, 'key': '', 'comp': 'minor_than' } images = {} for prop in properties: images[str(prop.key())] = ImageFile.all().filter( 'property =', prop.key()).order('position') prop.area_total = prop.area_indoor + prop.area_outdoor for attr in data.keys(): prop_attr_value = getattr(prop, attr) if getattr(self, data[attr]['comp'])(prop_attr_value, data[attr]['value']): #data[attr]['key'] = str(prop.key()) data[attr]['value'] = prop_attr_value data['price'] = data[price_field] comp_key = str(time.time()).replace('.', '') compare = self.render_template( 'frontend/compare.html', properties=properties, images=images, data=data, operation=oper, price_field=price_field, config_array=config_array, extra_fields=sorted( config_array['binary_values_properties'], key=config_array['binary_values_properties'].get, reverse=False), comp_key=comp_key, Property=Property) tab = self.render_template('frontend/templates/_compare_tab.html', comp_key=comp_key) return self.render_json_response({'compare': compare, 'tab': tab})
def list(request): # Handle file upload if request.method == 'POST': successcount = 0 totalcount = len(request.FILES.getlist('file')) for f in request.FILES.getlist('file'): try: if f.size > 20 * 1024 * 1024: return HttpResponseRedirect( reverse('eqnsolver.views.list')) newfile = ImageFile() newfile.original_name = f.name newfile.save() saved_path = os.path.join(unicode(configs.BASE_FILE_PATH), unicode(newfile.id)) saved_path = os.path.realpath(saved_path) handle_uploaded_file(f, saved_path) newfile.real_path = saved_path newfile.save() # notify to redis redis_server.rpush( u"image", unicode(newfile.id) + u"," + unicode(saved_path)) redis_server.publish(u"request", u"image") result_key, result_text = redis_server.blpop( u"result" + unicode(newfile.id)) # some kind of error occurred if result_text is None or len(result_text) == 0: remove_by_object(newfile) continue newfile.parsed = result_text newfile.save() successcount = successcount + 1 except: continue files = ImageFile.objects.all() # Redirect to the file list after POST if successcount == 0: msg_class = 'danger' elif successcount < totalcount: msg_class = 'warning' else: msg_class = 'success' return render_to_response('l.html', { 'files': files, 'message': 'Processed {} files out of {} files!'.format( successcount, totalcount), 'messageclass': msg_class }, context_instance=RequestContext(request)) # Load files for the list page files = ImageFile.objects.all() # Render list page return render_to_response('l.html', {'files': files}, context_instance=RequestContext(request))
def post(self, **kwargs): self.request.charset = 'utf-8' # Todo esto es para recuperar la session en funcion de un parametro del post # que nos manda el flash swfupload cookie_name = self.app.config['webapp2_extras.sessions']['cookie_name'] secret_key = self.app.config['webapp2_extras.sessions']['secret_key'] raw_data = str(self.request.POST[cookie_name]) if raw_data[0] == "\"" and raw_data[-1] == "\"": raw_data = raw_data[1:][:-1] # ALTO HACK: no se por que carajo no funcion el urllib.unquote raw_data = raw_data.decode('string_escape') self.session = SecureCookieSerializer(secret_key).deserialize(cookie_name, raw_data) # Hacemos lo que hacia el decorator if not self.is_logged: self.abort(500) property = self.mine_or_404(kwargs['key']) fs = self.request.POST['file'] # Create the file file_name = files.blobstore.create(mime_type='image/jpg', _blobinfo_uploaded_filename=fs.filename) # Open the file and write to it img = images.Image(fs.file.getvalue()) img.resize(width=800, height=600) with files.open(file_name, 'a') as f: f.write(img.execute_transforms(output_encoding=images.JPEG, quality=70)) # Finalize the file. Do this before attempting to read it. files.finalize(file_name) # Get the file's blob key blob_key = files.blobstore.get_blob_key(file_name) # ------ BEGIN HACK -------- # # GAE BUG => http://code.google.com/p/googleappengine/issues/detail?id=5142 for i in range(1,10): if not blob_key: time.sleep(0.05) blob_key = files.blobstore.get_blob_key(file_name) else: break if not blob_key: logging.error("no pude obtener el blob_key, hay un leak en el blobstore!") abort(500) # ------ END HACK -------- # imgfile = ImageFile() imgfile.title = get_serving_url(blob_key) imgfile.file = blob_key imgfile.filename = fs.filename imgfile.realestate= property.realestate.key() imgfile.property = db.Key(encoded=kwargs['key']) imgfile.put() #Update property if property.images_count: property.images_count = property.images_count + 1 else: property.images_count = 1 property.main_image_url = imgfile.title result = property.save(build_index=False) # HACK: No mandamos a regenerar el PropertyIndex #if result != 'nones': # taskqueue.add(url=self.url_for('property/update_index'), params={'key': str(property.key()),'action':result}) return self.render_response('backend/includes/img_box.html', image=imgfile)