本文整理汇总了Python中models.Album类的典型用法代码示例。如果您正苦于以下问题:Python Album类的具体用法?Python Album怎么用?Python Album使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Album类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post
def post(self):
"""POST handler for gallery albums.
URL pattern: /albums
POST data must contain album metadata: 'name'.
Returns 201 CREATED with JSON data structure describing new album.
Returns Content-type: application/json.
Also returns Location header pointing to API URL for album details.
Include 'wrapjson' parameter in POST to wrap returned JSON in
a <textarea>. This also changes the returned Content-type to text/html.
If request is poorly formatted returns 400 BAD REQUEST.
Returns 401 UNAUTHORIZED to all calls if authorization fails.
"""
try:
data = dict(((str(k), v) for k, v in self.request.POST.items()))
album = Album(album_id=config.ALBUM_ID_GENERATOR(),
**data)
except:
data = {}
self.error(400)
else:
if not config.DEMO_MODE:
album.put()
data = album.to_dict()
self.response.headers['Location'] = data['url']
self.response.set_status(201)
write_json(self, data, wrapjson='wrapjson' in self.request.POST)
示例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')
示例3: test_parse_album
def test_parse_album(self):
response = '''{"response":[{"aid":"16178407","thumb_id":"96509883","owner_id":"6492","title":"qwerty",
"description":"desc","created":"1298365200","updated":"1298365201","size":"3",
"privacy":"3"},{"aid":"17071606","thumb_id":"98054577","owner_id":"-6492",
"title":"","description":"","created":"1204576880","updated":"1229532461",
"size":"3","privacy":"0"}]}
'''
instance = Album()
owner = UserFactory.create(remote_id=6492)
instance.parse(json.loads(response)['response'][0])
instance.save()
self.assertEqual(instance.remote_id, '6492_16178407')
self.assertEqual(instance.thumb_id, 96509883)
self.assertEqual(instance.owner, owner)
self.assertEqual(instance.title, 'qwerty')
self.assertEqual(instance.description, 'desc')
self.assertEqual(instance.created, datetime(2011,2,22,9,0,0))
self.assertEqual(instance.updated, datetime(2011,2,22,9,0,1))
self.assertEqual(instance.size, 3)
self.assertEqual(instance.privacy, 3)
instance = Album()
group = GroupFactory.create(remote_id=6492)
instance.parse(json.loads(response)['response'][1])
instance.save()
self.assertEqual(instance.remote_id, '-6492_17071606')
self.assertEqual(instance.group, group)
示例4: album
def album(request, album_id = None):
if album_id is not None:
album = request.db_session.query(Album).get(album_id)
else:
album = Album()
if request.method == 'POST':
if 'cancel' in request.POST:
return redirect('index')
form = AlbumForm(request.POST)
if form.is_valid():
# hydrate album object
album.title = form.cleaned_data['title']
album.artist = form.cleaned_data['artist']
# save it
request.db_session.add(album)
request.db_session.commit()
# show flash message to confirm update is OK
messages.success(request, "Album saved successfully")
# redirect to list of albums
return redirect('index')
elif album_id is not None:
form = AlbumForm(album.__dict__)
else:
form = AlbumForm()
return render(request, "album.html", {'form': form, 'album_id': album_id})
示例5: mock_album
def mock_album():
songs = [
Song(title="You Ain't Goin' Nowhere", track=1, album_id=1, s3_name="Los Angeles 2012-10-26-00.ogg", duration="5:20"),
Song(title="To Ramona", track=2, album_id=1, s3_name="Los Angeles 2012-10-26-02.ogg", duration="5:01"),
Song(title="Things Have Changed", track=3, album_id=1, s3_name="Los Angeles 2012-10-26-02.ogg", duration="5:20"),
Song(title="Tangled Up In Blue", track=4, album_id=1, s3_name="Los Angeles 2012-10-26-03.ogg", duration="6:26"),
Song(title="The Levee's Gonna Break", track=5, album_id=1, s3_name="Los Angeles 2012-10-26-04.ogg", duration="7:14"),
Song(title="Make You Feel My Love", track=6, album_id=1, s3_name="Los Angeles 2012-10-26-05.ogg", duration="5:00"),
Song(title="Cry A While", track=7, album_id=1, s3_name="Los Angeles 2012-10-26-06.ogg", duration="5:42"),
Song(title="Desolation Row", track=8, album_id=1, s3_name="Los Angeles 2012-10-26-07.ogg", duration="9:08"),
Song(title="Highway 61 Revisitied", track=9, album_id=1, s3_name="Los Angeles 2012-10-26-08.ogg", duration="7:00"),
Song(title="Love Sick", track=10, album_id=1, s3_name="Los Angeles 2012-10-26-09.ogg", duration="5:32"),
Song(title="Thunder on the Mountain", track=11, album_id=1, s3_name="Los Angeles 2012-10-26-10.ogg", duration="7:51"),
Song(title="Ballad of A Thin Man", track=12, album_id=1, s3_name="Los Angeles 2012-10-26-11.ogg", duration="6:17"),
Song(title="Like A Rolling Stone", track=13, album_id=1, s3_name="Los Angeles 2012-10-26-12.ogg", duration="6:32"),
Song(title="All Along the Watchtower", track=14, album_id=1, s3_name="Los Angeles 2012-10-26-13.ogg", duration="6:18"),
Song(title="Blowin' In the Wind", track=15, album_id=1, s3_name="Los Angeles 2012-10-26-14.ogg", duration="9:02"),
]
album = Album(
title="Hollywood Bowl 2012",
date=datetime.date(year=2012, day=26, month=10),
venue="Hollywood Bowl",
city="Los Angeles",
bucket="priestc-dylan",
folder="hollywood_bowl_2012",
encoding="ogg q5",
source="Core Sound micros DPA 4060 with Sony PCM - M10>Hard Drive>Flac"
)
album.songs = songs
return album
示例6: add_to_db
def add_to_db(audio_files):
for audio_file in audio_files:
audio_file_id3 = eyed3.load(audio_file)
# If the artist, album or track doesn't exist in the database, create
# table(s) for them.
try:
if not Artist.objects.filter(name=audio_file_id3.tag.artist).exists():
artist = Artist(name=audio_file_id3.tag.artist)
artist.save()
if not Album.objects.filter(title=audio_file_id3.tag.album).exists():
album = Album(title=audio_file_id3.tag.album, \
artist=artist)
album.save()
if not Track.objects.filter(title=audio_file_id3.tag.title).exists():
track = Track(title=audio_file_id3.tag.title, \
album=album, \
artist=artist, \
fspath=audio_file, \
media_url=MEDIA_URL + audio_file.split(MEDIA_ROOT)[1])
track.save()
print 'Added to DB: ' + audio_file_id3.tag.title
except Exception as e:
print 'Error: ' + e
示例7: create
def create(request, albumTitle):
is_auth = request.user.is_authenticated()
if (is_auth):
album = Album(title=request.albumTitle, description=none, userId=request.user)
album.save()
return render_to_response('create.html', {'is_auth':is_auth, 'user':request.user, 'title':albumTitle})
else:
return render_to_response('login.html',{'is_auth':is_auth})
示例8: album
def album(request, album_id, lang="en", name=""):
if album_id == "0":
query = request.GET.get("query", " ")
album = Album(query=query)
album.id = 0
else:
album = get_object_or_404(Album, id=album_id)
try:
page = int(request.GET.get("page", "1"))
except ValueError:
page = 1
if request.GET.get("redirect", "") != "":
if album_id == "0" and page == 1:
goto = reverse("wilson:custom_album", kwargs={"lang": translation.get_language(), "query": query})
elif album_id == "0" and page > 1:
goto = reverse(
"wilson:custom_album", kwargs={"lang": translation.get_language(), "page": page, "query": query}
)
elif page == 1:
goto = reverse(
"wilson:album",
kwargs={"lang": translation.get_language(), "album_id": album_id, "name": slugify(album.title())},
)
else:
goto = reverse(
"wilson:album_page",
kwargs={
"lang": translation.get_language(),
"album_id": album_id,
"name": slugify(album.title()),
"page": page,
},
)
return HttpResponseRedirect(goto)
paginator = Paginator(album.pictures_id_list(), 35, 7)
# If page request (9999) is out of range, deliver last page of results.
try:
album_pics = paginator.page(page)
except (EmptyPage, InvalidPage):
album_pics = paginator.page(paginator.num_pages)
album_pics.page_range = paginator.page_range
return render_to_response(
"wilson/album.html",
{
"album": album,
"album_pics": album_pics,
"menu": {
"left": list(MenuPlaceholder.objects.filter(parent=None, position_h="l").order_by("position_v")),
"right": list(MenuPlaceholder.objects.filter(parent=None, position_h="r").order_by("position_v")),
},
},
context_instance=RequestContext(request),
)
示例9: next
def next(self, request, **kwargs):
if request.GET['album'] and request.GET['track_num']:
song = Song.get_song(int(request.GET['album']), int(request.GET['track_num']))
if request.GET['album'] and not song:
song = Album.get_similar_album(request.GET['album']).song_set[0]
if not song:
song = Album.get(0).song_set[0]
bundle = self.build_bundle(obj=song, request=request)
bundle = self.full_dehydrate(bundle)
return self.create_response(request, { 'song': bundle })
示例10: sync_to
def sync_to(self, sync_cls):
objs = []
# traverse the dir
for dirpath, folders, files in os.walk(self.folder):
for fname in files:
fpath = os.path.join(dirpath, fname)
# get album, if have
rel = os.path.relpath(dirpath, self.folder)
if rel != '.': # has sub dir
try:
album = Album.get(name=rel)
except Album.DoesNotExist:
album = Album.create(name=rel, folder=rel)
else:
album = None
# TODO: should a file extension filter here?
md5 = hashlib.md5(open(fpath).read()).hexdigest()
try: # if file has been exists before
local = Local.get(md5=md5)
opath = local.path.encode('utf8')
if opath != fpath:
logging.debug('%s path change: %s --> %s' % (local, local.path, fpath))
# file was moved, rename filename or folder
local.title, ext = os.path.splitext(fname)
local.album = album
#local.fpath = fpath
local.last_modified = datetime.datetime.now()
local.save()
objs.append(local) # objs: path modified.
except Local.DoesNotExist: # new file
try:
# file content modified
local = Local.get(path=fpath)
logging.debug('%s modified, path: %s' % (local, fpath))
except Local.DoesNotExist:
# brand new file
logging.debug('new file %s' % fpath)
local = Local()
local.title, ext = os.path.splitext(fname)
local.album = album
local.path = fpath
local.md5 = md5
local.last_modified = datetime.datetime.now()
local.save()
objs.append(local)
# for those have not been upload
for l in Local.select():
sets = getattr(l, sync_cls.model.local.related_name)
if sets.count() == 0 and l not in objs:
objs.append(l)
# pass objs that needs update to sync class
logging.info('local: sync to %s, count %d' % (sync_cls, len(objs)))
sync_cls.sync_from_local(objs)
示例11: create_album_view
def create_album_view(request):
owner = request.user
if request.method == 'POST':
form = CreateAlbumForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
album = Album(name=name, owner=owner)
album.save()
return HttpResponseRedirect('/main')
else:
form = CreateAlbumForm()
return render(request, 'photorizer/create_album.html', {'form': form})
示例12: get
def get(self):
user = users.get_current_user()
if user is not None:
nickname = users.get_current_user().nickname()
logInOut = users.create_logout_url(self.request.uri)
greeting = "Please Enter Your Picasa Album Address:"
gd_client = gdata.photos.service.PhotosService()
# try delete the user's album in the DB
# pass if can't find.
try:
query = "Where owner = '%s'" % (nickname)
allAlbum = Album.gql(query)
db.delete(allAlbum)
except:
print "no album deleted for %s" % (nickname)
pass
# Grab user album list from Google Picasa and store in DB
try:
albumList = gd_client.GetUserFeed(user=user)
for album in albumList.entry:
newAlbum = Album()
newAlbum.owner = nickname
newAlbum.albumName = album.title.text
newAlbum.albumID = album.gphoto_id.text
newAlbum.albumPhoto = album.numphotos.text
newAlbum.put()
except:
print "%s album not added into DB" % (nickname)
pass
# Grab all available albums for the user
nickname = users.get_current_user().nickname()
query = "Where owner = '%s'" % (nickname)
time.sleep(1)
allAlbum = Album.gql(query)
print query
print allAlbum.count()
template_values = {
'user': user,
'logInOut': logInOut,
'greeting': greeting,
'albumInfo': allAlbum,
}
return render_template(self, 'index.html', template_values)
else:
logInOut = users.create_login_url(self.request.uri)
greeting = "Please Login to continue."
template_values = {
'user': user,
'logInOut': logInOut,
'greeting': greeting,
}
return render_template(self, 'index.html', template_values)
return render_template(self, 'index.html', template_values)
示例13: createAlbum
def createAlbum():
form = CreateAlbumForm(prefix="createAlbum")
if form.validate_on_submit():
album = Album(name=form.name.data,
description=form.description.data,
creationDate=datetime.utcnow(),
numImages=0,
coverImageId=0)
if form.passwordProtected.data and form.passwordHash.data:
album.passwordHash = getAlbumPasswordHash(album.creationDate, form.passwordHash.data)
db.session.add(album)
db.session.commit()
return admin(createAlbumForm=form)
示例14: post
def post(self):
if not self.has_permission:
return
user = self.current_user
name = self.get_argument('name', None)
name = strip_tags(name)
if not name:
return self.send_error_result(msg=u'没有填写专辑名')
if len(name) >= 10:
return self.send_error_result(msg=u'专辑名不能超过 10 个字符')
album = Album(name=name, user_id=user.id).save()
return self.send_success_result(data=album.to_dict())
示例15: test_create_album
def test_create_album(self):
"""Create an album and verify that it appears as expected."""
album = Album(
title='An Album',
description='A Description',
author=self.u
)
album.full_clean()
album.save()
self.assertIsInstance(album, Album)
self.assertIsInstance(album.date_created, datetime)
self.assertIsInstance(album.date_modified, datetime)
self.assertEqual(album.title, 'An Album')
self.assertEqual(album.description, 'A Description')
self.assertEqual(album.author, self.u)