Beispiel #1
0
def add_user():
    # dummy user and dummy member are created on first request.
    # user is responsible for creating dummy events.
    Event.create_table(fail_silently=True)
    Member.create_table(fail_silently=True)
    Minute.create_table(fail_silently=True)
    Picture.create_table(fail_silently=True)
    User.create_table(fail_silently=True)
#
#     # create a dummy member
#     try:
#         member = Member(first_name="Bryan",
#                         last_name="Bennett",
#                         collegiate_chapter="Zeta Omicron "
#                                            "(Georgia Southern University)",
#                         initiation_date=datetime.date(2006, 04, 06),
#                         office="Secretary, Warden",
#                         image_path="Bryan_Bennett.jpg")
#         member.save()
#     except IntegrityError as e:
#         print e
#
    # create a dummy user
    try:
        admin = User(username='******', email='*****@*****.**',
                     admin=True, active=True)
        admin.set_password("password")
        admin.save()
    except IntegrityError as e:
        print e
Beispiel #2
0
def update_picture_database(album_name):
    """
	Updates the picture database that has field name 'album_name'.

	Performs a twitter REST API search with 'album_name' as a hashtag and retrive the new pictures from results to be added to Picture
	database.
	"""

    hashtag = "#" + album_name
    # 'tweets_result' list has the following contents: [media_url, favorite_count, user_screen_name, tweet_id]
    tweets_result = search(hashtag)

    # remove results that already exists in database
    pivots = ["tweet_id", "src_url"]
    print "Result tweets has %d results BEFORE duplicate removal." % len(tweets_result)
    for pivot in pivots:
        if len(tweets_result) <= 0:
            print "No new tweets are found."
            break
        tweets_result = remove_duplicates(tweets_result, pivot)
    print "Result tweets has %d results AFTER duplicate removal." % len(tweets_result)

    # modify picture contents.
    # modifications are:
    # 	1. set new picture name to be stored
    # 	2. extract image contents from url
    if len(tweets_result) > 0:
        new_pictures = []
        for i in range(len(tweets_result)):
            # set new img name to be stored
            src = tweets_result[i][0]
            new_img_name = generate_img_filename(src)
            # extract img content and put to new file
            new_img_file = get_img_content(src, new_img_name)
            new_pictures.append(new_img_file)

            # upload new_pictures list to s3 bucket
        upload_to_bucket(new_pictures, album_name)
        print "New '%s' album images has been uploaded to S3 bucket." % album_name

        # upload contents to database
        i = 0
        album = Album.objects.get(name=album_name)  # get album object
        if album != None:
            for img in tweets_result:
                pic = Picture(
                    album=album,
                    url=new_pictures[i][0],
                    src_url=img[0],
                    like_count=img[1],
                    owner=img[2],
                    tweet_id=img[3],
                )
                pic.save()
                print "%s saved to database." % img[0]
                i += 1
                # fire off signal
        abcd = Picture(album=album, url=new_pictures[0], like_count=img[1], owner=img[2], tweet_id=img[3])
        send_email.send(sender=Picture, instance=abcd)
    return
Beispiel #3
0
def cron_sync():
    print 'start cron_sync ...'
    with app.test_request_context():
        users = User.query.all()
        for user in users:
            print user
            # make sure not conflict
            if get_user_last_activity(user.id) is not None:
                continue
            resp = client.metadata(user.vdisk_token, '/idesktop')
            if isinstance(resp, str):
                print 'error in metadata'
                continue
            result = json.loads(resp.read())
            if result['hash'] == user.vdisk_hash:
                print 'same hash'
                continue
            user.vdisk_hash = result['hash']
            db.session.add(user)
            db.session.commit()

            contents = [content for content in result['contents'] if is_good(content)]
            for content in contents:
                #print content['md5']
                pic = Picture.query.filter_by(hash_id=content['md5']).first()
                if not pic:  # need to upload
                    #upload to upyun
                    ret = client.media(user.vdisk_token, content['path'])
                    if isinstance(ret, str):
                        continue
                    url = json.loads(ret.read())['url']
                    filename = content['md5']
                    filename += '.' + content['path'].split('.')[-1]
                    low_q.enqueue(down_upload, url, filename)

                    # add to db
                    filename = content['path'].split('/')[-1]
                    picture = Picture(filename, content['md5'])
                    picture.in_yun = True
                    picture.user = user
                    picture.users.append(user)
                    db.session.add(picture)
                    db.session.commit()
                    #print filename + '#' + url
                elif user not in pic.users:
                    pic.users.append(user)
                    db.session.add(pic)
                    db.session.commit()
            #handle self delete in local folder
            hashs = [content['md5'] for content in contents]
            for pic in user.downloads.all():
                if pic.hash_id not in hashs:
                    #need delete
                    pic.users.remove(user)
                    db.session.add(pic)
                    db.session.commit()
    print 'stop cron_sync ...'
    ret = {'result':'ok'}
    return jsonify(**ret)
Beispiel #4
0
def test_fetchimage_notfound():
    picture = Picture()
    picture.url = "http://www.globo.com/media/globocom/noimage.png"
    try:
        picture.fetch_image()
        assert False
    except ImageNotFoundError:
        pass
Beispiel #5
0
def create_tables():
    User.create_table(fail_silently=True)
    Item.create_table(fail_silently=True)
    Address.create_table(fail_silently=True)
    Order.create_table(fail_silently=True)
    OrderItem.create_table(fail_silently=True)
    Picture.create_table(fail_silently=True)
    Favorite.create_table(fail_silently=True)
def update_photo_info():
    if not 'MyWebsite_user_id' in session.keys():
        return redirect('/')
    if not User.is_logged_in(session['MyWebsite_user_id'],session['login_session']):
        return redirect('/danger')    
    photo_info=json.loads(request.form['json'])
    # print("Photo Info",photo_info)
    Picture.update_info(photo_info)
    return "Thank You"
    def test_delete_pictures__missing_file(self):
        item = Item.create(**TEST_ITEM)
        picture = Picture.create(item=item, **TEST_PICTURE)
        resp = self.app.delete(
            '/pictures/{picture_uuid}'.format(picture_uuid=picture.uuid))

        assert resp.status_code == client.NO_CONTENT
        assert not Picture.select().exists()
        assert Item.select().exists()
Beispiel #8
0
    def get(self, item_uuid):
        """Retrieve every picture of an item"""
        pictures = Picture.select().join(Item).where(Item.uuid == item_uuid)

        if pictures:
            data = Picture.json_list(pictures)
            return generate_response(data, client.OK)

        return None, client.NOT_FOUND
    def test_get_item_pictures__success(self):
        item = Item.create(**TEST_ITEM)
        Picture.create(item=item, **TEST_PICTURE)
        Picture.create(item=item, **TEST_PICTURE2)
        resp = self.app.get(
            '/items/{item_uuid}/pictures/'.format(item_uuid=item.uuid))
        assert resp.status_code == client.OK

        test_utils.assert_valid_response(
            resp.data, EXPECTED_RESULTS['get_item_pictures__success'])
Beispiel #10
0
def api_upload(request):
    if request.method == 'POST':
        picture = Picture()
        user = User.objects.get(email=request.POST['email'])
        picture.user = user
        form = UploadFileForm(request.POST, request.FILES, instance=picture)
        if form.is_valid():
            picture.picture = request.FILES['picture']
            if request.POST.has_key('gallery_id'):
                gallery = Gallery.objects.get(id=request.POST['gallery_id'],
                                              user=user)
                picture.gallery = gallery

            picture.picture.name = unidecode(picture.picture.name)
            picture.save()
            rotate_picture(picture)
            picture.update_thumb()

            if request.POST.has_key('description'):
                picture_description = PictureDescription(picture=picture)
                picture_description.text = request.POST['description']
                picture_description.save()

            response = {'status': 'OK'}
            response['data'] = serialize_picture(picture)
            return HttpResponse(json.dumps(response))

    return HttpResponse(content_200)
Beispiel #11
0
def search(parameters):
    # Préparation des paramètres de la requête
    payload = {
        'client':
        "v8.a.3",
        'price_range':
        "%s,%s" % (parameters['price'][0], parameters['price'][1]),  # Loyer
        'area_range':
        "%s,%s" %
        (parameters['surface'][0], parameters['surface'][1]),  # Surface
        'rooms_range':
        "%s,%s" % (parameters['rooms'][0], parameters['rooms'][1]),  # Pièces
        'bedrooms_range':
        "%s,%s" %
        (parameters['bedrooms'][0], parameters['bedrooms'][1]),  # Chambres
        'localities':
        ','.join(key for key in search_city_code(parameters['cities']))
    }

    # Insertion des paramètres propres à LeBonCoin
    payload.update(parameters['logic-immo'])

    request = requests.post(
        "http://lisemobile.logic-immo.com/li.search_ads.php",
        params=payload,
        headers=header)
    data = request.json()

    for ad in data['items']:

        annonce, created = Annonce.get_or_create(
            id='logic-immo-' + ad['identifiers']['main'],
            site="Logic Immo",
            created=datetime.fromtimestamp(ad['info']['firstOnlineDate']),
            title="%s %s pièces" %
            (ad['info']['propertyType']['name'], ad['properties']['rooms']),
            description=ad['info']['text'],
            telephone=ad['contact'].get('phone'),
            price=ad['pricing']['amount'],
            surface=ad['properties']['area'],
            rooms=ad['properties']['rooms'],
            bedrooms=ad['properties'].get('bedrooms'),
            city=ad['location']['city']['name'],
            link=ad['info']['link'])

        if created:
            pictures = [
                picture.replace("[WIDTH]",
                                "1440").replace("[HEIGHT]", "956").replace(
                                    "[SCALE]", "3.5")
                for picture in ad.get('pictures')
            ]
            for picture in pictures:
                Picture.create(url=picture, annonce=annonce)
            annonce.save()
Beispiel #12
0
def picture_creator(num_picture, index, item):
    ALLOWED_EXTENSION = ['jpg', 'jpeg', 'png', 'gif']
    pictures_path = get_random_pictures(num_picture)
    picture_id = fake.uuid4()
    extension = random.choice(ALLOWED_EXTENSION)
    Picture.create(uuid=picture_id, extension=extension, item=item)
    image_folder = utils.get_image_folder()
    if not os.path.exists(image_folder):
        os.makedirs(image_folder)
    shutil.copy2(pictures_path[index],
                 '/{}/{}.{}'.format(image_folder, picture_id, extension))
Beispiel #13
0
def add_to_db(image_files):
    for image_file in image_files:
        image_filename = image_file.rsplit('/', 1)[1] # Get filename
        
        if not Picture.objects.filter(filename=image_filename).exists():
            picture = Picture(name=os.path.splitext(image_filename)[0], \
                              filename=image_filename, \
                              fspath=image_file, \
                              media_url=MEDIA_URL + image_file.split(MEDIA_ROOT)[1])
            picture.save()
            print 'Added to DB: ' + image_filename
Beispiel #14
0
def picture():
    p = {"picture": "img/1.jpg"}
    if request.method == "POST":
        file = request.files.get("photo")
        file_name = file.filename
        file_path = "img/%s" % file_name
        save_path = os.path.join(STATICFILES_DIR, file_path)
        file.save(save_path)
        p = Picture()
        p.picture = file_path
        p.save()
    return render_template("picture.html", **locals())
 def test_post_picture__success(self):
     item = Item.create(**TEST_ITEM)
     resp = self.app.post(
         '/items/{item_uuid}/pictures/'.format(item_uuid=item.uuid),
         data={'image': (BytesIO(b'my file contents'), 'testimage.jpg')},
         content_type='multipart/form-data')
     assert resp.status_code == client.CREATED
     assert len(Picture.select()) == 1
     picture = Picture.get()
     assert picture.item == item
     assert picture.extension == 'jpg'
     assert type(picture.uuid) == uuid.UUID
Beispiel #16
0
def drop_tables():
    database.connect()

    # Initialize db by deleting all tables
    Item.drop_table(fail_silently=True)
    User.drop_table(fail_silently=True)
    Address.drop_table(fail_silently=True)
    Order.drop_table(fail_silently=True)
    OrderItem.drop_table(fail_silently=True)
    Picture.drop_table(fail_silently=True)

    database.close()
Beispiel #17
0
def picture():
    p={'picture':'img/photo.jpg'}
    if request.method == 'POST':
        file=request.files.get('photo')
        file_name=file.filename
        file_path='img/%s'%file_name
        save_path=os.path.join(STATICFILES_DIR,file_path)
        file.save(save_path)
        p=Picture()
        p.picture=file_path
        p.save()
    return render_template('picture.html',**locals())
Beispiel #18
0
def create_tables():
    database.connect()

    # Create new table with the same name
    Item.create_table()
    User.create_table()
    Address.create_table()
    Order.create_table()
    OrderItem.create_table()
    Picture.create_table()

    database.close()
Beispiel #19
0
def api_upload(request):
    if request.method == 'POST':
        picture = Picture()
        user = User.objects.get(email=request.POST['email'])
        picture.user = user
        form = UploadFileForm(request.POST, request.FILES, instance=picture)
        if form.is_valid():
            picture.picture = request.FILES['picture']
            if request.POST.has_key('gallery_id'):
                gallery = Gallery.objects.get(id=request.POST['gallery_id'], user=user)
                picture.gallery = gallery

            picture.picture.name = unidecode(picture.picture.name)
            picture.save()
            rotate_picture(picture)
            picture.update_thumb()

            if request.POST.has_key('description'):
                picture_description = PictureDescription(picture=picture)
                picture_description.text = request.POST['description']
                picture_description.save()  

            response = {'status':'OK'}
            response['data'] = serialize_picture(picture)
            return HttpResponse(json.dumps(response))

    return HttpResponse(content_200)
 def create_photos(self, photo_count = default_photo_count):
     count = 1;
     for photo in self.flickr.walk(text='butteryfly', content_type='1', media='photos', per_page=photo_count):
         farm_id = photo.get('farm')
         server_id = photo.get('server')
         _id = photo.get('id')
         secret = photo.get('secret')
         url = 'http://farm' + farm_id + '.staticflickr.com/' + server_id + '/' + _id + '_' + secret + '.jpg'
         print url
         Picture.create(url)
         count +=1
         if count > photo_count:
             break  
     return self
Beispiel #21
0
def review_photo(request, project_id):
    print project_id
    review = None
    try:
        review = get_object_or_404(ApplicationReview, pk=project_id)
        print review
    except Http404:
        review = ApplicationReview(id=99999)  # hack an empty review

    print request.FILES
    picture = Picture(review=review, file=request.FILES["files"])
    picture.save()

    return HttpResponse(json.dumps("OK"), content_type="application/json")
Beispiel #22
0
def classify_add_picture_by_url(request):
	global saved_url
	global results
	if request.method=="POST":
		saved_url=request.POST['original_image_url']
		saved_path=download_img(saved_url)
		saved_path=quote(saved_path)
		img=Picture(original_image=saved_path)
		img.save()
		img=Picture.objects.order_by('-id')[0]
		saved_url=unquote(unquote(img.original_image.url))
		print saved_url
		results=classify(saved_url)
		return HttpResponseRedirect('/deeplearning/image_text/')
Beispiel #23
0
def save_image(dfile):
    """ given a django file handle, save the image """
    data = dfile.read()
    name = urlsafe_b64encode(sha1(data).digest())
    suffix = None
    if data[0:8] == PNG_HEADER:
        suffix = 'png'
    elif data[0:2] == JPEG_HEADER:
        suffix = JPEG_SUFFIX
    elif data[0:6] == GIF89A_HEADER or data[0:6] == GIF87A_HEADER:
        suffix = 'gif'
    else:
        suffix = JPEG_SUFFIX # we'll just force-convert it to a jpeg
                        # (assuming imagemagick can read it)

    # fixme: in the future, thread this
    # keep everything in pipes to save disk hits
    s3_put("%s-%s.%s" % (name, 'original', suffix), data, 
           SUFFIX_TO_CTYPE[suffix], False)
    pipe = Popen(["convert", 
                  "-auto-orient",
                  "-quality",
                  str(JPEG_QUALITY if suffix==JPEG_SUFFIX else PNG_QUALITY), 
                  '-resize',
                  "%dx%d>" % (SLIDE_WIDTH, SLIDE_HEIGHT), "-", 
                  "%s:-" % suffix], 
                 stdout=PIPE, stdin=PIPE)
    slide = pipe.communicate(data)[0]
    if pipe.returncode != 0:
        return False
    s3_put("%s-%s.%s" % (name, 'slide', suffix), slide, 
           SUFFIX_TO_CTYPE[suffix], True)
    pipe = Popen(["convert", 
                  "-auto-orient",
                  "-quality", 
                  str(JPEG_QUALITY if suffix==JPEG_SUFFIX else PNG_QUALITY), 
                  '-resize',
                  "%dx%d>" % (THUMB_WIDTH, THUMB_HEIGHT), "-[0]", 
                  "%s:-" % suffix], 
               stdout=PIPE, stdin=PIPE)
    thumb = pipe.communicate(slide)[0]
    if pipe.returncode != 0:
        return False
    s3_put("%s-%s.%s" % (name, 'thumb', suffix), thumb, 
           SUFFIX_TO_CTYPE[suffix], True)
    
    pic = Picture(name=name, suffix=suffix)
    pic.save()
    return pic
Beispiel #24
0
def sync():
    resp = client.metadata(g.user.vdisk_token, '/idesktop')
    if isinstance(resp, str):
        flash('get metadata failed!', 'error')
        return redirect(url_for('setting'))
    result = json.loads(resp.read())
    user = g.user
    user.vdisk_hash = result['hash']
    db.session.add(user)
    db.session.commit()
    #handle self add file in local folder
    contents = [content for content in result['contents'] if is_good(content)]
    for content in contents:
        #print content['md5']
        pic = Picture.query.filter_by(hash_id=content['md5']).first()
        if not pic:  # need to upload
            #upload to upyun
            ret = client.media(g.user.vdisk_token, content['path'])
            if isinstance(ret, str):
                continue
            url = json.loads(ret.read())['url']
            filename = content['md5']
            filename += '.' + content['path'].split('.')[-1]
            #get_queue('default').enqueue(down_upload, url, filename)
            low_q.enqueue(down_upload, url, filename)
            #down_upload(url, filename)
            # add to db
            filename = content['path'].split('/')[-1]
            picture = Picture(filename, content['md5'])
            picture.in_yun = True
            picture.user = g.user
            picture.users.append(g.user)
            db.session.add(picture)
            db.session.commit()
            #print filename + '#' + url
        elif g.user not in pic.users:
            pic.users.append(g.user)
            db.session.add(pic)
            db.session.commit()
    #handle self delete in local folder
    hashs = [content['md5'] for content in contents]
    for pic in g.user.downloads.all():
        if pic.hash_id not in hashs:
            #need delete
            pic.users.remove(g.user)
            db.session.add(pic)
            db.session.commit()
    flash('sync completed!', 'success')
    return redirect(url_for('setting'))
Beispiel #25
0
 def setUp(self):
     self.client.login(username='******', password='******')
     
     # Set up test Picture and Gallery.
     # These must be set up here instead of in fixtures in order to allow Picture
     # to use a NamedTemporaryFile.
     tdir = tempfile.gettempdir()
     file1 = tempfile.NamedTemporaryFile(suffix=".file1", dir=tdir)
     file1.write('a' * (2 ** 21))
     filename = file1.name
     file1.close()
     g = Gallery(name="Test Gallery")
     g.save()
     p = Picture(name="Test Picture", image=filename, gallery=g)
     p.save()
Beispiel #26
0
    def post(self):
        User_email = self.request.params.get('User_email')
        current_user = User.query(User.email == User_email).fetch(1)[0]
        activity = self.request.params.get('activity')
        upload = self.get_uploads()[0]
        if activity == 'FeedPad':
            content = self.request.params.get('content')
            latitude = self.request.params.get("latitude")
            longitude = self.request.params.get("longitude")

            newyeller = Yeller(author=User_email)
            newyeller.text = content
            newyeller.latitude = float(latitude)
            newyeller.longitude = float(longitude)
            newyeller.to_whom = 'public'
            newyeller.Anonymity = False
            newyeller.pictures.append(Picture(blob_key=upload.key()))
            yeller_key = newyeller.put()
            newyeller.key_id = str(newyeller.key.id())
            newyeller.put()
            current_user.yellers_owned.append(yeller_key)
        else:
            current_user.head_portrait = upload.key()

        current_user.put()
Beispiel #27
0
 def setup_method(self):
     super(TestItemSchema, self).setup_method()
     self.data = {
         'name': 'Test item',
         'price': 10.25,
         'description': 'Test item description',
         'availability': 73,
         'category': 'scarpe',
     }
     self.item1 = Item.create(
         uuid='25da606b-dbd3-45e1-bb23-ff1f84a5622a',
         name='Item 1',
         description='Item 1 description',
         price=5.24,
         availability=5,
         category='scarpe',
     )
     self.item2 = Item.create(
         uuid='08bd8de0-a4ac-459d-956f-cf6d8b8a7507',
         name='Item 2',
         description='Item 2 description',
         price=8,
         availability=10,
         category='accessori',
     )
     self.picture = Picture.create(
         item=self.item1,
         uuid='08bd8de0-a4ac-459d-956f-cf6d8b8a7507',
         extension='png',
     )
Beispiel #28
0
    def __iter__(self):
        session = requests.Session()
        for thread in self.search():
            for post in chan.Thread(self.board, num=thread).posts:

                for pic in post.pictures:

                    if PictureModel.check_existance(pic.url):
                        continue

                    picture = PictureModel.create(
                        url=pic.url,
                        thread=thread,
                        caption=purify_message(post.message))

                    yield picture
Beispiel #29
0
def question(request):

    # q = Picture.objects.get(id=randint(0, 14))
    r = randint(0, 14)
    while (r == StaticVar.last):
        r = randint(0, 14)
    StaticVar.last = r

    dataReader = csv.reader(open(os.path.join(BASE_DIR, 'pic.csv')),
                            delimiter=',',
                            quotechar='"')
    for row in dataReader:
        if int(row[0]) == r:
            q = Picture(id=row[0], name=row[1], sum=row[2], result=row[3])
            break

    path = '/static/pic/' + q.name + '.png'

    template = loader.get_template('j1.html')
    context = {
        'path': path,
        'n1': int(q.sum),
        'n2': int(q.sum) - int(q.result),
        'result': int(q.result)
    }

    return HttpResponse(template.render(context, request))
Beispiel #30
0
def upload_file():
    if request.method == 'POST':
        f = request.files['file']
        # 判断是否是图片
        name = f.filename
        suffix = name[name.find('.') + 1:]
        if suffix != 'bmp' and suffix != 'jpg' and suffix != 'jpeg' and suffix != 'png':
            return jsonify(code=500, message="the file is not pic")
        # 存入数据库
        # 重新生成名字
        randomCode = get_code()
        name = randomCode + '.' + suffix
        # 设置url
        url = request.url
        url = url[0:url.rfind('/') + 1] + 'pic/' + randomCode
        pic = Picture(name, url, 'Origin', -1)
        # 添加
        db.session.add(pic)
        db.session.commit()
        # 上传图片
        basepath = os.path.dirname(__file__)
        upload_path = os.path.join(basepath, 'myTest', secure_filename(name))
        f.save(upload_path)
        # 保存缩略图50x50
        url = convertToThumbnail(name, url, suffix)
        return jsonify(code=200, message="success upload", url=url, name=name)
Beispiel #31
0
    def post(self, item_id):
        try:
            item = Item.get(Item.uuid == item_id)
        except Item.DoesNotExist:
            return None, NOT_FOUND

        parser = reqparse.RequestParser()
        parser.add_argument('title', type=non_empty_string, required=True)
        parser.add_argument('file', type=FileStorage, location='files', required=True)

        args = parser.parse_args(strict=True)

        image = args['file']
        title = args['title']

        extension = image.filename.rsplit('.', 1)[1].lower()
        config = current_app.config
        if '.' in image.filename and extension not in config['ALLOWED_EXTENSIONS']:
            abort(400, message="Extension not supported.")

        picture = Picture.create(
            uuid=uuid.uuid4(),
            title=title,
            extension=extension,
            item=item
        )

        save_path = os.path.join('.', config['UPLOADS_FOLDER'], 'items', str(item_id))
        new_filename = secure_filename('.'.join([str(picture.uuid), extension]))

        os.makedirs(save_path, exist_ok=True)

        image.save(os.path.join(save_path, new_filename))

        return picture.json(), CREATED
Beispiel #32
0
def from_json():
    """
    Load all content from dump.txt into Content.existing_content
    """
    dump_file = open('dump.txt', 'r')

    # read JSON string from dump_file
    json_string = dump_file.read()
    dump_file.close()

    # parse the JSON string into a list of dictionaries
    all_content_dicts = json.loads(json_string)

    # loop over list
    for d in all_content_dicts:
        if d['type'] == 'Article':
            # this automatically adds the Article or Picture to
            # Content.existing_content
            Article(d['year'], d['month'], d['day'], d['headline'],
                    d['content'], d['contributors'])

        elif d['type'] == 'Picture':
            Picture(d['year'], d['month'], d['day'], d['title'], d['caption'],
                    d['path'], d['contributors'])
        else:
            # pass quietly
            continue
Beispiel #33
0
def upload():
    if request.method == 'POST':
        f = request.files['file']
        basepath = os.path.dirname(__file__)  #当前文件路径
        upload_path = os.path.join(basepath, 'static/uploads/',
                                   secure_filename(f.filename))
        f.save(upload_path)
        print(upload_path)

        # vedio=Vedio(vediopath=basepath,vedio=f.save(upload_path))
        # db.session.add(vedio)
        # db.session.commit()
        #print(upload_path)
        # f.save(upload_path)
        #file=request.files['file'].read()

        classification, description, path = classify_all(upload_path)

        print('path分类为' + path)
        picture = Picture(path=path,
                          classification=classification,
                          description=description)

        db.session.add(picture)
        db.session.commit()

        return redirect(url_for('index'))
    else:
        #return render_template('uploadfile.html')
        return render_template('uploadfile.html')
Beispiel #34
0
def picture_get(site, host, netloc, site_id, user_id, portfolio_id, picture_id):
    """
    Get portfolio url
    """

    # Portfolio
    try:
        portfolio = Portfolio.get(Portfolio.id == portfolio_id, Portfolio.site == site)
    except Portfolio.DoesNotExist:
        return dict(status=False, info='Portfólio não encontrado')

    # Picture
    try:
        picture = Picture.get(Picture.id == picture_id, Picture.site == site, Picture.portfolio == portfolio)
    except Picture.DoesNotExist:
        return dict(status=False, info='Imagem não encontrada')

    # Images data
    site_img_url = '%s/%s/' % (host, IMAGE_DIR)
    original_url = site_img_url + picture.original_image
    normalized_url = site_img_url + picture.normalized_image
    thumbnail_url = site_img_url + picture.thumbnail_image

    # Return OK
    return dict(status=True,
                info='Imagem encontrada com sucesso',
                original=original_url,
                normalized=normalized_url,
                thumbnail=thumbnail_url,
                **picture.get_dictionary())
Beispiel #35
0
def picture_get(site, host, netloc, site_id, user_id, portfolio_id,
                picture_id):
    """
    Get portfolio url
    """

    # Portfolio
    try:
        portfolio = Portfolio.get(Portfolio.id == portfolio_id,
                                  Portfolio.site == site)
    except Portfolio.DoesNotExist:
        return dict(status=False, info='Portfólio não encontrado')

    # Picture
    try:
        picture = Picture.get(Picture.id == picture_id, Picture.site == site,
                              Picture.portfolio == portfolio)
    except Picture.DoesNotExist:
        return dict(status=False, info='Imagem não encontrada')

    # Images data
    site_img_url = '%s/%s/' % (host, IMAGE_DIR)
    original_url = site_img_url + picture.original_image
    normalized_url = site_img_url + picture.normalized_image
    thumbnail_url = site_img_url + picture.thumbnail_image

    # Return OK
    return dict(status=True,
                info='Imagem encontrada com sucesso',
                original=original_url,
                normalized=normalized_url,
                thumbnail=thumbnail_url,
                **picture.get_dictionary())
 def test_post_item_pictures__wrong_item_uuid(self):
     resp = self.app.post(
         '/items/{item_uuid}/pictures/'.format(item_uuid=WRONG_UUID),
         data={'image': (BytesIO(b'my file contents'), 'testimage.jpg')},
         content_type='multipart/form-data')
     assert resp.status_code == client.NOT_FOUND
     assert Picture.select().count() == 0
def upload():
    # upload one or more pictures to the filesystem and register it/them in the database
    if not 'MyWebsite_user_id' in session.keys():
        return redirect('/')
    if not User.is_logged_in(session['MyWebsite_user_id'],session['login_session']):
        return redirect('/danger')    
    user=User.get_one(session['MyWebsite_user_id'])
    album_id=request.form['active_album']
    # f=request.files['new_pic']
    files=request.files.getlist('new_pic')
    for eachfile in files:
        filename=secure_filename(eachfile.filename)
        ALLOWED_EXTENSIONS = ('bmp','png', 'jpg', 'jpeg', 'gif')
        if '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS:
            print(filename)
            if path.exists('UserFiles/'+user.email+'/'+filename):
                # Album.add_pic(user,pic,album_id)
                filename=filename.rsplit('.',1)
                filename[0]=filename[0]+str(round(datetime.timestamp(datetime.now())))
                filename='.'.join(filename)

            # Save pic to the filesystem
            eachfile.save('UserFiles/'+user.email+'/'+filename)
            # Add pic to the pictures db
            pic=Picture.new(user.id,user.email+'/'+filename,filename)
            # Add pic to the active album
            Album.add_pic(user,pic,album_id)
            # Create thumbnail image using PIL
            im=Image.open('UserFiles/'+user.email+'/'+filename)
            im.thumbnail((100,100),Image.ANTIALIAS)
            im.save('UserFiles/thumbnails/'+user.email+'/'+filename)
            user.set_active_album(album_id)
        else:
            print('invalid file extension.')
    return redirect('/dashboard')
Beispiel #38
0
def handle_picture():
    """
    Create picture URL and retrieve all pictures
    """

    # POST request
    if request.method == 'POST':
        body = request.get_json()

        if body is None:
            raise APIException(
                "You need to specify the request body as a json object",
                status_code=400)
        if 'picture_url' not in body:
            raise APIException('You need to specify the picture URL',
                               status_code=400)

        address1 = Picture(picture_url=body['picture_url'],
                           photos_id=body['photos_id'])
        db.session.add(address1)
        db.session.commit()
        return "ok", 200

    # GET request
    if request.method == 'GET':
        all_pictures = Picture.query.all()
        all_pictures = list(map(lambda x: x.serialize(), all_pictures))
        return jsonify(all_pictures), 200

    return "Invalid Method", 404
Beispiel #39
0
    def create_item_picture(self, item=None, title="Picture title"):
        if not item:
            item = self.create_item()

        # TODO: Add option for different images and extensions?
        extension = 'jpg'

        picture = Picture.create(uuid=uuid.uuid4(),
                                 title=title,
                                 extension=extension,
                                 item=item)

        config = app.config
        with open(os.path.join('.', 'tests', 'images', 'test_image.jpg'),
                  'rb') as image:
            image = FileStorage(image)

            save_path = os.path.join('.', config['UPLOADS_FOLDER'], 'items',
                                     str(item.uuid))
            new_filename = secure_filename('.'.join(
                [str(picture.uuid), extension]))

            os.makedirs(save_path, exist_ok=True)

            image.save(os.path.join(save_path, new_filename))
        return picture
Beispiel #40
0
def update_book():
    pics_array = json.loads(request.form['pics_array'])
    book_id = request.form['book_id']
    for item in pics_array:
        pic = Picture.query.filter_by(instagram_id = item['id'], book_id = book_id).first()
        print pic
        if pic == None: #create a new picture
            pic = Picture(thumb_url = item['thumb_url'], full_url = item['full_url'], instagram_user = item['instagram_user'], book_id = book_id, order = item['order'], instagram_id = item['id'])
        else:
            pic.order = item['order']
        db.session.add(pic)

    db.session.commit()
    return jsonify({
        'error': 'none'
        })
    def test_delete_picture_succed(self):
        picture1 = self.create_item_picture()

        resp = self.open('/pictures/{}'.format(picture1.uuid), 'delete', data='')
        assert resp.status_code == NO_CONTENT
        assert len(Picture.select()) == 0
        resp = self.open('/pictures/{}'.format(picture1.uuid), 'get', data='')
        assert resp.status_code == NOT_FOUND
 def test_post_item_pictures__wrong_extension(self):
     item = Item.create(**TEST_ITEM)
     resp = self.app.post(
         '/items/{item_uuid}/pictures/'.format(item_uuid=item.uuid),
         data={'image': (BytesIO(b'my file contents'), 'testimage.txt')},
         content_type='multipart/form-data')
     assert resp.status_code == client.BAD_REQUEST
     assert Picture.select().count() == 0
 def test_post_picture__no_image(self):
     item = Item.create(**TEST_ITEM)
     resp = self.app.post(
         '/items/{item_uuid}/pictures/'.format(item_uuid=item.uuid),
         data={},
         content_type='multipart/form-data')
     assert resp.status_code == client.BAD_REQUEST
     assert Picture.select().count() == 0
Beispiel #44
0
def save_picture(request):
    try:

        qd = request.POST
        name = qd.get('name', '')
        desc = qd.get('desc', '')
        reqfile = request.FILES['picfile']  # picfile要和html里面一致
        img = Image.open(reqfile)
        img.thumbnail((500, 500), Image.ANTIALIAS)  # 对图片进行等比缩放
        img.save("{0}/{1}.png".format(UPLOAD_PATH, name), "png")  # 保存图片
        dire = "{0}.png".format(name)
        Picture.add(name=name, dire=dire, desc=desc)

        return render(request, 'picture.html', {})

    except Exception, e:
        return HttpResponse("Error %s" % e)  # 异常,查看报错信息
Beispiel #45
0
    def test_delete_item__pictures_cascade(self):
        """
        delete a selected item and all its binded pictures
        """
        test_utils.setup_images()
        item = Item.create(**TEST_ITEM)
        item2 = Item.create(**TEST_ITEM2)
        picture = Picture.create(item=item, **TEST_PICTURE)
        picture2 = Picture.create(item=item, **TEST_PICTURE2)
        picture3 = Picture.create(item=item2, **TEST_PICTURE3)
        imgfolder = utils.get_image_folder()
        path_pic = os.path.join(imgfolder, "{uuid}.{extension}".format(
            uuid=picture.uuid,
            extension=picture.extension))
        path_pic2 = os.path.join(imgfolder, "{uuid}.{extension}".format(
            uuid=picture2.uuid,
            extension=picture2.extension))
        path_pic3 = os.path.join(imgfolder, "{uuid}.{extension}".format(
            uuid=picture3.uuid,
            extension=picture3.extension))
        open(path_pic, "wb")
        open(path_pic2, "wb")
        open(path_pic3, "wb")

        resp = self.app.delete('/items/{item_uuid}'.format(
            item_uuid=item.uuid))

        assert resp.status_code == client.NO_CONTENT
        assert Picture.select().count() == 1
        assert Item.select().count() == 1
        item2 = Item.get()
        pic = Picture.get()
        assert pic == picture3
        assert os.path.isfile("{path}/{picture_uuid}.{extension}".format(
            path=utils.get_image_folder(),
            picture_uuid=picture3.uuid,
            extension=picture3.extension))
        assert not os.path.isfile("{path}/{picture_uuid}.{extension}".format(
            path=utils.get_image_folder(),
            picture_uuid=picture.uuid,
            extension=picture.extension))
        assert not os.path.isfile("{path}/{picture_uuid}.{extension}".format(
            path=utils.get_image_folder(),
            picture_uuid=picture2.uuid,
            extension=picture2.extension))
        test_utils.clean_images()
Beispiel #46
0
def feed(request, cordova_js_file="", os=""):
    picture_list = Picture.get_latest(count=30)
    
    return render(request, 'feed.html', {
        "picture_list" : picture_list,
        "cordova_js_file": cordova_js_file,
        os:os
    })
Beispiel #47
0
def picture_update(site, host, netloc, csrf, logged_in, user_id_logged_in):
    """
    Edit picture post url
    """

    # POST parameters
    site_id = int(request.POST.get('site'))
    user_id = int(request.POST.get('user'))
    portfolio_id = int(request.POST.get('portfolio'))
    picture_id = int(request.POST.get('picture'))
    title = request.POST.get('title')
    description = request.POST.get('description')

    # Portfolio
    try:
        portfolio = Portfolio.get(Portfolio.id == portfolio_id, Portfolio.site == site)
    except Portfolio.DoesNotExist:
        return dict(status=False, info='Portfólio não encontrado')

    # Picture
    try:
        picture = Picture.get(Picture.id == picture_id, Picture.site == site, Picture.portfolio == portfolio)
    except Picture.DoesNotExist:
        return dict(status=False, info='Imagem não encontrada')

    # Update upload picture image
    if request.files.get('upload'):
        img_path = site.get_image_path(IMAGE_PATH)
        original_file = os.path.join(img_path, picture.original_image)
        normalized_file = os.path.join(img_path, picture.normalized_image)
        thumbnail_file = os.path.join(img_path, picture.thumbnail_image)
        upload_response = upload_image(request, original_file, normalized_file, thumbnail_file, ORIG_SIZE, NORM_SIZE, THUMB_SIZE)
        if not upload_response['status']:
            return upload_response

    # Upload data
    picture.title = title
    picture.description = description
    picture.save()

    # Images data
    img_url = '%s/%s/' % (host, IMAGE_DIR)
    original_url = img_url + picture.original_image
    normalized_url = img_url + picture.normalized_image
    thumbnail_url = img_url + picture.thumbnail_image

    # Lista de pictures atualizada
    try:
        picture_list = template('pictures_admin_list.html', site=site, host=host, csrf=csrf,
                                portfolio=portfolio, img_url=img_url)
    except Exception as exp:
        return dict(status=False, info='%s' % exp)

    # Return OK
    return dict(status=True, info='Atualizada com sucesso', picture_id=picture.get_id(),
                original=original_url, normalized=normalized_url, thumbnail=thumbnail_url,
                picture_list=picture_list)
Beispiel #48
0
def upload_file(request, object_id):
	"""
		takes every files sent by the request upload and insert them inside the database.
	"""
	a = get_object_or_404(Album, pk=object_id)

	if request.method == 'POST':		
		for file in request.FILES.getlist('file'):
			p = Picture(picture=file, album=a)
			p.save()

		return render_to_response('success/url.html', RequestContext(request, {}))

	else:
		form = UploadFileForm()

	context = {'form':form, 'album':a }

	return render_to_response('admin/albums/upload.html', RequestContext(request, context))
Beispiel #49
0
 def post(self, request):
     # Get username from html
     username = request.POST.get("username")
     # Check if username is empty
     if username != "":
         # Look for username in the database
         # Filter by username
         user = User.objects.filter(user_name=username)
         # If username exists in the database return its account_id
         if user.count() > 0:
             return redirect("show_gallery:template1", pk=user.values("account_id")[0]["account_id"])
         else:
             r = requests.get(
                 "https://api.instagram.com/v1/users/search?access_token=1497402817.1fb234f.1b8969bb3b304945a6782ae574069017&q={}".format(
                     username
                 )
             )
             # Check if the API request returns any data, meaning that the user exists in instagram
             data = r.json()["data"]
             if data != []:
                 # Add user to database
                 user = getUser(data, username)
                 username = user["username"]
                 id = user["id"]
                 new_user = User(account_id="{}".format(id), user_name="{}".format(username))
                 new_user.save()
                 # Get the pictures
                 r = requests.get(
                     "https://api.instagram.com/v1/users/{}/media/recent?access_token=1497402817.1fb234f.1b8969bb3b304945a6782ae574069017".format(
                         id
                     )
                 )
                 r = r.json()
                 for picture in r["data"]:
                     picture_name = picture["images"]["standard_resolution"]["url"]
                     new_pic = Picture(user_name=new_user, picture_name="{}".format(picture_name))
                     new_pic.save()
                 return redirect("show_gallery:template1", pk=id)
             # User does not exist
             else:
                 return render(request, "show_gallery/index.html", {"error_message": "User does not exist"})
     else:
         return render(request, "show_gallery/index.html", {"error_message": "Empty field"})
Beispiel #50
0
def upload_image(request):
    if request.method == "POST":
        if len(request.FILES) > 0:
            filename = save_file(request.FILES['picture'])

            width, height = get_image_size(filename)

            picture = Picture()
            picture.picture_url = filename
            picture.posted_on = datetime.datetime.now()
            picture.text = "testing hardstyle"
            picture.published = True
            picture.width = width
            picture.height = height
            picture.save()

            response_data = {}
            response_data['image_id'] = picture.pk

            return HttpResponse(simplejson.dumps(response_data), mimetype="application/json")
Beispiel #51
0
 def get(self):
     imgid = self.request.get("img_id")
     if imgid:
         imgid = int(imgid)
     else:
         self.error(500)
         return
     greeting = Picture.get_by_id(imgid)
     if not greeting:
         self.error(404)
     elif greeting.df:
         self.response.headers["Content-Type"] = "application/x-www-form-urlencoded"
         self.response.out.write(greeting.df)
     else:
         self.error(505)
Beispiel #52
0
def viewGallery(request):

  try:
      page = int(request.GET.get('step', '1')) - 1
  except:
      page = 0

  data = Picture.all()
  paginator = ObjectPaginator(data, 25)
  if page>=paginator.pages:
      page = paginator.pages - 1

  params = {
      "pictures" : paginator.get_page(page),
      "steps" : range(1,paginator.pages+1),
      "step" : page+1
  }

  return respond(request, 'gallery.html', params)
Beispiel #53
0
def create_picture(session, orga, name="testPicture"):
    picture = Picture(orga)
    picture.name = name
    picture.filename = name
    picture.radiotext = name
    picture.radiolink = name
    picture.image_url_prefix = name
    session.add(picture)
    session.commit()
    Channel.query.filter_by(id=1).first().default_picture_id = picture.id
    Channel.query.filter_by(id=2).first().default_picture_id = picture.id
    session.commit()
    time.sleep(config.SPI_GENERATION_INTERVAL * 3)
    return picture
Beispiel #54
0
def picture_delete(site, host, netloc, csrf, logged_in, user_id_logged_in):
    """
    Delete picture post url
    """

    # POST parameters
    site_id = int(request.POST.get('site'))
    user_id = int(request.POST.get('user'))
    portfolio_id = int(request.POST.get('portfolio'))
    picture_id = int(request.POST.get('picture'))

    # Portfolio
    try:
        portfolio = Portfolio.get(Portfolio.id == portfolio_id, Portfolio.site == site)
    except Portfolio.DoesNotExist:
        return dict(status=False, info='Portfólio não encontrado')

    # Picture
    try:
        picture = Picture.get(Picture.id == picture_id, Picture.site == site, Picture.portfolio == portfolio)
    except Picture.DoesNotExist:
        return dict(status=False, info='Imagem não encontrada')

    # Delete picture
    site_img_path = site.get_image_path(IMAGE_PATH)
    picture.delete_all(site_img_path)

    # Images url
    img_url = '%s/%s/' % (host, IMAGE_DIR)

    # Lista de pictures atualizada
    try:
        picture_list = template('pictures_admin_list.html', site=site, host=host, csrf=csrf,
                                portfolio=portfolio, img_url=img_url)
    except Exception as exp:
        return dict(status=False, info='%s' % exp)

    # Return OK
    return dict(status=True, info='Apagado com sucesso', picture_id=picture_id, picture_list=picture_list)
Beispiel #55
0
def upload(request):
    if request.method == "POST":
        
        filename = str(int(random.random() * 1000000)) + str(int(time.time())) + ".jpg"
        fh = open(settings.MEDIA_ROOT + filename , "wb")
        fh.write(request.POST['base64_image'].decode('base64'))
        fh.close()
        
        width, height = get_image_size(filename)

        picture = Picture()
        picture.picture_url = filename
        picture.posted_on = datetime.datetime.now()
        picture.width = width
        picture.height = height
        picture.text = "testing hardstyle"
        picture.save()

        response_data = {}
        response_data['image_id'] = picture.pk

        return HttpResponse(simplejson.dumps(response_data), mimetype="application/json")
    else:
        return HttpResponseRedirect("/")
Beispiel #56
0
def picture_add(site, host, netloc, csrf, logged_in, user_id_logged_in):
    """
    Add picture post url
    """

    # POST parameters
    site_id = int(request.POST.get('site'))
    user_id = int(request.POST.get('user'))
    portfolio_id = int(request.POST.get('portfolio'))
    title = request.POST.get('title')
    description = request.POST.get('description')

    # Portfolio
    try:
        portfolio = Portfolio.get(Portfolio.id == portfolio_id, Portfolio.site == site)
    except Portfolio.DoesNotExist:
        return dict(status=False, info='Portfólio não encontrado')

    # Upload picture image
    start_index = 1
    try:
        pictures = site.pictures.order_by(Picture.id.desc())
        last_picture = pictures.get()
        start_index = last_picture.id + 1
    except Picture.DoesNotExist:
        pass
    img_path = site.get_image_path(IMAGE_PATH)
    img_url = '%s/%s/' % (host, IMAGE_DIR)
    upload_response = upload_new_image(request, 'picture', start_index, img_path, img_url, ORIG_SIZE, NORM_SIZE, THUMB_SIZE)
    if not upload_response['status']:
        return upload_response

    # Upload data
    original_image = upload_response['original_filename']
    normalized_image = upload_response['normalized_filename']
    thumbnail_image = upload_response['thumbnail_filename']
    original_url = upload_response['original_url']
    normalized_url = upload_response['normalized_url']
    thumbnail_url = upload_response['thumbnail_url']

    # Create Picture
    picture_created = None
    with db.transaction():
        try:
            picture_created = Picture.create(site=site,
                                             portfolio=portfolio,
                                             title=title,
                                             description=description,
                                             original_image=original_image,
                                             normalized_image=normalized_image,
                                             thumbnail_image=thumbnail_image)
        except IntegrityError as exp:
            if picture_created:
                picture_created.delete_instance(IMAGE_PATH)
            else:
                site_img_path = site.get_image_path(IMAGE_PATH)
                if original_image:
                    original_file = os.path.join(site_img_path, original_image)
                    if os.path.exists(original_file):
                        os.remove(original_file)
                if normalized_image:
                    normalized_file = os.path.join(site_img_path, normalized_image)
                    if os.path.exists(normalized_file):
                        os.remove(normalized_file)
                if thumbnail_image:
                    thumbnail_file = os.path.join(site_img_path, thumbnail_image)
                    if os.path.exists(thumbnail_file):
                        os.remove(thumbnail_file)
            # Return error
            return dict(status=False, info='%s' % exp)

    # Lista de pictures atualizada
    try:
        picture_list = template('pictures_admin_list.html', site=site, host=host, csrf=csrf,
                                portfolio=portfolio, img_url=img_url)
    except Exception as exp:
        return dict(status=False, info='%s' % exp)

    # Return OK
    return dict(status=True, info='Adicionada com sucesso', picture_id=picture_created.get_id(),
                original=original_url, normalized=normalized_url, thumbnail=thumbnail_url,
                picture_list=picture_list)
Beispiel #57
0
    def get(self,
            flip_horizontal,
            width,
            flip_vertical,
            height,
            halign,
            valign,
            url):

        url = self.validate_url(url)

        width = width and int(width) or 0
        height = height and int(height) or 0

        if width > MAX_WIDTH:
            width = MAX_WIDTH
        if height > MAX_HEIGHT:
            height = MAX_HEIGHT

        if not halign:
            halign = "center"
        if not valign:
            valign = "middle"

        key = "%d_%d_%s_%s_%s" % (
                width,
                height,
                halign,
                valign,
                url
        )

        extension = splitext(url)[-1]
        image_format = extension in ('.jpg', '.jpeg') and JPEG or PNG

        data = memcache.get(key)

        self.response.headers['Cache-Key'] = key
        if data is not None:
            results = data
            self.response.headers['Cache-Hit'] = 'True'
        else:
            query = "SELECT * FROM Picture WHERE url = :1 LIMIT 1"
            pictures = db.GqlQuery(query, url).fetch(1)

            try:
                if len(pictures) > 0: 
                    picture = pictures[0]
                    if picture.is_expired():
                        img = picture.fetch_image()
                        try:
                            picture.put()
                        except RequestTooLargeError:
                            picture.rebalance_picture_size(self.transform)
                            picture.put()
                    else:
                        img = Image(picture.picture)
                else:
                    picture = Picture()
                    picture.url = url
                    img = picture.fetch_image()
                    try:
                        picture.put()
                    except RequestTooLargeError:
                        picture.rebalance_picture_size(self.transform)
                        picture.put()
            except ImageNotFoundError:
                self._error(404, 'Your image source is not found!')
                return

            results = self.transform(img, width, flip_horizontal, height, flip_vertical, image_format, halign, valign)

            memcache.set(key=key,
                     value=results,
                     time=EXPIRATION) # ONE MONTH

            self.response.headers['Cache-Hit'] = 'False'

        self.response.headers['Content-Type'] = image_format == JPEG and 'image/jpeg' or 'image/png'
        self.response.out.write(results)
Beispiel #58
0
    def get(self,
            flip_horizontal,
            width,
            flip_vertical,
            height,
            halign,
            valign,
            url):
        if not url:
            self._error(400, 'The url argument is mandatory!')
            return

        if not width and not height:
            self._error(400, 'Either width or height are mandatory!')

        url = join('http://', url)

        if not self._verify_allowed_domains():
            self._error(404, 'Your domain is not allowed!')
            return

        if not self._verify_allowed_sources(url):
            self._error(404, 'Your image source is not allowed!')
            return

        width = width and int(width) or 0
        height = height and int(height) or 0

        if width > MAX_WIDTH:
            width = MAX_WIDTH
        if height > MAX_HEIGHT:
            height = MAX_HEIGHT

        if not halign:
            halign = "center"
        if not valign:
            valign = "middle"

        key = "%d_%d_%s_%s_%s" % (
                width,
                height,
                halign,
                valign,
                url
        )

        extension = splitext(url)[-1]
        image_format = extension in ('.jpg', '.jpeg') and JPEG or PNG

        data = memcache.get(key)

        self.response.headers['Cache-Key'] = key
        if data is not None:
            results = data
            self.response.headers['Cache-Hit'] = 'True'
        else:
            query = "SELECT * FROM Picture WHERE url = :1 LIMIT 1"
            pictures = db.GqlQuery(query, url).fetch(1)
            
            try:
                if len(pictures) > 0: 
                    picture = pictures[0]
                    if picture.is_expired():
                        img = picture.fetch_image()
                        picture.put()
                    else:
                        img = Image(picture.picture)
                else:
                    picture = Picture()
                    picture.url = url
                    img = picture.fetch_image()
                    picture.put()
            except ImageNotFoundError:
                self._error(404, 'Your image source is not found!')
                return

            if float(width) / float(img.width) > float(height) / float(img.height):
                img.resize(width=width)
                image_width = width
                image_height = float(width) / float(img.width) * float(img.height)
            else:
                img.resize(height=height)
                image_width = float(height) / float(img.height) * float(img.width)
                image_height = height

            rect = BoundingRect(height=image_height, width=image_width)
            rect.set_size(height=height, width=width, halign=halign, valign=valign)

            if not width:
                width = rect.target_width
            if not height:
                height = rect.target_height

            img.crop(left_x=rect.left,
                     top_y=rect.top,
                     right_x=rect.right,
                     bottom_y=rect.bottom)

            if flip_horizontal:
                img.horizontal_flip()
            if flip_vertical:
                img.vertical_flip()

            results = img.execute_transforms(output_encoding=image_format, quality=QUALITY)

            memcache.set(key=key,
                     value=results,
                     time=EXPIRATION) # ONE MONTH


            self.response.headers['Cache-Hit'] = 'False'

        self.response.headers['Content-Type'] = image_format == JPEG and 'image/jpeg' or 'image/png'
        self.response.out.write(results)
Beispiel #59
0
def upload_picture(request):
    """Upload picture view.
    """
    if request.method == "POST":
        picture = Picture()
        picture.user = request.user
        form = UploadFileForm(request.POST, request.FILES, instance=picture)
        response = {}

        if form.is_valid():
            picture.picture = request.FILES["picture"]
            picture.picture.name = unidecode(picture.picture.name)
            picture.save()

            ### nasty error at 3:45 AM ;/
            try:
                rotate_picture(picture)
                picture.update_thumb()
                picture.save()
            except:
                import sys, traceback

                traceback.print_exc(file=sys.stdout)
                picture.delete()
                response["status"] = "UPLOAD ERROR. PUT HELMET ON AND EVACUATE!!!"
                response = json.dumps(response)
                return HttpResponse(response)
            response["url"] = picture.picture_thumb.url
            response["id"] = picture.id
            response = json.dumps(response)
        else:
            response = "Failed to upload"
    else:
        if request.GET.has_key("gallery_id"):
            preffered_gallery = int(request.GET["gallery_id"])
        else:
            preffered_gallery = None
        galleries = Gallery.objects.filter(user=request.user)
        return render(request, "upload.html", {"galleries": galleries, "preffered_gallery": preffered_gallery})
    return HttpResponse(response)
Beispiel #60
0
def radiovis_gallery_edit(request, id):
    """Edit a channel."""

    object = None
    errors = []

    plugitapi = PlugItAPI(config.API_URL)
    orga = plugitapi.get_orga(request.args.get('ebuio_orgapk') or request.form.get('ebuio_orgapk'))

    sp = None
    if orga.codops:
        sp = ServiceProvider.query.filter_by(codops=orga.codops).order_by(ServiceProvider.codops).first()

    if id != '-':
        object = Picture.query.filter_by(orga=int(request.args.get('ebuio_orgapk') or request.form.get('ebuio_orgapk')),
                                         id=int(id)).first()

    if request.method == 'POST':

        if not object:
            object = Picture(int(request.form.get('ebuio_orgapk')))

        if sp:
            object.image_url_prefix = sp.image_url_prefix

        object.name = request.form.get('name')
        object.radiotext = request.form.get('radiotext')
        object.radiolink = request.form.get('radiolink')

        def add_unique_postfix(fn):
            """__source__ = 'http://code.activestate.com/recipes/577200-make-unique-file-name/'"""
            if not os.path.exists(fn):
                return fn

            path, name = os.path.split(fn)
            name, ext = os.path.splitext(name)

            make_fn = lambda i: os.path.join(path, '%s(%d)%s' % (name, i, ext))

            for i in xrange(2, sys.maxint):
                uni_fn = make_fn(i)
                if not os.path.exists(uni_fn):
                    return uni_fn

            return None

        def unique_filename(fn):

            path, name = os.path.split(fn)
            name, ext = os.path.splitext(name)

            make_fn = lambda i: os.path.join(path, '%s%s' % (str(uuid.uuid4()), ext))

            for i in xrange(2, sys.maxint):
                uni_fn = make_fn(i)
                if not os.path.exists(uni_fn):
                    return uni_fn

            return None

        new_file = False
        if request.files:
            new_file = True
            file = request.files['file']
            if file:
                filename = secure_filename(file.filename)
                full_path = unique_filename('media/uploads/radiovis/gallery/' + filename)
                path, name = os.path.split(full_path)
                file.save(full_path)
                if object.filename:
                    try:
                        os.unlink(object.filename)
                    except:
                        pass
                object.filename = name

            # Check errors
            if object.name == '':
                errors.append("Please set a name")

            if object.radiotext == '':
                errors.append("Please set a text")

            if object.radiolink == '':
                errors.append("Please set a link")

            if object.filename == '' or object.filename is None:
                errors.append("Please upload an image")
            else:

                if imghdr.what(full_path) not in ['jpeg', 'png']:
                    errors.append("Image is not an png or jpeg image")
                    os.unlink(full_path)
                    object.filename = None
                else:
                    im = Image.open(full_path)
                    if im.size != (320, 240):
                        errors.append("Image must be 320x240")
                        del im
                        os.unlink(full_path)
                        object.filename = None

        pieces = urlparse.urlparse(object.radiolink)

        if pieces.scheme not in ['http', 'https', 'ftp']:
            errors.append("The link is not valid")

        # If no errors, save
        if not errors:

            # Upload to s3
            if new_file:
                try:
                    if config.STANDALONE:
                        send_image_to_mock_api({name: open(full_path, 'rb')})
                    else:
                        awsutils.upload_public_image(sp, name, full_path)
                except:
                    pass
            # TODO Clean up old images on S3

            if not object.id:
                db.session.add(object)

            db.session.commit()

            try:
                # Remove local copy
                os.unlink(full_path)
            except:
                pass

            return PlugItRedirect('radiovis/gallery/?saved=yes')

        try:
            # Remove local copy
            os.unlink(full_path)
        except:
            pass

    if object:
        object = object.json

    return {'object': object, 'errors': errors}