Example #1
0
    def post(self):
        if self.get_uploads('image'):
            upload_files = self.get_uploads('image')
            blob_info = upload_files[0]

        else:
            blob_info = None

        if self.form.validate():
            form = self.form
            photo = Photo(name=form.name.data, image=blob_info)

            if (form.lat.data and form.lon.data):
                photo.location = db.GeoPt(lat=form.lat.data, lon=form.lon.data)

            photo.put()
            response = redirect_to('collector-thanks', )

        else:
            form = self.form
            photo = Photo(name=form.name.data,
                          email=form.email.data,
                          phone=form.phone.data,
                          image=blob_info)

            photo.put()
            response = redirect_to('collector', photo=photo.key())

        # Clear the response body.
        response.data = ''
        return response
Example #2
0
def save_photo(file, user_id=None, spot_id=None):
    filename = str(uuid.uuid4()) + "." + file.filename.rsplit('.', 1)[1].lower()
    if user_id is not None:
        s3.Bucket(bucket).put_object(Key=filename, Body=file)
        new_photo = Photo(user_id=user_id, filename=filename)
        db.session.add(new_photo)
    if spot_id is not None:
        s3.Bucket(bucket).put_object(Key=filename, Body=file)
        new_photo = Photo(spot_id=spot_id, filename=filename)
        db.session.add(new_photo)
    db.session.commit()
Example #3
0
def up_photo():
    if request.method == 'POST':
        print('True')
        img = request.files.get('fileList')
        print(img.filename)
        im = misc.imread(img)
        path = os.path.dirname(__file__)
        print('g.user is ', g.user.username)
        if not os.path.exists(path):
            os.makedirs(path)
        basepath = os.path.dirname(
            __file__) + '/static/photo' + '/' + g.user.username
        print(basepath)
        if not os.path.exists(basepath):
            os.makedirs(basepath)
        #########产生JK序列#########
        JK = generate_JK(im)
        #########加密算法#########
        miwen = jiami(im, np.array(JK))
        miwen = Image.fromarray(miwen.astype(np.uint8))
        filepath = os.path.join(basepath, img.filename)
        miwen.save(filepath)
        photo_exit = Photo.query.filter(Photo.photoname == img.filename).all()
        usernames = []
        for k in photo_exit:
            usernames.append(k.username)
        print(usernames)
        print(g.user.username)
        if photo_exit is None:
            photo_new = Photo(
                username=g.user.username,
                photoname=img.filename,
                photopath='http://172.31.102.126:4241/static/photo/' +
                g.user.username + '/' + img.filename)
            db.session.add(photo_new)
            db.session.commit()
        elif g.user.username not in usernames:
            photo_new = Photo(
                username=g.user.username,
                photoname=img.filename,
                photopath='http://172.31.102.126:4241/static/photo/' +
                g.user.username + '/' + img.filename)
            db.session.add(photo_new)
            db.session.commit()
        return jsonify(g.user.username, img.filename)
        # for file in request.files.getlist('file'): # 这里改动以存储多份文件
        #     if file and allowed_file(file.filename):
        #         filename = secure_filename(file.filename)
        #         file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

    else:
        return render_template('up_photo.html')
Example #4
0
def getTrailsAndPhotos(lon, lat, cnt, resort, trails, photos):
    """
    gets all trails nearby given resort
    associates all created trails with resortid
    and adds photo for trail into the photos for the resort
    """
    data = None
    try:
        if resort is None:
            data = fetch.fetchJSON(
                'https://www.hikingproject.com/data/get-trails?lat=' +
                str(lat) + '&lon=' + str(lon) + '&maxDistance=10&maxResults=' +
                str(cnt) +
                '&sort=distance&key=200217902-4d9f4e11973eb6aa502e868e55361062'
            )
        else:
            data = fetch.fetchJSON(
                'https://www.hikingproject.com/data/get-trails?lat=' +
                str(resort.lat) + '&lon=' + str(resort.lon) +
                '&maxDistance=10&maxResults=' + str(cnt) +
                '&sort=distance&key=200217902-4d9f4e11973eb6aa502e868e55361062'
            )
    except ValueError as e:
        return trails, photos
    for t in data['trails']:
        if t['id'] not in trails:
            trail = Trail(name=t['name'], id=t['id'])
            trail.difficulty = t['difficulty'] if 'difficulty' in t else None
            trail.summary = t['summary'] if 'summary' in t else None
            trail.stars = t['stars'] if 'stars' in t else None
            trail.starVotes = t['starVotes'] if 'starVotes' in t else None
            trail.lat = t['latitude'] if 'latitude' in t else None
            trail.lon = t['longitude'] if 'longitude' in t else None
            trail.length = t['length'] if 'length' in t else None
            trail.ascent = t['ascent'] if 'ascent' in t else None
            trail.descent = t['descent'] if 'descent' in t else None
            try:
                youtubedata = fetch.fetchJSON(
                    'https://www.googleapis.com/youtube/v3/search?q=' +
                    trail.name + ' trail' +
                    '&part=snippet&type=video&maxResults=25&key=AIzaSyDRwflQaI1Zq5bqKVQJ2YBDHb7l7oD1L2o'
                )
                trail.youtubeid = youtubedata['items'][0]['id']['videoId']
            except ValueError:
                trail.youtubeid = None
            except IndexError:
                trail.youtubeid = None
            trails[t['id']] = trail
            if 'imgMedium' in t and t['imgMedium'] != "":
                photo = Photo(id=trail.id,
                              name=trail.name + " photo",
                              lat=trail.lat,
                              lon=trail.lon)
                photo.url = t['imgMedium']
                photos[t['imgMedium']] = photo
                photo.trail = trails[t['id']]
                photo.content = getPhotoContents(photo.url)
        resort.trails.append(trails[t['id']])
        resort.photos += trails[t['id']].photos
    return trails, photos
Example #5
0
def post_photo(user, request):
    yelp_id = request.form.get('yelp_id')
    if not yelp_id:
        return {'error': 'Missing yelp_id.'}, HTTP_STATUS_BAD_REQUEST

    restaurant = yelp_client.get_restaurant(yelp_id)
    if not restaurant:
        return {'error': 'Invalid yelp_id'}, HTTP_STATUS_INTERNAL_SERVER_ERROR

    if 'image' not in request.files:
        return {'error': 'No image attached!'}, HTTP_STATUS_BAD_REQUEST

    file = request.files.get('image')

    try:
        user_id = user.id

        photo_url = s3_client.upload_photo(user_id, file)

        photo = Photo(user_id=user_id,
                      photo_url=photo_url,
                      yelp_id=restaurant.id,
                      restaurant_name=restaurant.name)

        session.add(photo)
        session.flush()
        session.commit()

        return photo.to_dict(), HTTP_STATUS_OK
    except S3UploadFailedError as e:
        logging.error(str(e))
        return {'error': 'Failed to upload image!'}, HTTP_STATUS_BAD_REQUEST
def index(request):
    # return HttpResponse("Hello, world. You're at the photoslideshow app.")

    #latest_photos = Photo.objects.all()[:5]
    #output = ', '.join([p.url for p in latest_photos])
    #output = ''

    xmlphotoset = get_photos_for_vivid_festival()

    photoset = xmlphotoset.find('photoset')
    #print(photoset.attrib)

    latest_photos = []
    for photo in photoset.findall('photo'):
        photo_id = photo.attrib['id']

        photo_title = photo.attrib['title']
        photo_url = get_photo_url_large(photo_id)
        #photo_created_date = ''
        p = Photo(title=photo_title, url=photo_url, created_date='')
        latest_photos.append(p)

    #for p in latest_photos:
    #new_image = '<img src="' + p.url + '" + alt="' + p.title + '" > <br/>'
    #output += new_image
    #return HttpResponse(output)
    return render(request, 'display_photo.html', {
        'photos': latest_photos,
        'firstphoto': latest_photos[0]
    })
Example #7
0
def build_photo(id, line):
    elements = line.split()

    orientation = elements[0]
    tags = set(elements[2:2 + int(elements[1])])

    return Photo(id=id, orientation=orientation, tags=tags)
Example #8
0
def photographer_upload():
    # if request method is post
    if request.method == 'POST':
        form = PhotoUploadForm(name=request.form.get("name"),
                               file=request.files.get("file"))
        if form.validate():
            # get the photographer id from the user
            # save the image and link to photographer
            image_file = form.file.data
            photo = Photo(name=form.name.data,
                          photographer_id=current_user.photographer.id,
                          file=image_file.read())
            image = Image.open(image_file)
            file_type = image_file.headers.get("Content-Type")
            photo.add_image_data(*image.size, file_type)
            # save photo to db
            session_object = db_session()
            session_object.add(photo)
            session_object.commit()
            # success message
            flash("Image Uploaded Successfully", "success")
            return redirect(url_for('dashboard'))
        else:
            return render_template('photographer_uploads.html', form=form)
    # if the request is any other than get
    return render_template('photographer_uploads.html', form=PhotoUploadForm())
Example #9
0
 def add_photo(self, album_id=''):
     if request.method == 'POST':
         album = Album.get(id=album_id)
         photo = Photo()
         photo.album = album
         file = request.files['files']
         photo_title, size, photo_path, photo_url, thumb_url, thumb_path = self.gal_man.add_photo(
             album, file)
         result = []
         result.append({
             'name': photo_title,
             'size': size,
             'url': photo_url,
             'thumbnail_url': thumb_path,
             "delete_type": "POST",
         })
         photo.title = photo_title
         photo.photo_path = photo_path
         photo.thumb_path = thumb_path
         photo.photo_url = photo_url
         photo.thumb_url = thumb_url
         photo.size = size
         photo.save()
         return json.dumps(result)
     else:
         return 'response'
Example #10
0
def edit():
    form = EditForm(g.user.nickname)
    if request.method == 'POST': avatar_img_file = request.files[form.avatar_img.name]
    else: avatar_img_file = None
    if form.validate_on_submit(avatar_img_file):            
        g.user.nickname = form.nickname.data
        g.user.about_me = form.about_me.data
        db.session.add(g.user)
        db.session.commit()
        if form.avatar_img.data:
            f = request.files[form.avatar_img.name]
            pic = Photo(fname = "", timestamp = datetime.utcnow(), owner = g.user)
            db.session.add(pic)
            db.session.commit()
            #try:
            pic.fname = (str(pic.id)+"."+f.filename.split(".")[-1])
            f.save(os.path.join(UPLOAD_IMG_DIR, pic.fname))
            g.user.set_avatar(pic)
            db.session.add(pic)
            db.session.add(g.user)
            db.session.commit()
                
        flash('Your changes have been saved.', 'info')
        return redirect(url_for('user', nickname=g.user.nickname))
    else:
        form.nickname.data = g.user.nickname
        form.about_me.data = g.user.about_me
    return render_template('edit.html',
        form = form,
        user = g.user)
Example #11
0
def add_media_item(media_type):
    logger.info("add_media_item %s" % media_type)
    file = request.files['file']
    filename = file.filename
    group_id = request.values.get("group_id")
    album_id = request.values.get("album_id")
    secured_filename = secure_filename(filename)
    file_path = os.path.join(config.UPLOAD_FOLDER, secured_filename)
    file.save(file_path)
    logger.info("save file %s to file path %s" % (filename, file_path))
    # file_url = url_for('uploaded_file', filename=filename)
    file_url = "/static/upload/" + secured_filename
    photo = Photo(album_id=album_id,
                  group_id=group_id,
                  url=file_url,
                  media_type=media_type,
                  name=filename)
    db.session.add(photo)
    db.session.commit()
    data = {
        "photo_id": photo.id,
        "album_id": album_id,
        "group_id": group_id,
        "file_url": file_url
    }
    return make_response(jsonify(data))
Example #12
0
def create_photo(request):
    """
    Gestiona la creación de una nueva foto
    :param request: objeto request
    :return: objeto response
    """

    new_photo = None

    if request.method == 'POST': # si le hemos dado al boton crear, vamos a validar el formulario y a guardar la foto
        photo_with_user = Photo(owner=request.user) # creamos foto para el usuario autenticado
        form = PhotoForm(request.POST, instance=photo_with_user) # Le indicamos que en lugar de instanciarse una foto propio,
                                                           # use new_photo que tiene ya asignado un usuario
        if form.is_valid():
            new_photo = form.save() # guardamos la foto en la base de datos
            form = PhotoForm() #para que nos borre la info que ya habíamos metido en el formulario

    else: # si no, creamos un formulario vacio
        form = PhotoForm()

    context = {
        'form' : form,
        'photo' : new_photo
    }

    return render(request, 'photos/create_photo.html', context)
Example #13
0
def new_photo(slide_id):
    slide = Slide.query.filter_by(id=slide_id).first()
    if not slide:
        flash(BAD_KITTY, 'danger')
        return redirect(url_for('index'))

    journey = Journey.query.filter_by(id=slide.journey_id,
                                      user_id=current_user.id).first()
    if not journey:
        flash(BAD_KITTY, 'danger')
        return redirect(url_for('index'))

    form = NewPhotoForm(slide_id=slide_id)
    if form.validate_on_submit():
        photo = Photo()
        tmp = tempfile.NamedTemporaryFile(suffix='.jpg')
        form.photo.data.save(tmp)
        tmp.flush()
        photo.create(form.data['title'], form.data['description'], slide_id,
                     tmp.name)
        db.session.add(photo)
        db.session.commit()
        flash('Photo added to slide', 'success')
        return redirect(url_for('edit_slide', slide_id=slide_id))

    flash_errors(form)
    return render_template('new-photo.html', form=form, title='New Photo')
Example #14
0
def run():
    redis_client = get_redis_client()
    redis_client.delete(REDIS_KEY['USER_LIKED_COUNT'])
    redis_client.delete(REDIS_KEY['USER_LIKES_COUNT'])
    redis_client.delete(REDIS_KEY['USER_PHOTO_COUNT'])
    photos = Photo().select(['id', 'user_id',
                             'likes_count']).where('status', '=',
                                                   0).findall(limit=1000000)
    for photo in progress.bar(photos):
        current_liked_count = redis_client.hget(REDIS_KEY['USER_LIKED_COUNT'],
                                                photo.user_id) or 0
        redis_client.hset(REDIS_KEY['USER_LIKED_COUNT'], photo.user_id,
                          int(current_liked_count) + int(photo.likes_count))

        current_photo_count = redis_client.hget(REDIS_KEY['USER_PHOTO_COUNT'],
                                                photo.user_id) or 0
        redis_client.hset(REDIS_KEY['USER_PHOTO_COUNT'], photo.user_id,
                          int(current_photo_count) + 1)

        photo_like = Photo_Like().findall_by_photo_id(photo.id)
        for item in photo_like:
            current_likes_count = redis_client.hget(
                REDIS_KEY['USER_LIKES_COUNT'], item.user_id) or 0
            redis_client.hset(REDIS_KEY['USER_LIKES_COUNT'], item.user_id,
                              int(current_likes_count) + 1)
Example #15
0
def photos_from_zip(path,approved=True,user=None):
    """turn a zip file into a photos"""
    now = datetime.datetime.now()
    _ = now.strftime(Photo._meta.get_field('file').upload_to)
    zip_name = path.split('/')[-1]
    root = os.path.join(settings.MEDIA_ROOT,_)
    if not os.path.exists(root):
        os.mkdir(root)
    directory = os.path.join(root,'%s_%s'%(now.day,now.time()))
    os.mkdir(directory)
    new_path = os.path.join(directory,zip_name)
    os.chdir(directory)
    os.rename(path,new_path)
    command = 'unzip %s'%new_path
    process = Popen(command, stdout=PIPE, shell=True)
    process.communicate()
    for folder,_,files in os.walk('.'):
        for f in files:
            os.rename(os.path.join(folder,f),os.path.join(directory,f))
    folders = [f for f in os.listdir(directory) if os.path.isdir(f)]
    for f in folders:
        os.rmdir(f)
    files = [f for f in os.listdir(directory) if not os.path.isdir(f)]
    for f_path in files:
        print "creating photo!"
        photo = Photo(
            file = os.path.join(directory,f_path).split(settings.MEDIA_ROOT)[-1],
            source = "misc",
            approved = approved,
            user=user
            )
        photo.save()
    #all done, delete the zip!
    os.remove(new_path)
Example #16
0
	def upload():
		path = os.path.join(Config.UPLOADS_DEFAULT_DEST, str(current_user.id), request.form.get('slug'))
		path_min = os.path.join(Config.DEFAULT_MIN_DIR, str(current_user.id), request.form.get('slug'))
		
		# создаем директорию для фоток, если ее нет
		if not os.path.isdir(path):
			os.makedirs(path)
			
		# создаем директорию для миниатюр, если ее нет
		if not os.path.isdir(path_min):
			os.makedirs(path_min)
		
		album = Album.objects(slug=request.form.get('slug', ''), user=current_user.id).get()
		
		photos_list = album.photos
		for img in request.files.getlist("images"):
			if img.filename:
				file_path = photos.save(img, folder=path)
				filename = file_path.split('/')[-1]
				
				image = PilImage.open(file_path)
				exif_data = image.getexif()
				device = None
				created = None
				
				for tag_id in exif_data:
					tag = TAGS.get(tag_id, tag_id)
					data = exif_data.get(tag_id)
					try:
						if isinstance(data, bytes):
							data = data.decode()
						
						if f"{tag:25}".find('Model') == 0:
							device = data
						if f"{tag:25}".find('DateTimeOriginal') == 0:
							created = data
					except:
						pass
				
				ratio = (Config.WIDTH / float(image.size[0]))
				height = int((float(image.size[1]) * float(ratio)))
				image = image.resize((Config.WIDTH, height), PIL.Image.ANTIALIAS)
				file_min_path = image.save(os.path.join(path_min, filename))
				
				photo = Photo()
				photo.file = filename
				photo.device = device
				if created:
					photo.created = datetime.strptime(created, '%Y:%m:%d %H:%M:%S')
				
				photos_list.append(photo)
		
		# сортируем фотографии по дате создания в обратном порядке
		try:
			photos_list = sorted(photos_list, key=itemgetter('created'), reverse=True)
		except TypeError:
			photos_list = sorted(photos_list, key=itemgetter('file'))
		
		album.update(photos=photos_list)
Example #17
0
def save_images(offerId, images):
    from urllib.request import urlretrieve
    for i in images:
        from models import Photo
        im = Photo(offerId=offerId,
                   url=i)  # named params because no Photo.__init__
        path = "images/{0}/{1}.jpg".format(offerId, im.id)
        urlretrieve(i, path)
Example #18
0
 def testQueryPhoto(self):
     photo = Photo()
     photo.name = "Test Query Photo"
     photo.id = 50
     photo.trailid = 50
     self.acc.insertData([photo])
     self.assertEqual(self.acc.queryPhoto("Test Query Photo").id, 50)
     self.assertEqual(self.acc.queryPhoto("Test Query Photo").trailid, 50)
Example #19
0
def create_photo(user, image):
    m = Photo(user=user)
    if image:
        image.seek(0)
    m.save_file(image)
    m.save()
    lookedup = Photo.objects.get(id=m.id)
    return lookedup
Example #20
0
async def api_create_photo(request, *, name, url):
	check_admin(request) #检查request对象身上是否绑定了user
	if not name or not name.strip():
		raise APIValueError('name', 'name cannot be empty.')
	if not url or not url.strip():
		raise APIValueError('url', 'summary cannot be empty')
	photo = Photo(user_id=request.__user__.id, user_name=request.__user__.name, name=name.strip(), url=url.strip())
	await photo.save()
	return photo
Example #21
0
    def test_parse_photo(self):

        response = '''{"response":[{"pid":"146771291","aid":"100001227","owner_id":"6492",
            "src":"http://cs9231.vkontakte.ru/u06492/100001227/m_7875d2fb.jpg",
            "src_big":"http://cs9231.vkontakte.ru/u06492/100001227/x_cd563004.jpg",
            "src_small":"http://cs9231.vkontakte.ru/u06492/100001227/s_c3bba2a8.jpg",
            "src_xbig":"http://cs9231.vkontakte.ru/u06492/100001227/y_62a74569.jpg",
            "src_xxbig":"http://cs9231.vkontakte.ru/u06492/100001227/z_793e9682.jpg",
            "text":"test","user_id":6492,"width":10,"height":10,
            "created":"1298365200"},{"pid":"146772677","aid":"100001227","owner_id":-6492,
            "src":"http://cs9231.vkontakte.ru/u06492/100001227/m_fd092958.jpg",
            "src_big":"http://cs9231.vkontakte.ru/u06492/100001227/x_1f8ec9b8.jpg",
            "src_small":"http://cs9231.vkontakte.ru/u06492/100001227/s_603d27ab.jpg",
            "src_xbig":"http://cs9231.vkontakte.ru/u06492/100001227/y_6938f576.jpg",
            "src_xxbig":"http://cs9231.vkontakte.ru/u06492/100001227/z_6a27e9fd.jpg",
            "text":"test","user_id":6492,"width":10,"height":10,
            "created":"1260887080"}]}
            '''
        instance = Photo()
        owner = UserFactory(remote_id=6492)
        album = AlbumFactory(remote_id='6492_100001227')
        instance.parse(json.loads(response)['response'][0])
        instance.save()

        self.assertEqual(instance.remote_id, '6492_146771291')
        self.assertEqual(instance.album, album)
        self.assertEqual(instance.owner, owner)
        self.assertEqual(
            instance.src,
            'http://cs9231.vkontakte.ru/u06492/100001227/m_7875d2fb.jpg')
        self.assertEqual(instance.text, 'test')
        self.assertEqual(instance.width, 10)
        self.assertEqual(instance.height, 10)
        self.assertIsNotNone(instance.created)

        instance = Photo()
        group = GroupFactory(remote_id=6492)
        album = AlbumFactory(remote_id='-6492_100001227')
        instance.parse(json.loads(response)['response'][1])
        instance.save()

        self.assertEqual(instance.remote_id, '-6492_146772677')
        self.assertEqual(instance.album, album)
        self.assertEqual(instance.group, group)
Example #22
0
def photo_to_db(photo_url, subtitle, location_id):
    try:
        photo = Photo(photo_url=photo_url,
                      subtitle=subtitle,
                      location_id=location_id)
        db.session.add(photo)
        db.session.commit()
        return "Photo added. Photo id={}".format(photo.id)
    except Exception as e:
        return (str(e))
Example #23
0
    def createEvent(sessionId, eventArgs):
        '''
		Метод для создания событий (по сессии и списку аргументов)
		'''
        userId = SessionManager.getUser(sessionId)
        eName = 'Noname event'
        eTime = '2012-12-31'
        eDescription = 'No defenition'
        photo = Photo.objects.get(pk=1)
        eEventTypeId = 1
        eLatitude = 0
        eLongitude = 0
        eCountryId = Country.objects.get(pk=1)
        eCityId = City.objects.get(pk=1)
        eNamePlace = 'Noname place'

        if eventArgs.has_key('name'):
            eName = eventArgs['name']

        if eventArgs.has_key('time'):
            eTime = eventArgs['time']

        if eventArgs.has_key('description'):
            eDescription = eventArgs['description']

        if eventArgs.has_key('photo'):
            photo = Photo(photo=eventArgs['photo'])
            photo.save()
        else:
            photo = Photo.objects.get(pk=1)

        if eventArgs.has_key('eventTypeId'):
            eEventTypeId = eventArgs['eventTypeId']

        if eventArgs.has_key('longitude'):
            eLatitude = eventArgs['longitude']

        if eventArgs.has_key('latitude'):
            eLongitude = eventArgs['latitude']

        place = Place(cityId=eCityId,
                      countryId=eCountryId,
                      name=eNamePlace,
                      latitude=eLatitude,
                      longitude=eLongitude)
        place.save()
        newEvent = Event(creatorId=userId,
                         name=eName,
                         time=eTime,
                         description=eDescription,
                         photoId=photo,
                         eventTypeId_id=eEventTypeId,
                         PlaceId=place)
        newEvent.save()
        return newEvent.pk
Example #24
0
def generate_resized_photos():
    """ Get all photos from server, rezise them and save your paths in database"""
    urls = get_urls_photos_origin()
    Photo.objects.delete()
    for url in urls:
        photo_db = Photo(url=url)
        photo = get_photo_by_url(url)
        photo_db.path_small = create_resized_photo(photo, url, 'small')
        photo_db.path_medium = create_resized_photo(photo, url, 'medium')
        photo_db.path_large = create_resized_photo(photo, url, 'large')
        photo_db.save()
Example #25
0
def run():
    redis_client = get_redis_client()
    for table in ('photo', 'user'):
        redis_key = REDIS_KEY['TABLE_ITEMS'].format(table=table)
        if table == 'photo':
            result = Photo().findall_by_status(0, limit=1000000)
        elif table == 'user':
            result = User().findall(limit=1000000)

        for item in progress.bar(result):
            redis_client.hset(redis_key, item.id, json.dumps(item.to_dict()))
Example #26
0
def get_stubbed_photos(user=None, last_id=None):
    stubbed_page = list()

    photo = Photo(id=32432,
                  user_id=23432423,
                  photo_url=STUBBED_PHOTO_URL,
                  creation_date=datetime.today())
    for i in range(0, 15):
        stubbed_page.append(photo)

    return stubbed_page
Example #27
0
def add_event():
    if 'user_id' in session:
        user_id = session['user_id']
    else:
        return redirect(url_for('index'))

    print 'add event func'
    print request.form
    t_id = request.form['team_id']
    team_id = int(t_id[0])

    if request.form['event_time']:
        event_date = datetime.strptime(request.form['event_time'], '%d %B %Y')
    else:
        event_date = datetime.now()

    event = Event(
            title = request.form['event_title'],
            content = request.form['event_content'],
            timestamp = event_date,
            team_id = team_id,
            author_id = user_id
            )
    # category
    c_id = request.form['category_id'],
    print 'c_id', c_id
    if c_id[0]:
        print 'has category'
        event.category_id = c_id
    db.session.add(event)
    db.session.commit()

    date_path = event_date.strftime('%Y-%m')
    save_path = os.path.join(app.config['UPLOAD_FOLDER'], 
            'team-'+str(team_id), date_path)
    if not os.path.exists(save_path):
        os.makedirs(save_path)

    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        img_name = str(uuid.uuid4()) + '.' + filename.rsplit('.', 1)[1]
        file.save(os.path.join(app.config['UPLOAD_FOLDER'],
            'team-'+str(team_id), date_path, img_name))

        photo = Photo(
                path = os.path.join('team-'+str(team_id), date_path, filename),
                event_id = event.id
                )
        db.session.add(photo)
        db.session.commit()
    return redirect(url_for('admin_team', team_id=team_id)) 
Example #28
0
File: tests.py Project: bekas/MeToo
    def setUp(self):
        '''
		Метод начальной инициализации
		'''
        photo = Photo(photo='this is a photo, believe me ;)')
        photo.save()
        user = User(login='******', password='******', avatarId=photo, rating=0)
        user.save()
        user = User(login='******',
                    password='******',
                    avatarId=photo,
                    rating=0)
        user.save()
Example #29
0
def addphoto():
    code = 400
    data = {'error': {'message': 'Bad request'}}
    if request.method == 'POST':
        userid = request.json.get('userid')
        if userid and photo is not None:
            photos = Photo(userid, photo)
            db.session.add(user)
            db.session.commit()
            code = 200
            data = {'message': 'ok'}

    return json.dumps(data), code
Example #30
0
def uploadImg():
    imgBase64 = request.form['imgDataUrl']
    includePost = request.form['includePost']
    postId = request.form['postId']
    print "Include Post:", includePost
    print "PostId", postId
    img = base64.b64decode(imgBase64.split(",")[-1])

    if includePost == "true":
        print "including post..."
        pic = Photo(fname = "", timestamp = datetime.utcnow(), owner = g.user, post_id=(int(postId)))
    else:
        print "no post... only photo"
        pic = Photo(fname = "", timestamp = datetime.utcnow(), owner = g.user)
    db.session.add(pic)
    db.session.commit()
    pic.fname = (str(pic.id)+".png")
    db.session.add(pic)
    db.session.commit()
    with open(os.path.join(UPLOAD_IMG_DIR, pic.fname), "wb") as f:
        f.write(img)
    return jsonify({'response':'success'})