def receive(): data = request.data data = xmltodict.parse(data)['xml'] if data['MsgType'] == 'text': return send_text(data['FromUserName'], 'hi') if data['MsgType'] == 'image': token = current_access_token() file_url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s' % (token, data['MediaId']) file = requests.get(file_url, stream=True).raw i = Image() i.image = file uuid = shortuuid.ShortUUID().random(length=6) while Image.objects(iid=uuid): uuid = shortuuid.ShortUUID().random(length=6) i.iid = uuid i.title = data['MediaId'] i.user = system_user i.description = '' i.tags = [] i.save() return send_text( data['FromUserName'], '업로드 성공, 사진주소:%s%s' % ( request.url_root[:-1], url_for('light-cms.image', iid=i.iid) ) )
def post(self): "Upload via a multitype POST message" img = self.request.get("img") # if we don't have image data we'll quit now if not img: self.redirect("/") return try: width = int(self.request.get("width")) hight = int(self.request.get("height")) except ValueError: image_content = img else: image_content = images.resize(img, width, height) original_content = img thumb_content = images.resize(img, 100, 100) image = Image() image.image = db.Blob(image_content) image.original = db.Blob(original_content) image.thumb = db.Blob(thumb_content) image.user = users.get_current_user() image.put() self.redirect("/")
def upload(): with open('data.csv') as f: reader = csv.DictReader(f) for row in reader: try: s = Store() print row['name'], row['images'], row['types'] if re.search("\[.*\]", row['reference']): row['place_id'] = row['scope'] row['scope'] = row['latlng'] row['latlng'] = row['address'] row['address'] = row['photos'] row['photos'] = row['reference'] print row['name'], row['images'], row['types'] s.tags = json.loads(row['types']) s.point = db.GeoPt(*eval(row['latlng'])) s.reference = row['reference'] and row['reference'][0] or "" s.address = row['address'] s.name = row['name'] for img in eval(row['images']): image = Image() image.image = img image.put() s.imgs.append(image) except Exception as e: pass finally: s.put()
def post(self): "Upload via a multitype POST message" if self.request.get('img'): try: # check we have numerical width and height values width = int(self.request.get("width")) height = int(self.request.get("height")) except ValueError: # if we don't have valid width and height values # then just use the original image image_content = google.appengine.api.images.resize(self.request.get("img"), IMAGE_WIDTH, IMAGE_HEIGHT) thumb_content = google.appengine.api.images.resize(self.request.get("img"), 100, 100) else: # if we have valid width and height values # then resize according to those values image_content = google.appengine.api.images.resize(self.request.get("img"), width, height) # always generate a thumbnail for use on the admin page thumb_content = google.appengine.api.images.resize(self.request.get("img"), 100, 100) else: image_content = None if not self.request.get('key'): logging.critical('No key and no image! Cannot save image.') return self.redirect('/admin') # check if image is being edited if self.request.get('key'): image = db.get(self.request.get("key")) if self.request.get('position'): import datetime position = int(self.request.get('position')) images = imageQuery().fetch(100) offset_image = images.pop(position- 1) if position == 1: time_offset = -datetime.timedelta(milliseconds=10) else: time_offset = datetime.timedelta(milliseconds=10) if not offset_image.key() == image.key(): image.date = offset_image.date + time_offset else: # create the image object image = Image() image.user = users.get_current_user() image.title = self.request.get('title') if image_content: # and set the properties to the relevant values image.image = db.Blob(image_content) # we always store the original here in case of errors # although it's currently not exposed via the frontend image.thumb = db.Blob(thumb_content) # store the image in the datasore image.put() # and redirect back to the admin page self.redirect('/admin')
def multiuploader(request): if request.method == 'POST': log.info('received POST to main multiuploader view') if request.FILES == None: return HttpResponseBadRequest('Must have files attached!') #getting file data for farther manipulations file = request.FILES[u'files[]'] wrapped_file = UploadedFile(file) filename = wrapped_file.name file_size = wrapped_file.file.size log.info('Got file: "' + str(filename) + '"') #writing file manually into model #because we don't need form of any type. image = Image() image.title = str(filename) image.image = file image.save() log.info('File saving done') #getting url for photo deletion file_delete_url = '/delete/' #getting file url here file_url = '/' #getting thumbnail url using sorl-thumbnail im = get_thumbnail(image, "80x80", quality=50) thumb_url = im.url #generating json response array result = [] result.append({ "name": filename, "size": file_size, "url": file_url, "thumbnail_url": thumb_url, "delete_url": file_delete_url + str(image.pk) + '/', "delete_type": "POST", }) response_data = simplejson.dumps(result) return HttpResponse(response_data, content_type='application/json') else: #GET return render_to_response( 'multiuploader_main.html', { 'static_url': settings.MEDIA_URL, 'open_tv': u'{{', 'close_tv': u'}}' }, )
def post(self): "Upload via a multitype POST message" try: # check we have numerical width and height values width = int(self.request.get("width")) height = int(self.request.get("height")) except ValueError: # if we don't have valid width and height values # then just use the original image image_content = self.request.get("img") else: # if we have valid width and height values # then resize according to those values image_content = images.resize(self.request.get("img"), width, height) # get the image data from the form original_content = self.request.get("img") # always generate a thumbnail for use on the admin page thumb_content = images.resize(self.request.get("img"), 100, 100) # create the image object image = Image() # Try and create an s3 connection if len(awskeys.AWS_ACCESS_KEY_ID) > 0 and len(awskeys.AWS_SECRET_ACCESS_KEY) > 0: s3 = GoogleS3.AWSAuthConnection(awskeys.AWS_ACCESS_KEY_ID, awskeys.AWS_SECRET_ACCESS_KEY) else: s3 = None # and set the properties to the relevant values image.image = db.Blob(image_content) image.user = users.get_current_user() if s3 is None: # we always store the original here in case of errors # although it's currently not exposed via the frontend image.original = db.Blob(original_content) image.thumb = db.Blob(thumb_content) # store the image in the datasore image.put() else: # we want to store in S3, so store the data and use the key image.put() # Put the 3 different images s3.put(awskeys.BUCKET_NAME,str(image.key()) + "_original",original_content) s3.put(awskeys.BUCKET_NAME,str(image.key()) + "_thumb",thumb_content) s3.put(awskeys.BUCKET_NAME,str(image.key()) + "_image",image_content) # and redirect back to the admin page self.redirect('/')
def multiuploader(request): if request.method == 'POST': log.info('received POST to main multiuploader view') if request.FILES == None: return HttpResponseBadRequest('Must have files attached!') #getting file data for farther manipulations file = request.FILES[u'files[]'] wrapped_file = UploadedFile(file) filename = wrapped_file.name file_size = wrapped_file.file.size log.info ('Got file: "'+str(filename)+'"') #writing file manually into model #because we don't need form of any type. image = Image() image.title=str(filename) image.image=file image.save() log.info('File saving done') #getting url for photo deletion file_delete_url = '/delete/' #getting file url here file_url = '/' #getting thumbnail url using sorl-thumbnail im = get_thumbnail(image, "80x80", quality=50) thumb_url = im.url #generating json response array result = [] result.append({"name":filename, "size":file_size, "url":file_url, "thumbnail_url":thumb_url, "delete_url":file_delete_url+str(image.pk)+'/', "delete_type":"POST",}) response_data = simplejson.dumps(result) return HttpResponse(response_data, mimetype='application/json') else: #GET return render_to_response('multiuploader_main.html', {'static_url':settings.MEDIA_URL, 'open_tv':u'{{', 'close_tv':u'}}'}, )
def drop(): file = request.files['file'] i = Image() i.title = file.filename i.image = file uuid = shortuuid.ShortUUID().random(length=6) while Image.objects(iid=uuid): uuid = shortuuid.ShortUUID().random(length=6) i.iid = uuid if login.current_user.is_active(): i.user = login.current_user._get_current_object() else: i.user = system_user i.description = '' i.tags = [] i.save() return jsonify(id=uuid)
def gallery_drop(gid): if not login.current_user.is_active(): flash('앨범기능엔 로그인이 필요합니다') return redirect(url_for('light-cms.user_login')) g = Gallery.objects.get_or_404(gid=gid) file = request.files['file'] i = Image() i.gallery.append(g) i.title = file.filename i.image = file uuid = shortuuid.ShortUUID().random(length=6) while Image.objects(iid=uuid): uuid = shortuuid.ShortUUID().random(length=6) i.iid = uuid i.user = login.current_user._get_current_object() i.description = '' i.tags = [] i.save() return jsonify(id=uuid)
def gallery_drop(gid): if not login.current_user.is_active(): flash('请登录后再搞相册哦~') return redirect(url_for('light-cms.user_login')) g = Gallery.objects.get_or_404(gid=gid) file = request.files['file'] i = Image() i.gallery.append(g) i.title = file.filename i.image = file uuid = shortuuid.ShortUUID().random(length=6) while Image.objects(iid=uuid): uuid = shortuuid.ShortUUID().random(length=6) i.iid = uuid i.user = login.current_user._get_current_object() i.description = '' i.tags = [] i.save() return jsonify(id=uuid)
def post(self): "Upload via a multitype POST message" img = self.request.get("img") # if we don't have image data we'll quit now if not img: self.redirect('/') return # we have image data try: # check we have numerical width and height values width = int(self.request.get("width")) height = int(self.request.get("height")) except ValueError: # if we don't have valid width and height values # then just use the original image image_content = img else: # if we have valid width and height values # then resize according to those values image_content = images.resize(img, width, height) # get the image data from the form original_content = img # always generate a thumbnail for use on the admin page thumb_content = images.resize(img, 100, 100) # create the image object image = Image() # and set the properties to the relevant values image.image = db.Blob(image_content) # we always store the original here in case of errors # although it's currently not exposed via the frontend image.original = db.Blob(original_content) image.thumb = db.Blob(thumb_content) image.user = users.get_current_user() # store the image in the datasore image.put() # and redirect back to the admin page self.redirect('/')
def post(self, key): checkkey = UploadRequestKeys.get(key) if not checkkey: self.error(404) if checkkey.expire_date < datetime.now(): self.error(404) img = self.request.get("img") # if we don't have image data we'll quit now if not img: return None try: width = int(self.request.get("width")) hight = int(self.request.get("height")) except ValueError: image_content = img else: image_content = images.resize(img, width, height) original_content = img thumb_content = images.resize(img, 100, 100) image = Image() image.image = db.Blob(image_content) image.original = db.Blob(original_content) image.thumb = db.Blob(thumb_content) image.user = users.get_current_user() image.realm = RealmKeys.get(checkkey.realm_key) image.put() checkkey.delete() # self.response.out.write(simplejson.dumps({'img_url'::})) context = { "image": True, "img_url": "http://org-images.appspot.com/i/img?id=%s" % image.key(), "thumb_url": "http://org-images.appspot.com/i/thumb?id=%s" % image.key(), } path = os.path.join(os.path.dirname(__file__), "templates", "show_links.html") # render the template with the provided context self.response.out.write(template.render(path, context))
def upload_image(request): """ Handles image uploads and assigns them to the correct user. Resizes the image before uploading. The uploaded image's URL is in the HTTP header (Location) """ if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): img = Image() img.user = request.user img.note_id = form.cleaned_data['note'] img.image = form.cleaned_data['image'] img.save() # Build a response response = HttpResponse(status=201) response['Location'] = img.image.url.replace(settings.AWS_MEDIA_URL,settings.MEDIA_URL,1) return response else: return HttpResponse(status=400) return HttpResponseForbidden()
def query_image(exp): # Build a service object for interacting with the API. Visit # the Google APIs Console <http://code.google.com/apis/console> # to get an API key for your own application. service = build("customsearch", "v1", developerKey="AIzaSyCDlCGXWMJa4JPsbT1r0gJQPbCMo-RpwE4") # https://developers.google.com/custom-search/json-api/v1/reference/cse/list res = service.cse().list( q=exp, cx='008947772147471846402:fdhywbjbitw', num=4, searchType="image", imgColorType='color', imgType='photo', safe='high', rights='cc_publicdomain', filter='1' ).execute() parsed_res = json.dumps(res) json_res = json.loads(parsed_res) items = [] for i in range(4): img_url = json_res['items'][i]['link'] img = Image() f = "" try: f = urllib2.urlopen(img_url).read() # Opens the url as an image file so we can store it! except urllib2.HTTPError, e: print "There was an http error with url: "+img_url print e # TODO: Figure out how to best preserve quality while resizing if f: op_img = images.Image(f) op_img.resize(width=256, height=256, crop_to_fit=False) small_img = op_img.execute_transforms(output_encoding=images.JPEG) img.image = small_img img_id = img.put() items.append(ImageMessage(image_url="getgimage?id="+img_id.urlsafe()))
def upload_image(request): """ Handles image uploads and assigns them to the correct user. Resizes the image before uploading. The uploaded image's URL is in the HTTP header (Location) """ if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): img = Image() img.user = request.user img.note_id = form.cleaned_data['note'] img.image = form.cleaned_data['image'] img.save() # Build a response response = HttpResponse(status=201) response['Location'] = img.image.url.replace( settings.AWS_MEDIA_URL, settings.MEDIA_URL, 1) return response else: return HttpResponse(status=400) return HttpResponseForbidden()
def receive(): data = request.data data = xmltodict.parse(data)['xml'] if data['MsgType'] == 'text': return send_text(data['FromUserName'], 'hi') if data['MsgType'] == 'image': token = current_access_token() file_url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s' % ( token, data['MediaId']) file = requests.get(file_url, stream=True).raw i = Image() i.image = file uuid = shortuuid.ShortUUID().random(length=6) while Image.objects(iid=uuid): uuid = shortuuid.ShortUUID().random(length=6) i.iid = uuid i.title = data['MediaId'] i.user = system_user i.description = '' i.tags = [] i.save() return send_text( data['FromUserName'], '上传成功!图片地址:%s%s' % (request.url_root[:-1], url_for('light-cms.image', iid=i.iid)))
def post(self): # Grab album from url urlstring = self.request.POST['album'] album_key = ndb.Key(urlsafe=urlstring) album = album_key.get() # Check whether we're storing a album or a Question if self.request.GET['album'] == '1': album.title = self.request.POST['albumTitle'] album.category = self.request.POST['categoryTitle'] album.put() time.sleep(0.1) # Save album and redirect to edit if the user clicks on 'Save and continue editing' # Else, save album and go back to the main page which lists all albums if self.request.POST.get('stay') == '1': self.redirect('/edit?album=1&id='+urlstring) else: if album.album_type == 'match': self.redirect('/match') elif album.album_type == 'correlate': self.redirect('/correlate') else: self.redirect('/oddmanout') else: # Create Question with the album as parent for strong consistency question = "" new = "1" if self.request.POST['question'] == "": question = Question(parent=album_key) question.question_id = question.put().id() else: new = "0" question_url = self.request.POST['question'] question_key = ndb.Key(urlsafe=question_url) question = question_key.get() question.title = self.request.get('title') question.fact = self.request.get('fact') question.effect = self.request.get('revealEffect') question.difficulty = self.request.get('difficulty') # Create answer choices answer = int(self.request.get('correct_answer')) input_images = self.request.get('image', allow_multiple=True) num_images = 4 if album.album_type == 'correlate': num_images = 5 image_list = [] for i in range(num_images): img = "" input_img = input_images[i] # If old retrieve the Image if new == "0": img = question.images[i] else: img = Image() # Resize image if input_img: op_img = images.Image(input_img) op_img.resize(width=256, height=256, crop_to_fit=True) result_img = op_img.execute_transforms(output_encoding=images.JPEG) img.image = result_img # Set the title and correct fields if answer == i: img.title = "correct_answer_"+str(i) img.correct = True elif num_images == 5 and i == 0: # This is if the album is of type Correlate img.title = "main_image_"+str(i) img.correct = False else: img.title = "incorrect_answer_"+str(i) img.correct = False # If old Question, free up the old Image and put in new Image if new == "0": question.images.pop(i) question.images.insert(i, img) else: question.images.append(img) question.put() # Query all Question(s) for the album in recently added order for /create # Retrieve previously input values, and indicate whether this is a new album (edit) questions = Question.query(ancestor=album_key).order(-Question.date).fetch() retrieve = 1 edit = self.request.GET['edit'] template_values = { 'album': album, 'album_type': album.album_type, 'questions': questions, 'edit': edit, 'retrieve': retrieve } template = JINJA_ENVIRONMENT.get_template('create.html') self.response.write(template.render(template_values))
def experiance(request): #print "cook ----->", request.COOKIES request.session.save() #print "session ---->", request.session.session_key if not os.path.isdir("media/tmp/" + str(request.session.session_key)): os.mkdir("media/tmp/" + str(request.session.session_key), 0755) path = "media/tmp/" + str(request.session.session_key) print 'fichier cree --->', path else: path = "media/tmp/" + str(request.session.session_key) print 'le fichier existe ----->', path valid = False if request.POST: form = NewImage(request.POST, request.FILES) if form.is_valid(): img = Image() img.image = request.FILES['image'] img.save() visage = plt.imread("media/" + str(img.image.name)) #return render(request, 'debug.html', locals()) dim_false = False if visage.shape[0] != 124 or visage.shape[1] != 92: dim_false = True dimention_invalid = "Velliez séléctionnez une image de dimention 124x92 pixel" return render(request, 'experementation.html', locals()) database = rec.reconnaissance("media/Database", path) cv2.imwrite(path + "/moy.jpg", np.flipud(database.visage_moyen.reshape(124, -1))) #print img.image.url #print str(img.image.name) #print "media/"+str(img.image.name) #lecture de la photo uploader if visage.shape[2] >= 3: visage = cv2.cvtColor(visage, cv2.COLOR_BGR2GRAY) visage = cv2.equalizeHist(visage) cv2.imwrite(path + "/photo.jpg", np.flipud(visage)) img.delete_() vis = False #detection des visage dans la photo uploader #print database.norm.shape diff = (visage.ravel() - database.visage_moyen.ravel()) #print type(diff) #print diff.shape omega_new = np.array(np.dot(database.norm.transpose(), diff)) #print 'omega_new\n', omega_new.shape #print 'omega', database.omega.shape database.__reconnaitre__(omega_new, path) if database.__recontruction__(omega_new, path): visage_trouve = True else: visage_trouve = False np.savetxt(path + "/faces.txt", database.faces, fmt='%i') np.savetxt(path + "/mean_face.txt", database.visage_moyen, fmt='%i') np.savetxt(path + "/ecart_face.txt", database.ecart_face, fmt='%i') valid = True #print 'Valid form' else: form = NewImage() return render(request, 'experementation.html', locals())
def post(self): # Grab album from url urlstring = self.request.POST['album'] album_key = ndb.Key(urlsafe=urlstring) album = album_key.get() # Check whether we're storing a album or a Question if self.request.GET['album'] == '1': album.title = self.request.POST['albumTitle'] album.category = self.request.POST['categoryTitle'] album.put() time.sleep(0.1) # Save album and redirect to edit if the user clicks on 'Save and continue editing' # Else, save album and go back to the main page which lists all albums if self.request.POST.get('stay') == '1': self.redirect('/edit?album=1&id=' + urlstring) else: if album.album_type == 'match': self.redirect('/match') elif album.album_type == 'correlate': self.redirect('/correlate') else: self.redirect('/oddmanout') else: # Create Question with the album as parent for strong consistency question = "" new = "1" if self.request.POST['question'] == "": question = Question(parent=album_key) question.question_id = question.put().id() else: new = "0" question_url = self.request.POST['question'] question_key = ndb.Key(urlsafe=question_url) question = question_key.get() question.title = self.request.get('title') question.fact = self.request.get('fact') question.effect = self.request.get('revealEffect') question.difficulty = self.request.get('difficulty') # Create answer choices answer = int(self.request.get('correct_answer')) input_images = self.request.get('image', allow_multiple=True) num_images = 4 if album.album_type == 'correlate': num_images = 5 image_list = [] for i in range(num_images): img = "" input_img = input_images[i] # If old retrieve the Image if new == "0": img = question.images[i] else: img = Image() # Resize image if input_img: op_img = images.Image(input_img) op_img.resize(width=256, height=256, crop_to_fit=True) result_img = op_img.execute_transforms( output_encoding=images.JPEG) img.image = result_img # Set the title and correct fields if answer == i: img.title = "correct_answer_" + str(i) img.correct = True elif num_images == 5 and i == 0: # This is if the album is of type Correlate img.title = "main_image_" + str(i) img.correct = False else: img.title = "incorrect_answer_" + str(i) img.correct = False # If old Question, free up the old Image and put in new Image if new == "0": question.images.pop(i) question.images.insert(i, img) else: question.images.append(img) question.put() # Query all Question(s) for the album in recently added order for /create # Retrieve previously input values, and indicate whether this is a new album (edit) questions = Question.query( ancestor=album_key).order(-Question.date).fetch() retrieve = 1 edit = self.request.GET['edit'] template_values = { 'album': album, 'album_type': album.album_type, 'questions': questions, 'edit': edit, 'retrieve': retrieve } template = JINJA_ENVIRONMENT.get_template('create.html') self.response.write(template.render(template_values))