当前位置: 首页>>代码示例>>Python>>正文


Python models.Photo类代码示例

本文整理汇总了Python中models.Photo的典型用法代码示例。如果您正苦于以下问题:Python Photo类的具体用法?Python Photo怎么用?Python Photo使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Photo类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: photos_from_zip

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)
开发者ID:chriscauley,项目名称:django-unrest-media,代码行数:34,代码来源:utils.py

示例2: AlbumTest

class AlbumTest(TestCase):
    def setUp(self):
        self.user = User(username='sholmes', email='[email protected]',
                         first_name='Sherlock', last_name="Holmes",
                         password='watson')
        self.user.full_clean()
        self.user.save()
        self.photo = Photo(owner=self.user,
                           image='images/test.png',
                           name='test',
                           caption='testing')
        self.photo.clean()
        self.photo.save()
        self.tag = Tag(name='test tag', owner=self.user)
        self.tag.clean()
        self.tag.save()
        self.photo.tags.add(self.tag)
        self.album = Album(owner=self.user,
                           name='test album')
        self.album.clean()
        self.album.save()
        self.album.photos.add(self.photo)

    def test_id_creation(self):
        self.assertIsNotNone(self.album.id)

    def test_owner_entry(self):
        self.assertEqual(self.album.name, 'test album')

    def test_name_entry(self):
        self.assertEqual(self.photo.name, 'test')

    def test_album_to_photo_association(self):
        photos = Photo.objects.filter(album=self.album.id)
        self.assertEqual(photos[0].name, 'test')
开发者ID:jwhite007,项目名称:Photorize,代码行数:35,代码来源:test_models.py

示例3: new_photo

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')
开发者ID:aimxhaisse,项目名称:siduree,代码行数:25,代码来源:views.py

示例4: save_item

def save_item(item, update_desc=False):
    baidu_id = item.get('id')
    if baidu_id is None:
        return
    session = DB_Session()
    photo = session.query(Photo).filter(Photo.baidu_id==baidu_id).first()
    if not photo:
        photo = Photo(baidu_id=baidu_id,
                      photo_id=item['photo_id'],
                      image_url = item['image_url'],
                      image_width = item['image_width'],
                      image_height = item['image_height'],
                      thumbnail_url = item['thumbnail_url'],
                      thumbnail_width = item['thumbnail_width'],
                      thumbnail_height = item['thumbnail_height'],
                      thumb_large_url = item['thumb_large_url'],
                      thumb_large_width = item['thumb_large_width'],
                      thumb_large_height = item['thumb_large_height'],
                      from_url = item['from_url'],
                      obj_url = item['obj_url'],
                      desc = item['desc'],
                      image_date = item['date'],
                      insert_date = datetime.datetime.now()
                )
        session.add(photo)
        session.commit()
        logging.warn("add one item-%s" % photo.id)
    elif update_desc:
        photo.desc = item['desc']
        session.commit()
        logging.warn("update one item-%s" % photo.id)
    session.close()
开发者ID:wasw100,项目名称:app-ncdh,代码行数:32,代码来源:workers.py

示例5: add_photo

	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'
开发者ID:lpfan,项目名称:Wing-M.S.,代码行数:25,代码来源:gallery.py

示例6: get_photo

    def get_photo(self):
        if "photo" not in self.request.POST:
            logging.debug("no image uploaded for new item!")
            return None
        try:
            img = self.request.POST.get("photo")
            img_name = img.filename
            img_data = img.file.read()
            img = images.Image(img_data)

            img.im_feeling_lucky()
            img.resize(640, 480)
            png_data = img.execute_transforms(images.PNG)

            img.resize(200, 140)
            thumb = img.execute_transforms(images.PNG)

            photo = Photo(name=img_name, image=png_data, thumb=thumb)
            return photo.put()
        except images.BadImageError:
            self.error(400)
            self.response.out.write("Sorry, we had a problem processing the image provided.")
        except images.NotImageError:
            self.error(400)
            self.response.out.write(
                "Sorry, we don't recognize that image format."
                "We can process JPEG, GIF, PNG, BMP, TIFF, and ICO files."
            )
        except images.LargeImageError:
            self.error(400)
            self.response.out.write("Sorry, the image provided was too large for us to process.")
开发者ID:tchaikov,项目名称:beanfs,代码行数:31,代码来源:item.py

示例7: upload

def upload(request):
    if request.content_length/1000000 > 20:
        return error_response(400, 'Sorry, but the file must be under 20MB.')

    # Create photo object in database
    photo = Photo(datetime.today(), request.POST['file'].filename, request.client_addr, request.content_type, request.content_length)
    DBSession.add(photo)
    DBSession.flush()

    # Save uploaded file
    input_file = request.POST['file'].file
    input_file.seek(0)
    if not os.path.exists('data'):
        os.makedirs('data')
    if not os.path.exists('data/uploads'):
        os.makedirs('data/uploads')
    upload_path = os.path.join('data', 'uploads', str(photo.id))
    with open(upload_path, 'w') as f:
        shutil.copyfileobj(input_file, f)

    # Check the content type and rename as appropriate
    mime = magic.from_file(upload_path, mime=True)
    if mime not in ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/tiff', 'image/x-tiff']:
        resp = Response('Sorry, but we can only accept jpg, gif, or png files.')
        resp.status_code = 400
        resp.status_string = '400 Bad Request'
        return resp
    extension = {'image/jpeg': '.jpg', 'image/pjpeg': '.jpg',
                 'image/gif': '.gif', 'image/png': '.png',
                 'image/tiff': '.tiff', 'image/x-tiff': '.tiff'}[mime]
    os.rename(upload_path, upload_path + extension)
    photo.content_type = mime

    return Response('OK')
开发者ID:reberhardt7,项目名称:hcc-photo-upload,代码行数:34,代码来源:views.py

示例8: create_photo

def create_photo(file_path):
    photo_path, width, height = image_utils.fit_and_save(file_path)
    thumb_path = image_utils.generate_thumbnail(photo_path)
    photo_path, thumb_path = (relp(rp(p), PARENT_DIR) for p in (photo_path, thumb_path))
    photo = Photo(image_path=photo_path, thumbnail_path=thumb_path, width=width, height=height)
    photo.save()
    return photo
开发者ID:lumilux,项目名称:lumi,代码行数:7,代码来源:publish.py

示例9: test_corrupted

 def test_corrupted(self):
     p = session.query(Photo).filter_by(filename='bee.jpg').one()
     assert p
     self.assertFalse(p.is_corrupted())
     p = Photo(base_uri = os.path.join('file://', BASE_PATH, 'tests'),
               filename = 'bee-corrupted.jpg')
     self.assertTrue(p.is_corrupted())
开发者ID:leplatrem,项目名称:pyfspot,代码行数:7,代码来源:tests.py

示例10: create_photo

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
开发者ID:woome,项目名称:camera_upload,代码行数:8,代码来源:views.py

示例11: photo_save

def photo_save(request):
	if request.user.client_photo.count() >= 7:
		return HttpResponse('Max is 7')
	avatar = get_or_none(Photo, user=request.user, avatar=True)
	photo = Photo(user=request.user, photo=request.FILES['file'])
	if not avatar:
		photo.avatar = True
	photo.save()
	return HttpResponse('Uploaded')
开发者ID:MoonChel,项目名称:makeithappen,代码行数:9,代码来源:views.py

示例12: get

    def get(self):
        user = users.get_current_user()
        albumName = self.request.get('name')
        nickname = users.get_current_user().nickname()
        
        # Clear all photo data stored in the db
        query = "Where owner = '%s'" % (user)
        allPhoto = Photo.gql(query)
        db.delete(allPhoto)
        # Get selected album with owner
        query = "Where albumName = '%s' AND owner ='%s'" % (albumName, nickname)
        selectedAlbum = Album.gql(query)
        # Pre-select if album is empty
        if selectedAlbum[0].albumPhoto == '0':
            template_values = {
                'user': user,
                'albumName': albumName,
            }
            render_template(self, 'photo.html', template_values)

        gd_client = gdata.photos.service.PhotosService()
        photoList = gd_client.GetFeed('/data/feed/api/user/%s/albumid/%s?kind=photo' % (user, selectedAlbum[0].albumID))

        # initialize Lock and Queue objects
        lock = Lock()
        photoQueue = Queue()

        for photo in photoList.entry:
            photoQueue.put(photo)

        # start consumer
        for i in range(numConsumer):
            worker = Thread(target=consumer, args=(photoQueue, selectedAlbum[0].albumPhoto, nickname, lock))
            worker.start()

#        for thread in joinable:
#            thread.join()
        photoQueue.join()

        # All consumer thread are finished, empty photoQueue
#        with stdout_mutex:
        print "All done"

        lock.acquire()
        time.sleep(1)
        query = "Where owner = '%s'" % (nickname)
        allPhoto = Photo.gql(query)
        print allPhoto.count()

        template_values = {
                'user': user,
                'allPhoto': allPhoto,
                'albumName': albumName,
        }
        lock.release()

        render_template(self, 'photo.html', template_values)
开发者ID:JimmyCDChen,项目名称:photoAlbum,代码行数:57,代码来源:main.py

示例13: create_conversation

def create_conversation(user_id, conversation):

	conversation_type = conversation.get('conversation_type')
	conversationees_list = conversation.get('conversationees_list')
	conversationees_list = list(set(conversation.get('conversationees_list',[])))

	if conversation_type == conversations_config.get('CONVERSATION_DIRECT_TYPE') and len(conversationees_list) != 2:
		raise InvalidConversationException('Direct conversations should have 2 conversationees')

	ct = ConversationType.get(ConversationType.name == conversation_type)
	c = Conversation()
	c.conversation_type = ct

	p_url = conversation.get('picture','')
	picture = None
	if p_url:
		picture = Photo()
		picture.url = p_url

	name = conversation.get('name','')
	
	cps = []
	
	myself = None

	for index, conversationee in enumerate(conversationees_list):
		
		n = None
		p = None

		if conversation_type == 'group':
			n = name
			p = picture
		else:
			data = get_user_data(index, conversationees_list)
			n = data[0]
			p = data[1]

		cp = ConversationParty()
		cp.conversation = c
		cp.name = n 
		cp.user = User.get(User.id==conversationee)
		cp.picture = p
		cps.append(cp)

		if conversationee == user_id:
			myself = cp


	with database.transaction():
		c.save()
		if picture:
			picture.save()
		for cp in cps:
			cp.save()

	return __jsonify_one_conversation(myself)
开发者ID:FelipePiacsek,项目名称:chat_angular,代码行数:57,代码来源:conversations.py

示例14: setUp

	def setUp(self):
		'''
		Метод начальной инициализации
		'''
		photo = Photo(photo = 'this is a photo, believe me ;)')
		photo.save()
		user = User(login='test',password='test',avatarId = photo, rating = 0)
		user.save()
		user = User(login='TestUser',password='test_pass',avatarId = photo, rating = 0)
		user.save()
开发者ID:bekas,项目名称:MeToo,代码行数:10,代码来源:tests.py

示例15: savePhoto

 def savePhoto(self, galleryId, photoId, photoName, photoDescription, photoPosition, file):
     photo = None
     if(photoId):
         photo = Photo.objects.get(id=photoId)
     else:
         gid = uuid.uuid1().__str__()
         gid = gid.replace('-', '')
         photo = Photo()
         photo.id = gid
     photo.name = photoName
     photo.description = photoDescription
     photo.position = photoPosition
     photo.gallery_id = galleryId
     
     if(file):
         photoType = file.name.split('.')
         photo.type = photoType[1] if photoType.__len__() == 2 else ''
         
         destination  = open(constant.upload_path + galleryId + '/' +
                             photo.id + '.' + photo.type, 'wb')
         try:
             for chunk in file.chunks():
                 destination.write(chunk)
         finally:
             destination.close()
             
     photo.save()   
开发者ID:rsdgjb,项目名称:PortableApp,代码行数:27,代码来源:galleryService.py


注:本文中的models.Photo类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。