Example #1
0
def user_add():
	import bcrypt
	PostForm = model_form(User)
	form = PostForm(request.form)
	if request.method == 'POST': #and form.validate():
		#the following is described in flask-uploads documentation
		filename = "" #store blank photo filename
		#initialize default user photo
		i = Image(image_path = 'default_image', is_profile=True) 
		if 'photo' in request.files:
			filename = photos.save(request.files['photo'])
			i = Image(image_path = filename, is_profile=True)
			flash("Photo saved.")
		i.save()
		#hash password stored in database so that it is not viewable by people in Romania
		hashed = bcrypt.hashpw(request.form["password"], bcrypt.gensalt())
		u = User(	email = request.form["email"], 
					first_name = request.form["first_name"], 
					last_name =request.form["last_name"], 
					password = hashed, 
					authenticated = False,
					philosophy = request.form['philosophy'],
					tags = request.form['tags'].split(','),
				)
		u.profile_picture= i
		u.save()
		return "done:" + request.form["email"] + " " + request.form["first_name"]+ " " + request.form["last_name"] + " " + '/_uploads/photos/'+i.image_path
	else:
		return render_template('add.html', form=form, cities = OccupyCity.objects.all())
Example #2
0
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()
Example #3
0
def create_tables():
    from models import Image, Imageuri, ImageFragment, Metadata, Annotation
    Image.create_table()
    Imageuri.create_table()
    ImageFragment.create_table()
    Metadata.create_table()
    Annotation.create_table()
Example #4
0
    def post(self, user, account, group_id):
        group = get_image_group_or_404(self, group_id)

        # FIXME: admins!
        if group.owner.key() != account.key():
            return render_json_response(self, {"error": "access-denied"})

        file_name = self.request.headers["X-File-Name"]
        data = self.request.body

        mime_type = mimetypes.guess_type(file_name)[0]
        if not mime_type.startswith("image/"):
            return render_json_response(self, {"error": "wrong-file-type"})

        img = images.Image(data)

        imgdata = ImageData(data=data)
        imgdata.put()

        image = Image(
            file_name=file_name,
            width=img.width,
            height=img.height,
            mime_type=mime_type,
            group=group,
            data=imgdata,
            digest=hashlib.sha1(data).hexdigest(),
        )
        image.put()

        memcache.delete(group.memcache_key())

        return render_json_response(self, {"name": image.file_name})
Example #5
0
def transfer_s3_structure_to_db(name, path, parent_directory, is_dir=False):
    if parent_directory is not None:
        par_dir = Directory.get(Directory.key == parent_directory)
    else:
        par_dir = FakeDirectory()
        par_dir.id = None
    if is_dir:
        try:
            Directory.get(Directory.key == path)
            return False
        except DoesNotExist:
            Directory.create(
                name = name,
                key = path,
                parent_directory = par_dir.id
            )
            return True
    else:
        try:
            Image.get(Image.key == path)
            return False
        except DoesNotExist:
            Image.create(
                name = name,
                key = path,
                directory = par_dir.id
            )
            return True
Example #6
0
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)
            )
        )
Example #7
0
    def get(self, hash, extension=None):
        q = Album.all().filter('hash =', hash)
        album = q.get()
        if album:
            if extension:
                return self.error(404)
            
            q = Image.all().filter('album =', album)
            return self.response.out.write(render_template('album.html', {
                'name': album.name,
                'images': q,
            }))

        q = Image.all().filter('hash =', hash)
        image = q.get()
        if image:
            if not extension:
                return self.response.out.write(render_template('image.html',
                    { 'image': image }))
            elif image.extension == extension:
                return write_image(self, image.image_data, extension)
            else:
                return self.error(404)
        
        return self.error(404)
Example #8
0
def upload_image_for_match(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            #title
            tit = request.REQUEST.get("title", None)
            
            #Sensor
            lon = request.REQUEST.get('longitude', None)
            lat = request.REQUEST.get('latitude', None)
            azi = request.REQUEST.get("azimuth", None)
            pit = request.REQUEST.get("pitch", None)
            rol = request.REQUEST.get("roll", None)
            
            #Image
            image = Image(image_path = request.FILES['file'],
                          azimuth = azi,
                          pitch = pit,
                          roll = rol,
                          longitude = lon,
                          latitude = lat,
                          title = tit)
            image.save()
            
            '''match the image against the database'''
            name = image.match()
            obj = Object.objects.get(object_name = name)
            
            #wrap object_url and object_name as json and return
            return responseJson({'object_url':obj.img_path.name, 'object':obj.object_name})
            
        else:
            return fail()
    else:
        return fail()
Example #9
0
 def post(self):
     if not setup_occurred():
         Status.load_defaults()
         Image.load_defaults()
         api.invalidate_cache()
         finish_setup()
     self.redirect("/admin")
Example #10
0
 def test_create_image(self):
     i = Image(slug="broom", icon_set="fugue", path="icons/fugue/broom.png")
     i.put()
     self.assertEquals(i.slug, "broom")
     self.assertEquals(i.icon_set, "fugue")
     self.assertEquals(i.path, "icons/fugue/broom.png")
     self.assertEquals(i.absolute_url(), "/images/icons/fugue/broom.png")
Example #11
0
def upload():
    form = UploadForm()
    if form.validate_on_submit():
        try:
            name = form.name.data
            filename = images.save(form.image.data, folder=unicode(g.user.id))

            #Checks if Image is new or exists before commit changes
            image = Image.query.filter_by(name = form.name.data).first()
	    if image is None:
                image = Image(name = name, filename = filename, uid=g.user.id)
                message = "%r image uploaded." % name
            else:
                old_file = image.filename
                image.filename = filename
                message = "%r image changed." % name

            db.session.add(image)
            db.session.commit()

            flash(message)
            return redirect(url_for('index'))
        except UploadNotAllowed:
            flash("Not allowed to upload image")
    else:
        filename = None

    return render_template('upload.html',
        form = form,
        filename = filename)
 def get_contents(self):
     db_id = Directory.get(Directory.key == self.key).id
     directories = Directory.select().where(Directory.parent_directory == db_id)
     has_probes = False
     try:
         has_probes = Directory.get(Directory.key == directories
                             .first().key).images.first()
     except:
         pass
     if has_probes:
         directories = [DirectoryTree(d.name, d.key).get_contents() for d in directories]
         self.directories = [d.serialized for d in directories]
     else:
         self.directories = [DirectoryTree(d.name, d.key).serialized for d in directories]
     self.images = [image.serialized for image in Image.select().where(Image.directory == db_id)]
     if self.images:
         stack_title = self.key[:-1]
         try:
             stack_id = Stack.get(Stack.title == stack_title).id
         except models.DoesNotExist:
             images = Image.select().where(Image.directory == db_id)
             stack = models.Stack.create(title=stack_title)
             for image in images:
                 try:
                     models.StackImage.create(stack=stack, image = image.id)
                 except Exception as ex:
                     print ex
             stack_id = stack.id
         self.stack_id = stack_id
     return self
Example #13
0
 def setUp(self):
     super(StatusInstanceTest, self).setUp()
     image = Image(icon_set="fugue", slug="cross-circle",
                   path="fugue/cross-circle.png")
     image.put()
     self.status = Status(name="Foo", slug="foo", description="bar", 
         image="cross-circle")
     self.status.put()
Example #14
0
    def test_add(self):
        from models import Image
        Image.add(name="Hallo.img")

        img = Image.by_id(1)
        self.assertEqual(1, img.id)
        self.assertEqual("Hallo.img", img.name)
        self.assertEqual("hallo.img", img.route)
Example #15
0
    def post(self):
        album_key = ndb.Key(urlsafe=self.request.get('key'))
        upload_files = self.get_uploads()  # 'file' is file upload field in the form
        blob_info = upload_files[0]
        photo = Image(parent=album_key, image_blob=blob_info.key(), index=1)
        photo.populate(serving_url=images.get_serving_url(blob_info.key()))
        photo.put()

        self.redirect('/add-album?key=%s' % album_key.urlsafe())
Example #16
0
def gallery(id=None):
    # Get gallery images associated with feed #id
    if id is None:
        images = Image.select()
    else:
        images = Image.select().where(Feed.id == id).paginate(1, 50)

    return render_template("gallery.html",
                           images=images)
    def execute(self):
        image = Image()
        image.image_key = self.image_key
        image.put()

        invite = Invite.get_by_unique_id(self.unique_id)
        invite.poster_picture = image.key
        invite.put()
        return invite.poster_picture.urlsafe()
Example #18
0
 def create_image(self,request):
     u = self.current_user(request)
     if 'description' in request.POST:
         image = list(Image.objects.filter(user=u))[-1:][0]
         descr = request.POST['description']
         image.description = descr
         image.save()
         return response('Description added to image successfully')
     i = Image(link=self.upload_image(request),user=u)
     i.save()
     return response('Image created successfully')
Example #19
0
    def post(self):
        " Post to blobstore, create Image object and redirect to info URL. "
        upload_files = self.get_uploads("file")
        blob_info = upload_files[0]

        img = Image(title=self.request.POST.get("title", ""), image=blob_info)
        img.put()

        upload_url = urllib.quote(blobstore.create_upload_url("/%s/upload" % IMAGE_APP_PATH))
        self.response.set_status(303)
        self.redirect("/%s/upload?key=%s&newurl=%s" % (IMAGE_APP_PATH, urllib.quote(str(img.key())), upload_url))
Example #20
0
def save_image(file):
    filename = file.filename
    imagedata = file.read()
    shorturl = hash_link()
    ext = get_ext(filename)
    cur_date = str(datetime.now())
    mimetype = mimetypes.types_map["." + ext]
    image = Image(
        filename=filename, image=db.Blob(imagedata), shorturl=shorturl, ext=ext, mimetype=mimetype, dateadded=cur_date
    )
    image.put()
    return shorturl
Example #21
0
 def put_image(self, submitter, url, tags):
     DEBUG('put_image: %s (%s)' % (url, tags))
     exists = self.get_image_by_url(url)
     ltags = [tag.lower() for tag in tags]
     if exists:
         DEBUG('found existing %s' % img)
         for image in exists:
             image.tags.extend([tag for tag in ltags if tag not in image.tags])
             image.put()
     else:
         image = Image(url=url, tags=ltags, submitter=submitter)
         image.put()
Example #22
0
 def post(self,subdomain=None):
     product_id=self.request.get("product_id")
     upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
     blob_info = upload_files[0]  
     for i in range(0,5):
         count = Image.gql("WHERE __key__=KEY('Image','%s-%s') LIMIT 1" % (product_id,i)).count()
         if count == 0:
             image = Image(blob_key=str(blob_info.key()),key_name='%s-%s' %(product_id, i),user=subdomain)
             image.put()
             self.redirect('/serve/%s-%s' % (product_id,i))
             break;
     self.response.out.write('Maximum number of images for this product id, please delete one before uploading.'),
Example #23
0
    def process_uploaded_file(self, uploaded, object, request):
        # example:
        title = request.POST.get('title', '') or uploaded.name

        f = Image(image=uploaded, name=title)
        f.save()
        return {
            'url': f.imagem(),
            'thumbnail_url': f.imagem(),
            'id': f.id,
            'name': f.name,
        }
Example #24
0
def load(hotelname, hoteladdress, hotelweb, latitude, longitude, description, imagelist, categorylist):
	#itertools to work with multiple lists at once
	for name, address, web, latit, longit, descr, category, images in itertools.izip(hotelname, hoteladdress, hotelweb, latitude, longitude, description, categorylist, imagelist):
		#Strip HTML tags
		descr = strip_tags(descr)
		print "Saving: " + name
		hotel = Hotel(name=name, web=web, body=descr, address=address, category=category[0],
			          latitude=latit, longitude=longit, stars=category[1])
		hotel.save()
		identifier = Hotel.objects.get(name=name)
		urls =' '.join(images)
		images = Image(hotel=identifier, url_image=urls)
		images.save()
Example #25
0
def sendmessage():
    """
    phones = Phone.all()
    regIds = [phone.phone_id for phone in phones]
    data = dict()
    data['title'] = 'me'
    data['post'] = '123'
    dataToSend = dict()
    dataToSend['registration_ids'] = regIds
    dataToSend['data'] = data
    response = Response(json.dumps(dataToSend),mimetype='application/json')
    response.headers.add('Content-Type','application/json')
    response.headers.add('Authorization','key=AIzaSyBsBuZuPlRkt45QstSJ_qaHC7_e1NFEIZU')
    #return response

    headers = MultiDict()
    headers['Content-Type'] = 'application/json'
    headers['Authorization'] = "key=AIzaSyBsBuZuPlRkt45QstSJ_qaHC7_e1NFEIZU"
    req = urllib2.Request("https://android.googleapis.com/gcm/send", json.dumps(dataToSend), headers)
    f = urllib2.urlopen(req)
    responseMsg = f.read()
    f.close()
    return responseMsg;
    return json.dumps(dataToSend, sort_keys=True, indent=4)
    """
    data = MultiDict()
    f = request.form
    for key in f.keys():
        data[key] = f[key]

    files = request.files.getlist('upload')

    titleMsgHash = data['title'] + data['post']# + chr(random.randrange(97,97+26+1))
    titleMsgHash = getHash(titleMsgHash)

    currentPost = Post(key_name=titleMsgHash,title=data['title'],msg=data['post'])
    currentPost.put()
    base64Strings = []
    i = 0
    for file in files:
        #file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
        fileString = file.read()
        image64String = fileString.encode("base64")
        imageKeyName = data['title']+data['post']+'image'+str(i)
        tmpImage = Image(key_name=getHash(imageKeyName),encoded_string=image64String,post_id=currentPost.key())
        tmpImage.put()
        i = i+1

    logging.debug('reached end')
    return jsonify(data)
Example #26
0
	def t065_Image(self):
		"""Immagini"""
		L.i("ImageTestData load start")
		for el in TestData.listImages:
			img = Image(
				description = el['description'], 
				link = el['link'], 
				type = el['type'],
				blob = el['blob']
			)
			self.images.append(img)
			img.save()
		L.i("ImageTestData ended")
		return True
Example #27
0
    def post(self, album_id):
        """POST handler for a gallery image.

        URL pattern: /albums/${album_id}/images
        POST data must be of type multipart/form and contain image as 'file'.
        POST data must also contain image metadata: 'name'.
        Image filename must include an extension.

        Returns 201 CREATED with JSON data structure describing new image.
        Returns Content-type: application/json.
        Also returns Location header pointing to API URL for image details.

        Include 'wrapjson' parameter in POST to wrap returns JSON in
        a <textarea>. This also changes the returned Content-type to text/html.

        If album doesn't exist, returns 404 NOT FOUND.
        If request is poorly formatted returns 400 BAD REQUEST.

        Returns 401 UNAUTHORIZED to all calls if authorization fails.
        """
        q = Album.all().filter('album_id =', album_id)
        album = q.get()
        if not album:
            return self.error(404)

        try:
            data = dict(((str(k), v) for k, v in self.request.POST.items()))
            if 'file' in data:
                data['extension'] = data['file'].filename.split('.')[-1].lower()
                if data['extension'] == data['file'].filename:
                    data['extension'] = ''
                else:
                    data['extension'] = '.' + data['extension']
                data['image_data'] = data['file'].file.read()

            image = Image(image_id=config.IMAGE_ID_GENERATOR(),
                          album=album,
                          **data)
        except:
            data = {}
            self.error(400)
        else:
            if not config.DEMO_MODE:
                image.put()

            data = image.to_dict()
            self.response.headers['Location'] = data['url']
            self.response.set_status(201)

        write_json(self, data, wrapjson='wrapjson' in self.request.POST)
def attach_image_to_project(id):
  MyForm = model_form(Image, base_class=Form, exclude_fk = True, db_session=db.session, field_args={
    'subtitle': {'validators' : [InputRequired()]},
    'url': {'validators': [InputRequired(), URL(), valid_image_link]}}
    )
  image = Image(project_id = id)
  form = MyForm(request.form, image)
  if form.validate_on_submit():
    image.subtitle = form.subtitle.data
    image.url = form.url.data
    db.session.add(image)
    db.session.commit()
    return "success", 201
  return render_template("create_image.html", form=form, url = "/project/add/" + str(id) + "/image")
Example #29
0
 def test_thumbnail_creation(self):        
     data = 'big_image_data'        
     compressed_data = 'cmprsd_data'
     image = Image.create(data=data)
     mock_service_image = mock()
     when(images).Image(blob_key=image.blob_key).thenReturn(mock_service_image)
     when(mock_service_image).execute_transforms(output_encoding = images.JPEG).thenReturn(compressed_data)
     options = Options(dict(width=420))
     thumbnail = Image.thumbnail(image.short_key, options)
     verify(mock_service_image).resize(width=420)
     self.assertEqual(compressed_data, read_blob(thumbnail.blob_key))
     self.assertEqual(thumbnail.key, key.Key(Image, options.key, parent = image.key))
     original_blob_key = thumbnail.blob_key
     thumbnail = Image.thumbnail(image.short_key, options)
     self.assertEqual(original_blob_key, thumbnail.blob_key)
Example #30
0
    def get_context(self, pagenum):
        images = Image.get_sorted_list()

        try:
            num_per_page = session['num_per_page']
        except KeyError:
            num_per_page = 25
            session['num_per_page'] = num_per_page

        images = images.paginate(pagenum,
                                 int(num_per_page), False)

        form = SortForm(formdata=request.form)

        # reflect current setting in form
        try:
            form.sort_order.data = session['sort_order']
        except KeyError:
            pass

        try:
            form.sort_by.data = session['sort_by']
        except KeyError:
            pass

        try:
            form.num_per_page.data = session['num_per_page']
        except KeyError:
            pass

        context = {
            "images": images,
            "form": form
        }
        return context
Example #31
0
 def get(self):
     album_id = self.get_argument('album_id', None)
     from_id = force_int(self.get_argument('from_id', 0), 0)
     limit = force_int(self.get_argument('limit', config.paged),
                       config.paged)
     if not album_id:
         result = {'status': 'error', 'message': '没有指定专辑'}
         return self.write(result)
     images = Image.query_by_album_id(album_id,
                                      from_id=from_id,
                                      limit=limit + 1)
     has_more = len(images) > limit
     object_list = []
     for image in images:
         object_list.append(image.to_dict())
     return self.write({
         'status': 'success',
         'object_list': object_list,
         'has_more': has_more
     })
Example #32
0
def create_image():
    if request.method == 'POST':
        title = request.form.get('title')
        img_url = request.form.get('img_url')

        if title and img_url:
            if not img_url.startswith('/static/image/'):
                flash('Image creation failed')
                return redirect(url_for('create_image'))

            image = Image(title=title, url=img_url, owner=current_user)
            db.session.add(image)
            db.session.commit()
            res = redirect(url_for('index'))
            res.headers['X-ImageId'] = image.id
            return res
        return redirect(url_for('create_image'))

    elif request.method == 'GET':
        return render_template('create_image.html')
Example #33
0
    def get(self, slug):
        status = Status.get_by_slug(slug)
        if not status:
            self.not_found()
            return

        td = {
            "statuses_selected": True,
            "status": status,
            "action": "edit",
            "url": "/admin/api/v1/statuses/" + slug,
            "description": status.description,
            "name": status.name,
            "image_url": status.image,
            "images": Image.all().fetch(200),
            "default": status.default,
        }

        td.update(site.default_template_data())
        self.render(td, 'admin/status_edit.html')
Example #34
0
def verify_deploy(deploy_id):
    _deploy = Deploy.find(deploy_id)
    if _deploy is None:
        abort(500)
    if request.method == 'GET':
        image = Image.where('image_tag', _deploy.image_tag).first()
        project = Project.where('image_name', _deploy.image_name).first()
        user = User.find(_deploy.user_id)
        return render_template('deploy/verify.html',
                               deploy=_deploy,
                               image=image,
                               project=project,
                               user=user)
    admin_pwd = request.form.get('password')
    admin = User.where('is_admin', True).first()
    if admin.password == admin_pwd:
        send_deploy_request(_deploy)
        flash('请求发送成功')
        return redirect(url_for('docker.index'))
    flash('密码错误!')
    return redirect(url_for('docker.verify_deploy', deploy_id=deploy_id))
def save_to_db(line, path, url):

    name = line["pageURL"].split('/')[-2]
    url = url
    path = path
    pixabay_id = line['id']
    created_at = datetime.datetime.now()
    status = "Not Posted"
    tags = line['tags'].replace(",", "")
    caption = create_random_caption(tags)

    image = Image.create(name=name,
                         url=url,
                         path=path,
                         pixabay_id=pixabay_id,
                         created_at=created_at,
                         status=status,
                         tags=tags,
                         caption=caption)
    image.save()
    return image
Example #36
0
 def delete(self, image_id):
     image = Image.get(id=image_id)
     if not image:
         return self.redirect_next_url()
     if image.topic_id:
         return self.send_error_result(msg=u'此图片被主题《%s》引用,无法删除' %
                                       image.topic.title)
     if self.current_user.is_admin and image.user_id != self.current_user.id:
         subject = "图片删除通知 - " + config.site_name
         template = ('<p>尊敬的 <strong>%(nickname)s</strong> 您好!</p>'
                     '您在 %(site)s 的图片由于违反社区规定而被删除。</p>') % {
                         'nickname': image.author.nickname,
                         'site': config.site_name,
                     }
         self.send_email(self, image.author.email, subject, template)
     if self.current_user.is_admin or image.user_id == self.current_user.id:
         image.remove()
         result = {'status': 'success', 'message': '已成功删除'}
     else:
         result = {'status': 'error', 'message': '你没有权限啊, baby'}
     return self.write(result)
Example #37
0
 def post(self):
     try:
         logging.info("ONE")
         upload = self.get_uploads()[0]
         logging.info("TWO")
         stream_name = self.request.get('stream_name')
         logging.info("THREE")
         key = ndb.Key('Stream', stream_name)
         logging.info("FOUR")
         stream = key.get()
         logging.info("FIVE")
         image = Image(url=images.get_serving_url(upload.key()),
                       photo_key=upload.key(),
                       comment="")
         logging.info("SIX")
         stream.images.insert(0, image)
         logging.info("SEVEN")
         stream.put()
         logging.info("EIGHT")
         self.response.write(images.get_serving_url(upload.key()))
     except:
         pass
Example #38
0
def UpdateImageSchema(cursor=None, num_updated=0, has_more=True):
    if has_more:
        query = Image.query(ancestor=IMAGE_KEY)

        to_put = []
        images, next_cursor, more = query.fetch_page(page_size=BATCH_SIZE,
                                                     start_cursor=cursor)

        for i in images:
            i.OCRResult = None
            to_put.append(i)

        if to_put:
            ndb.put_multi(to_put)
            num_updated += len(to_put)
            logging.debug(
                'Put %d image entities to Datastore for a total of %d',
                len(to_put), num_updated)
            UpdateImageSchema(next_cursor, num_updated, more)
        else:
            logging.debug('UpdateImageSchema completed with %d updated!',
                          num_updated)
Example #39
0
    def post(self):
        user = users.get_current_user() # get current logged in user
        meme_key_string = self.request.get('meme_key')
        image_name = self.request.get('image')
        image_key = Image.query(Image.name == image_name).fetch(1)[0].key # get the key of the correct image by nickname

        if meme_key_string:
            meme = get_meme_from_key(meme_key_string)
            if meme.creator != user.user_id():
                self.response.status = "403 Forbidden"
                return
        else:
            meme = Meme()

        meme.top_text=self.request.get('top_text')
        meme.middle_text=self.request.get('middle_text')
        meme.bottom_text=self.request.get('bottom_text')
        meme.image=image_key
        meme.creator=user.user_id() # grab the user ID from currently logged in user, store with Meme

        meme_key = meme.put()
        self.redirect('/view?meme_key=' + meme_key.urlsafe())
Example #40
0
    def upload_image(self, request):
        photo = request.FILES.get('file')
        album_id = request.POST.get('albumId')
        file_id = get_file_md5(photo) + str(int(time.time()))
        title = request.POST.get('title', '无标题')
        if album_id == "" or album_id is None:
            is_default_album = True
        else:
            is_default_album = False

        new_img = Image(Photo=photo,
                        AlbumId=album_id,
                        FileId=file_id,
                        Name=photo.name,
                        Title=title,
                        IsDefaultAlbum=is_default_album,
                        Size=photo.size)
        new_img.save()
        new_img.Path = new_img.Photo.path.decode('utf8')
        new_img.Name = new_img.Photo.name.decode('utf8')
        try:
            new_img.save()
        except Exception, e:
            print e
Example #41
0
def index(request, template='./gallery/index.html'):
    entry = get("Gallery")

    if 'gallery' in request.POST and request.POST['gallery']:
        artist = User.objects.get(pk=request.POST['gallery'])
        photos = Image.objects.filter(artist=artist).order_by('-uploaded')
    else:
        photos = Image.objects.all().order_by('-uploaded')

    if not request.method == "POST" or ('gallery' in request.POST):
        f = UploadForm()
        af = ArtistForm(request.POST)
        ctx = {'entry': entry, 'form': f, 'photos': photos, 'artist': af}
        return render(request, template, ctx)

    f = UploadForm(request.POST, request.FILES)
    af = ArtistForm(request.POST)

    if not f.is_valid() and not request.FILES['file'].name.endswith('.svg'):
        ctx = {'entry': entry, 'form': f, 'photos': photos, 'artist': af}
        return render(request, template, ctx)

    file = request.FILES['file']
    #print type(file)
    #print dir(file)
    #for k,v in file.items(): print k, v
    #filename = file._get_name() #['filename']
    #content = file['content']
    store_in_s3(file.name, file.read())
    p = Image(url="http://%s.s3.amazonaws.com/%s" % (bucket, file.name))

    if isinstance(request.user, AnonymousUser):
        p.user = User.objects.get(username="******")
    else:
        p.user = User.objects.get(username=request.user)
    if request.POST['artist']:
        p.artist = User.objects.get(pk=request.POST['artist'])
    p.save()
    photos = Image.objects.all().order_by('-uploaded')
    ctx = {'entry': entry, 'form': f, 'photos': photos, 'artist': af}
    return render(request, template, ctx)
Example #42
0
def retype():
    if request.method == 'POST':
        x = request.form['message'].split('\n')
        username = x[0]
        aes_key = base64.b64decode(x[1])
        hex_aes_key = ''.join(x.encode('hex') for x in aes_key)

        print username
        user = User.query.filter(User.username == username).first()
        print '1', hex_aes_key == user.password[:32]
        print '2', hex_aes_key
        print '3', user.password[:32]

        print upload_cache
        entry = upload_cache.get(username)
        if not entry:
            return 'RETYPE 5'
        tries = entry[0]
        case = entry[1]
        folder = entry[2]
        if hex_aes_key == user.password[:32]:
            db.session.add(case)
            db.session.commit()

            # store images in database
            for img_file in glob.glob(os.path.join(folder, "*.jpg")):
                img = Image()
                img.create_image(img_file, case)
                db.session.add(img)
                db.session.commit()

            return 'OK'
        else:
            if tries != 4:
                upload_cache[username] = (tries + 1, case, folder)
            else:
                upload_cache.pop(username)
            return "RETYPE %s" % tries
Example #43
0
def uploadImage(request):
    '''Upload image to BAE cloud storage.'''
    '''@receive Form data with keys "allowOverwrite"(boolean), "images"(files in request.FILES).'''
    '''@return JSON indicating saved images, format [{'name':filename, 'path':imageSavePath}].'''
    methodName = 'uploadImage'
    username = request.user.username
    allowOverwrite = request.POST.get('allowOverwrite')
    savedImgs = []

    for img in request.FILES.getlist('images'):
        imgSavePath = resourcesHelper.getFileSavePath(username, img.name)
        imgSaveName = img.name[:img.name.rfind('.')]

        if bosResource.upload_by_str(
                imgSavePath,
                img.read()):  # Upload file succeeds. Save record to database.
            imgInfo = {'name': imgSaveName, 'path': imgSavePath}
            savedImgs.append(imgInfo)
            existedImages = Image.objects.filter(username=username,
                                                 name=imgSaveName)
            if len(existedImages) == 0:  # New Record.
                Image(username=username, name=imgSaveName,
                      src=imgSavePath).save()
            elif allowOverwrite is not None:  # Update existing record. There will be only one record as unique_together Meta setting.\
                existedImage = existedImages[0]
                existedImage.src = imgSavePath
                existedImage.save()
                imgInfo['overwrite'] = True
            else:
                raise E.RequestParamException(
                    '%s: Attempt to overwrite existed image with name (%s) while not allow to overwrite.'
                    % (methodName, imgSaveName))
        else:
            raise E.BAEException(
                '%s: Saving image to BAE bucket failed. Image name:%s. Error info: %s'
                % (methodName, img.name, response))

    return HttpResponse(json.dumps(savedImgs))
Example #44
0
def admin_images():
    form = ImageForm()
    if form.validate_on_submit():

        # save file to S3
        s3 = boto3.client('s3')
        file = request.files[form.file.name]
        filename = secure_filename(file.filename)
        s3.put_object(Body=file, Bucket='governmentswagger', Key=filename)

        # save image info to database
        url = 'http://s3.amazonaws.com/governmentswagger/' + filename
        name = form.name.data
        hotel = form.hotel.data
        cover_image = form.cover_image.data
        key = filename
        image = Image(name, url, key, cover_image, hotel.id)
        db.session.add(image)
        db.session.commit()
        return redirect('/admin/images')
    else:
        hotels = Hotel.query.all()
    return render_template('admin/images.html', form=form, hotels=hotels)
Example #45
0
def upload_images():
    if request.files:
        images = request.files.getlist("images")
        img_objects = []

        for image in images:
            # check that images where uploaded
            if image.filename == "":
                flash('Please add photos.')
                return redirect(url_for('index'))

            try:
                ImageStorageService.upload_image(image)
            except FileNotFoundError:
                flash(
                    'Internal Error: The file was not found. Please try again later.'
                )
                return redirect(url_for('index'))
            except NoCredentialsError:
                flash(
                    'Internal Error: Credentials not available. Please try again later.'
                )
                return redirect(url_for('index'))

            this_month = datetime(datetime.today().year,
                                  datetime.today().month, 1)
            # create database object
            img_obj = Image(month_uploaded=this_month,
                            path=image.filename,
                            user_id=current_user.id)
            img_objects.append(img_obj)

        # save images into database
        db.session.bulk_save_objects(img_objects)
        db.session.commit()
        flash('Uploaded Successfully.')
        return redirect(url_for('index'))
Example #46
0
def seed_data():
    fry_key = Image(name="fry_squint", image_file="fry.png").put()
    jc_key = Image(name="jackie_chan_wtf", image_file="jackie.png").put()
    tears_key = Image(name="tears_in_the_rain", image_file="tears.png").put()
    pika_key = Image(name="surprised_pikachu", image_file="surprised_pikachu.png").put()
    buzz_key = Image(name="buzz_everywhere", image_file="buzz_everywhere.jpg").put()
    roll_safe_key = Image(name="roll_safe", image_file="roll_safe.jpg").put()


    Meme(top_text="Not sure if meme app", bottom_text="or black hole",
         image=fry_key, creator="*****@*****.**",
         created_at=datetime.datetime(2018, 07, 23, 05, 23, 0, 0)).put()
    Meme(top_text="Meme app", bottom_text="doesn't save memes?",
         image=jc_key, creator="*****@*****.**",
         created_at=datetime.datetime(2018, 06, 23, 05, 23, 0, 0)).put()
    Meme(top_text="All these memes", bottom_text="lost like tears in the rain.",
         image=tears_key, creator="*****@*****.**",
         created_at=datetime.datetime(1984, 07, 23, 05, 23, 0, 0)).put()
def edit():
    image = Image()  #
    form = ImageForm()
    qry = db.session.query(Image).filter(Image.name.contains("oben"))
    image_fn = qry.first()  #result from the query
    image_file = url_for('static', filename='img/' + image_fn.image_file)  #

    if form.validate_on_submit():
        filename = photos.save(form.photo.data)
        file_url = photos.url(filename)
        f_name, f_ext = os.path.splitext(filename)
        picture_fn = f_name + f_ext
        picture_path = os.path.join(app.root_path, 'static/profile_pics',
                                    picture_fn)
        image_fn.image_file = picture_fn  #Dont forget to change the image path if it workd later on
        #image_fn.name = form.name.data
        #db.session.add(image)
        db.session.commit()
    else:
        file_url = None
    return render_template('edit-image.html',
                           form=form,
                           file_url=file_url,
                           image_file=image_file)
Example #48
0
def stats():
    db.connect()

    aufmacher_count = Aufmacher.select().count()
    author_count = Author.select().count()
    image_count = Image.select().count()

    print("Stats:")
    print("{:>5} Aufmacher".format(aufmacher_count))
    print("{:>5} authors".format(author_count))
    print("{:>5} images".format(image_count))

    print("\nLatest:")
    latest_aufmacher = Aufmacher.select().order_by(Aufmacher.created_at.desc())
    latest_aufmacher_string = """
since {created_at}
{supertitle}: {title}
{subtitle}
by {author_name}
    """.format(**model_to_dict(latest_aufmacher[0]),
               author_name=latest_aufmacher[0].author.name)
    print(latest_aufmacher_string.strip())

    db.close()
Example #49
0
    def post(self):
        album = self.request.get("album")
        u = self.request.get("u")
        des = self.request.get("des")
        name = self.request.get("name")
        retries = 3
        result = None
        try:
            result = urlfetch.fetch(u, deadline=10)
        except:
            retries -= 1
            if retries > 0:
                result = urlfetch.fetch(u, deadline=10)

        if result and result.status_code == 200:
            album = Album.get_by_key_name(album)
            bf = result.content
            mime = getImageInfo(bf)[0]
            if mime.find("image") < 0:
                raise Exception(u"不是正確的圖片")
            img = Image.add(album, name, mime, bf, **{"description": des})
            self.redirect(album.m_url)
        else:
            self.response.out.write(u"此地址抓取錯誤")
Example #50
0
def ParseGraphVRD(d):
  image = Image(d['photo_id'], d['filename'], d['width'], d['height'], '', '')

  id2obj = {}
  objs = []
  rels = []
  atrs = []

  for i,o in enumerate(d['objects']):
    b = o['bbox']
    obj = Object(i, b['x'], b['y'], b['w'], b['h'], o['names'], [])
    id2obj[i] = obj
    objs.append(obj)

    for j,a in enumerate(o['attributes']):
      atrs.append(Attribute(j, obj, a['attribute'], []))

  for i,r in enumerate(d['relationships']):
    s = id2obj[r['objects'][0]]
    o = id2obj[r['objects'][1]]
    v = r['relationship']
    rels.append(Relationship(i, s, v, o, []))

  return Graph(image, objs, rels, atrs)
Example #51
0
    def get(self):
        "Responds to GET requets with the admin interface"
        # query the datastore for images owned by
        # the current user. You can't see anyone elses images
        # in the admin
        images = Image.all()
        images.filter("user ="******"-date")

        # we are enforcing loggins so we know we have a user
        user = users.get_current_user()
        # we need the logout url for the frontend
        logout = users.create_logout_url("/")

        # prepare the context for the template
        context = {
            "images": images,
            "logout": logout,
        }
        # calculate the template path
        path = os.path.join(os.path.dirname(__file__), 'templates',
                            'index.html')
        # render the template with the provided context
        self.response.out.write(template.render(path, context))
Example #52
0
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()
Example #53
0
 def getImages(self, post):
     url = post['file_url']
     name = 'Zerochan ' + str(post['id']) + ' ' + post['name'] + '.' + post['file_ext']
     return [Image(name, url)]
Example #54
0
    def create_image(self, data, **kwargs):
        data['image'] = data['image'].encode('utf-8')

        return Image(**data)
 async def get(self):
     db = self.request.config_dict['db']
     all_images = await db.execute(Image.select())
     response = {image.id: model_to_dict(image) for image in all_images}
     return web.json_response(response)
Example #56
0
def register():
    from mail import send_mail
    req = request.get_json()

    name = str(req['name'])
    lastname = str(req['lastname'])
    email = str(req['email'])
    password = str(req['password'])
    confirm_password = str(req['confirmPassword'])
    role = int(req['role'])

    image = 'default_user.png'

    errors = {}

    def check_empty(field_names, field_values, display_names, errors, check):
        assert len(field_names) == len(field_values) == len(display_names)
        for field_name, field_value, display_name in zip(
                field_names, field_values, display_names):
            if check(field_value):
                errors[
                    field_name] = f'Polje {display_name} ne sme biti prazno.'

    existing_user_by_email = User.query.filter(User.email == email).first()

    check_empty(['name', 'lastname', 'password', 'confirmPassword', 'email'],\
                [name, lastname, password, confirm_password, email], \
                ['ime', 'prezime', 'lozinka', 'potvrdi lozinku', 'email adresa'],\
                errors, lambda x: len(x) == 0)

    if role == ROLE_STUDENT:
        year = int(req['year'])
        module = int(req['module'])
        student_id = str(req['studentId'])

        check_empty(['year', 'module'], [year, module], ['godina', 'modul'], errors, \
                    lambda x: x == 0)

        if len(student_id) == 0:
            errors['studentId'] = 'Polje broj indeksa ne sme biti prazno'
        else:
            existing_user_by_student_id = User.query.filter(
                User.student_id == student_id).first()
            if existing_user_by_student_id:
                errors[
                    'studentId'] = 'Korisnik sa navedenim brojem indeksa već postoji.'

    if existing_user_by_email:
        errors['email'] = 'Korisnik sa navedenom e-mail adresom već postoji.'

    if len(password) < 6:
        errors['password'] = '******'

    if password != confirm_password:
        errors['confirmPassword'] = '******'

    if len(errors) != 0:
        return jsonify(errors), 422

    image = Image()
    image.path = 'default_user.png'

    user = User()
    user.name = name
    user.lastname = lastname
    user.email = email
    user.hashed_password = sha256_crypt.hash(password)
    user.role_id = role
    user.user_status_id = USER_STATUS_EMAIL_UNCONFIRMED
    user.image = image

    if role == ROLE_STUDENT:
        user.student_year_id = year
        user.module_id = module
        user.student_id = student_id

    # verifikacija emaila

    email_token = create_access_token(identity=user.email)

    link = f'http://localhost:4200/verify-email/{email_token}'

    subject = f'Zdravo {user.name}'
    recipient = user.email
    body = f'Hvala Vam što ste se registrovali na portalu eQues. \
            Klikom na sledeći link završićete registraciju {link}'

    send_mail(subject, recipient, body)

    db.session.add(image)
    db.session.add(user)
    db.session.commit()

    return jsonify({'message': 'Uspešna registracija.'}), 200
Example #57
0
async def generate_thumbnail(url):
    async with aiohttp.request('GET', url) as response:
        raw_image = await response.read()
    images = resize(raw_image)
    Image(url=url, **images).save()
Example #58
0
    p_2017_files_descriptions[file] = ""
for file in p_2016_files:
    p_2016_files_descriptions[file] = ""
music_video_headers['angel_pose_embed.txt'] = "Angel Pose MV"
music_video_footers['angel_pose_embed.txt'] = "Video, Editing and Design by Nicholas Griffo"
music_video_headers['pink_sunset.mp4'] = "Pink Sunset MV"
music_video_footers['pink_sunset.mp4'] = "Video by Josh Thomas & Nicholas Griffo, Editing and Design by Nicholas Griffo"
music_video_headers['stereo.mp4'] = "Stereo MV"
music_video_footers['stereo.mp4'] = "Video, Editing and Design by Nicholas Griffo"

for video in water_video_files:
    water_video_headers[video] = None
    water_video_footers[video] = None

for video in beauty_virtue_video_files:
    beauty_virtue_video_headers[video] = "Beauty & Virtue Public Access Channel 8 - NYC 8Ball TV"
    beauty_virtue_video_footers[video] = "http://8balltv.club/"

Image.add_all_imgs(contact_files, 'contact_imgs', contact_files_descriptions)
Image.add_all_imgs(designs_logos_files, 'designs_logos_imgs', designs_logos_files_descriptions)
Image.add_all_imgs(scanner_1_files, 'scanner_1_imgs', scanner_1_files_descriptions)
Image.add_all_imgs(p_2020_files, 'photography_2020_imgs', p_2020_files_descriptions)
Image.add_all_imgs(p_2019_files, 'photography_2019_imgs', p_2019_files_descriptions)
Image.add_all_imgs(p_2018_files, 'photography_2018_imgs', p_2018_files_descriptions)
Image.add_all_imgs(p_2017_files, 'photography_2017_imgs', p_2017_files_descriptions)
Image.add_all_imgs(p_2016_files, 'photography_2016_imgs', p_2016_files_descriptions)
Video.add_all_vids(music_video_files, 'music_videos', music_video_headers, music_video_footers)
Video.add_all_vids(water_video_files, 'water_videos', water_video_headers, water_video_footers)
Video.add_all_vids(beauty_virtue_video_files, 'beauty_and_virtue_videos', beauty_virtue_video_headers, beauty_virtue_video_footers)

db.session.commit()
Example #59
0
 def get_images():
     return jsonify(Image.all().serialize())
Example #60
0
 def setUp(self):
     super(StatusesTest, self).setUp()
     image = Image(icon_set="fugue", slug="cross-circle",
                   path="fugue/cross-circle.png")
     image.put()