本文整理汇总了Python中xmodule.contentstore.content.StaticContent.get_location_from_path方法的典型用法代码示例。如果您正苦于以下问题:Python StaticContent.get_location_from_path方法的具体用法?Python StaticContent.get_location_from_path怎么用?Python StaticContent.get_location_from_path使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xmodule.contentstore.content.StaticContent
的用法示例。
在下文中一共展示了StaticContent.get_location_from_path方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_get_location_from_path
# 需要导入模块: from xmodule.contentstore.content import StaticContent [as 别名]
# 或者: from xmodule.contentstore.content.StaticContent import get_location_from_path [as 别名]
def test_get_location_from_path(self):
asset_location = StaticContent.get_location_from_path(u'/c4x/a/b/asset/images_course_image.jpg')
self.assertEqual(
AssetLocator(CourseLocator(u'a', u'b', None, deprecated=True),
u'asset', u'images_course_image.jpg', deprecated=True),
asset_location
)
示例2: get_asset_location
# 需要导入模块: from xmodule.contentstore.content import StaticContent [as 别名]
# 或者: from xmodule.contentstore.content.StaticContent import get_location_from_path [as 别名]
def get_asset_location(asset_id):
""" Helper method to get the location (and verify it is valid). """
try:
return StaticContent.get_location_from_path(asset_id)
except InvalidLocationError as err:
# return a 'Bad Request' to browser as we have a malformed Location
return JsonResponse({"error": err.message}, status=400)
示例3: test_delete_image_type_asset
# 需要导入模块: from xmodule.contentstore.content import StaticContent [as 别名]
# 或者: from xmodule.contentstore.content.StaticContent import get_location_from_path [as 别名]
def test_delete_image_type_asset(self):
""" Tests deletion of image type asset """
image_asset = self.get_sample_asset(self.asset_name, asset_type="image")
thumbnail_image_asset = self.get_sample_asset('delete_test_thumbnail', asset_type="image")
# upload image
response = self.client.post(self.url, {"name": "delete_image_test", "file": image_asset})
self.assertEquals(response.status_code, 200)
uploaded_image_url = json.loads(response.content)['asset']['url']
# upload image thumbnail
response = self.client.post(self.url, {"name": "delete_image_thumb_test", "file": thumbnail_image_asset})
self.assertEquals(response.status_code, 200)
thumbnail_url = json.loads(response.content)['asset']['url']
thumbnail_location = StaticContent.get_location_from_path(thumbnail_url)
image_asset_location = AssetLocation.from_deprecated_string(uploaded_image_url)
content = contentstore().find(image_asset_location)
content.thumbnail_location = thumbnail_location
contentstore().save(content)
with mock.patch('opaque_keys.edx.locator.CourseLocator.make_asset_key') as mock_asset_key:
mock_asset_key.return_value = thumbnail_location
test_url = reverse_course_url(
'assets_handler', self.course.id, kwargs={'asset_key_string': unicode(uploaded_image_url)})
resp = self.client.delete(test_url, HTTP_ACCEPT="application/json")
self.assertEquals(resp.status_code, 204)
示例4: test_happy_path
# 需要导入模块: from xmodule.contentstore.content import StaticContent [as 别名]
# 或者: from xmodule.contentstore.content.StaticContent import get_location_from_path [as 别名]
def test_happy_path(self, modulestore_type, create_after_overview):
"""
What happens when everything works like we expect it to.
If `create_after_overview` is True, we will temporarily disable
thumbnail creation so that the initial CourseOverview is created without
an image_set, and the CourseOverviewImageSet is created afterwards. If
`create_after_overview` is False, we'll create the CourseOverviewImageSet
at the same time as the CourseOverview.
"""
# Create a real (oversized) image...
image = Image.new("RGB", (800, 400), "blue")
image_buff = StringIO()
image.save(image_buff, format="JPEG")
image_buff.seek(0)
image_name = "big_course_image.jpeg"
with self.store.default_store(modulestore_type):
course = CourseFactory.create(
default_store=modulestore_type, course_image=image_name
)
# Save a real image here...
course_image_asset_key = StaticContent.compute_location(course.id, course.course_image)
course_image_content = StaticContent(course_image_asset_key, image_name, 'image/jpeg', image_buff)
contentstore().save(course_image_content)
# If create_after_overview is True, disable thumbnail generation so
# that the CourseOverview object is created and saved without an
# image_set at first (it will be lazily created later).
if create_after_overview:
self.set_config(enabled=False)
# Now generate the CourseOverview...
course_overview = CourseOverview.get_from_id(course.id)
# If create_after_overview is True, no image_set exists yet. Verify
# that, then switch config back over to True and it should lazily
# create the image_set on the next get_from_id() call.
if create_after_overview:
self.assertFalse(hasattr(course_overview, 'image_set'))
self.set_config(enabled=True)
course_overview = CourseOverview.get_from_id(course.id)
self.assertTrue(hasattr(course_overview, 'image_set'))
image_urls = course_overview.image_urls
config = CourseOverviewImageConfig.current()
# Make sure the thumbnail names come out as expected...
self.assertTrue(image_urls['raw'].endswith('big_course_image.jpeg'))
self.assertTrue(image_urls['small'].endswith('big_course_image-jpeg-{}x{}.jpg'.format(*config.small)))
self.assertTrue(image_urls['large'].endswith('big_course_image-jpeg-{}x{}.jpg'.format(*config.large)))
# Now make sure our thumbnails are of the sizes we expect...
for image_url, expected_size in [(image_urls['small'], config.small), (image_urls['large'], config.large)]:
image_key = StaticContent.get_location_from_path(image_url)
image_content = AssetManager.find(image_key)
image = Image.open(StringIO(image_content.data))
self.assertEqual(image.size, expected_size)
示例5: test_different_resolutions
# 需要导入模块: from xmodule.contentstore.content import StaticContent [as 别名]
# 或者: from xmodule.contentstore.content.StaticContent import get_location_from_path [as 别名]
def test_different_resolutions(self, src_dimensions):
"""
Test various resolutions of images to make thumbnails of.
Note that our test sizes are small=(200, 100) and large=(400, 200).
1. Images should won't be blown up if it's too small, so a (100, 50)
resolution image will remain (100, 50).
2. However, images *will* be converted using our format and quality
settings (JPEG, 75% -- the PIL default). This is because images with
relatively small dimensions not compressed properly.
3. Image thumbnail naming will maintain the naming convention of the
target resolution, even if the image was not actually scaled to that
size (i.e. it was already smaller). This is mostly because it's
simpler to be consistent, but it also lets us more easily tell which
configuration a thumbnail was created under.
"""
# Create a source image...
image = Image.new("RGB", src_dimensions, "blue")
image_buff = StringIO()
image.save(image_buff, format="PNG")
image_buff.seek(0)
image_name = "src_course_image.png"
course = CourseFactory.create(course_image=image_name)
# Save the image to the contentstore...
course_image_asset_key = StaticContent.compute_location(course.id, course.course_image)
course_image_content = StaticContent(course_image_asset_key, image_name, 'image/png', image_buff)
contentstore().save(course_image_content)
# Now generate the CourseOverview...
config = CourseOverviewImageConfig.current()
course_overview = CourseOverview.get_from_id(course.id)
image_urls = course_overview.image_urls
for image_url, target in [(image_urls['small'], config.small), (image_urls['large'], config.large)]:
image_key = StaticContent.get_location_from_path(image_url)
image_content = AssetManager.find(image_key)
image = Image.open(StringIO(image_content.data))
# Naming convention for thumbnail
self.assertTrue(image_url.endswith('src_course_image-png-{}x{}.jpg'.format(*target)))
# Actual thumbnail data
src_x, src_y = src_dimensions
target_x, target_y = target
image_x, image_y = image.size
# I'm basically going to assume the image library knows how to do
# the right thing in terms of handling aspect ratio. We're just
# going to make sure that small images aren't blown up, and that
# we never exceed our target sizes
self.assertLessEqual(image_x, target_x)
self.assertLessEqual(image_y, target_y)
if src_x < target_x and src_y < target_y:
self.assertEqual(src_x, image_x)
self.assertEqual(src_y, image_y)
示例6: test_delete_asset_with_invalid_thumbnail
# 需要导入模块: from xmodule.contentstore.content import StaticContent [as 别名]
# 或者: from xmodule.contentstore.content.StaticContent import get_location_from_path [as 别名]
def test_delete_asset_with_invalid_thumbnail(self):
""" Tests the sad path :( """
test_url = reverse_course_url(
'assets_handler', self.course.id, kwargs={'asset_key_string': unicode(self.uploaded_url)})
self.content.thumbnail_location = StaticContent.get_location_from_path('/c4x/edX/toy/asset/invalid')
contentstore().save(self.content)
resp = self.client.delete(test_url, HTTP_ACCEPT="application/json")
self.assertEquals(resp.status_code, 204)
示例7: memory_image_file
# 需要导入模块: from xmodule.contentstore.content import StaticContent [as 别名]
# 或者: from xmodule.contentstore.content.StaticContent import get_location_from_path [as 别名]
def memory_image_file(self):
try:
asset_location = StaticContent.get_location_from_path(self.image_url)
content = contentstore().find(asset_location, as_stream=True)
except (NotFoundError, InvalidKeyError):
return None
image_file = StringIO.StringIO(content.copy_to_in_mem().data)
return image_file
示例8: process_request
# 需要导入模块: from xmodule.contentstore.content import StaticContent [as 别名]
# 或者: from xmodule.contentstore.content.StaticContent import get_location_from_path [as 别名]
def process_request(self, request):
# look to see if the request is prefixed with 'c4x' tag
if request.path.startswith("/" + XASSET_LOCATION_TAG + "/"):
try:
loc = StaticContent.get_location_from_path(request.path)
except InvalidLocationError:
# return a 'Bad Request' to browser as we have a malformed Location
response = HttpResponse()
response.status_code = 400
return response
# first look in our cache so we don't have to round-trip to the DB
content = get_cached_content(loc)
if content is None:
# nope, not in cache, let's fetch from DB
try:
content = contentstore().find(loc, as_stream=True)
except NotFoundError:
response = HttpResponse()
response.status_code = 404
return response
# since we fetched it from DB, let's cache it going forward, but only if it's < 1MB
# this is because I haven't been able to find a means to stream data out of memcached
if content.length is not None:
if content.length < 1048576:
# since we've queried as a stream, let's read in the stream into memory to set in cache
content = content.copy_to_in_mem()
set_cached_content(content)
else:
# NOP here, but we may wish to add a "cache-hit" counter in the future
pass
# Check that user has access to content
if getattr(content, "locked", False):
if not hasattr(request, "user") or not request.user.is_authenticated():
return HttpResponseForbidden("Unauthorized")
course_partial_id = "/".join([loc.org, loc.course])
if not request.user.is_staff and not CourseEnrollment.is_enrolled_by_partial(
request.user, course_partial_id
):
return HttpResponseForbidden("Unauthorized")
# convert over the DB persistent last modified timestamp to a HTTP compatible
# timestamp, so we can simply compare the strings
last_modified_at_str = content.last_modified_at.strftime("%a, %d-%b-%Y %H:%M:%S GMT")
# see if the client has cached this content, if so then compare the
# timestamps, if they are the same then just return a 304 (Not Modified)
if "HTTP_IF_MODIFIED_SINCE" in request.META:
if_modified_since = request.META["HTTP_IF_MODIFIED_SINCE"]
if if_modified_since == last_modified_at_str:
return HttpResponseNotModified()
response = HttpResponse(content.stream_data(), content_type=content.content_type)
response["Last-Modified"] = last_modified_at_str
return response
示例9: process_request
# 需要导入模块: from xmodule.contentstore.content import StaticContent [as 别名]
# 或者: from xmodule.contentstore.content.StaticContent import get_location_from_path [as 别名]
def process_request(self, request):
if request.path.startswith('/' + XASSET_LOCATION_TAG + '/'):
if request.GET.get('width') or request.GET.get('height'):
# generate the requested thumbnail location
width = int(request.GET['width'])
path = request.path.split('/')
category = 'thumbnail'
name = os.path.splitext(path[5])
path[5] = "%s-w%d%s" % (name[0], width, name[1])
path[4] = category
path = '/'.join(path)
thumbnail_location = StaticContent.get_location_from_path(path) # calculate thumbnail 'location' in gridfs
try: # is it already created ?
thumbnail_content = contentstore().find(thumbnail_location, as_stream=True)
except NotFoundError:
# get original asset
asset_location = StaticContent.get_location_from_path(request.path)
try:
content = contentstore().find(asset_location, as_stream=True)
except NotFoundError:
return # if original asset do not exists, let the request pass by
# generate thumbnail
im = Image.open(StringIO.StringIO(content.copy_to_in_mem().data))
im = im.convert('RGB')
size = (width, width) # PIL is dumb, we shall use a better tool to generate smartly framed thumbnails
im.thumbnail(size, Image.ANTIALIAS)
thumbnail_file = StringIO.StringIO()
im.save(thumbnail_file, 'JPEG')
thumbnail_file.seek(0)
# store thumbnail in contentstore
thumbnail_name = StaticContent.generate_thumbnail_name(thumbnail_location.name)
thumbnail_content = StaticContentStream(thumbnail_location, thumbnail_name,
'image/jpeg', thumbnail_file)
contentstore().save(thumbnail_content.copy_to_in_mem())
# return found or generated tumbnail
response = HttpResponse(thumbnail_content.copy_to_in_mem().stream_data(), content_type=thumbnail_content.content_type)
return response
return super(ThumbnailStaticContentServer, self).process_request(request)
示例10: get_old_style_versioned_asset_url
# 需要导入模块: from xmodule.contentstore.content import StaticContent [as 别名]
# 或者: from xmodule.contentstore.content.StaticContent import get_location_from_path [as 别名]
def get_old_style_versioned_asset_url(asset_path):
"""
Creates an old-style versioned asset URL.
"""
try:
locator = StaticContent.get_location_from_path(asset_path)
content = AssetManager.find(locator, as_stream=True)
return u'{}/{}{}'.format(VERSIONED_ASSETS_PREFIX, content.content_digest, asset_path)
except (InvalidKeyError, ItemNotFoundError):
pass
return asset_path
示例11: get_versioned_asset_url
# 需要导入模块: from xmodule.contentstore.content import StaticContent [as 别名]
# 或者: from xmodule.contentstore.content.StaticContent import get_location_from_path [as 别名]
def get_versioned_asset_url(asset_path):
"""
Creates a versioned asset URL.
"""
try:
locator = StaticContent.get_location_from_path(asset_path)
content = AssetManager.find(locator, as_stream=True)
return StaticContent.add_version_to_asset_path(asset_path, content.content_digest)
except (InvalidKeyError, ItemNotFoundError):
pass
return asset_path
示例12: process_request
# 需要导入模块: from xmodule.contentstore.content import StaticContent [as 别名]
# 或者: from xmodule.contentstore.content.StaticContent import get_location_from_path [as 别名]
def process_request(self, request):
# look to see if the request is prefixed with 'c4x' tag
if request.path.startswith('/' + XASSET_LOCATION_TAG + '/'):
try:
loc = StaticContent.get_location_from_path(request.path)
except InvalidLocationError:
# return a 'Bad Request' to browser as we have a malformed
# Location
response = HttpResponse()
response.status_code = 400
return response
# first look in our cache so we don't have to round-trip to the DB
content = get_cached_content(loc)
if content is None:
# nope, not in cache, let's fetch from DB
try:
content = contentstore().find(loc)
except NotFoundError:
response = HttpResponse()
response.status_code = 404
return response
# since we fetched it from DB, let's cache it going forward
set_cached_content(content)
else:
# @todo: we probably want to have 'cache hit' counters so we can
# measure the efficacy of our caches
pass
# see if the last-modified at hasn't changed, if not return a 302
# (Not Modified)
# convert over the DB persistent last modified timestamp to a HTTP compatible
# timestamp, so we can simply compare the strings
last_modified_at_str = content.last_modified_at.strftime(
"%a, %d-%b-%Y %H:%M:%S GMT")
# see if the client has cached this content, if so then compare the
# timestamps, if they are the same then just return a 304 (Not
# Modified)
if 'HTTP_IF_MODIFIED_SINCE' in request.META:
if_modified_since = request.META['HTTP_IF_MODIFIED_SINCE']
if if_modified_since == last_modified_at_str:
return HttpResponseNotModified()
response = HttpResponse(
content.data, content_type=content.content_type)
response['Last-Modified'] = last_modified_at_str
return response
示例13: process_request
# 需要导入模块: from xmodule.contentstore.content import StaticContent [as 别名]
# 或者: from xmodule.contentstore.content.StaticContent import get_location_from_path [as 别名]
def process_request(self, request):
# look to see if the request is prefixed with 'c4x' tag
if request.path.startswith('/' + XASSET_LOCATION_TAG + '/'):
try:
loc = StaticContent.get_location_from_path(request.path)
except InvalidLocationError:
# return a 'Bad Request' to browser as we have a malformed Location
response = HttpResponse()
response.status_code = 400
return response
# first look in our cache so we don't have to round-trip to the DB
content = get_cached_content(loc)
if content is None:
# nope, not in cache, let's fetch from DB
try:
content = contentstore().find(loc, as_stream=True)
except NotFoundError:
response = HttpResponse()
response.status_code = 404
return response
# since we fetched it from DB, let's cache it going forward, but only if it's < 1MB
# this is because I haven't been able to find a means to stream data out of memcached
if content.length is not None:
if content.length < 1048576:
# since we've queried as a stream, let's read in the stream into memory to set in cache
content = content.copy_to_in_mem()
set_cached_content(content)
else:
# NOP here, but we may wish to add a "cache-hit" counter in the future
pass
# see if the last-modified at hasn't changed, if not return a 302 (Not Modified)
# convert over the DB persistent last modified timestamp to a HTTP compatible
# timestamp, so we can simply compare the strings
last_modified_at_str = content.last_modified_at.strftime("%a, %d-%b-%Y %H:%M:%S GMT")
# see if the client has cached this content, if so then compare the
# timestamps, if they are the same then just return a 304 (Not Modified)
if 'HTTP_IF_MODIFIED_SINCE' in request.META:
if_modified_since = request.META['HTTP_IF_MODIFIED_SINCE']
if if_modified_since == last_modified_at_str:
return HttpResponseNotModified()
response = HttpResponse(content.stream_data(), content_type=content.content_type)
response['Last-Modified'] = last_modified_at_str
return response
示例14: remove_asset
# 需要导入模块: from xmodule.contentstore.content import StaticContent [as 别名]
# 或者: from xmodule.contentstore.content.StaticContent import get_location_from_path [as 别名]
def remove_asset(request, org, course, name):
'''
This method will perform a 'soft-delete' of an asset, which is basically to
copy the asset from the main GridFS collection and into a Trashcan
'''
get_location_and_verify_access(request, org, course, name)
location = request.POST['location']
# make sure the location is valid
try:
loc = StaticContent.get_location_from_path(location)
except InvalidLocationError:
# return a 'Bad Request' to browser as we have a malformed Location
response = HttpResponse()
response.status_code = 400
return response
# also make sure the item to delete actually exists
try:
content = contentstore().find(loc)
except NotFoundError:
response = HttpResponse()
response.status_code = 404
return response
# ok, save the content into the trashcan
contentstore('trashcan').save(content)
# see if there is a thumbnail as well, if so move that as well
if content.thumbnail_location is not None:
try:
thumbnail_content = contentstore().find(content.thumbnail_location)
contentstore('trashcan').save(thumbnail_content)
# hard delete thumbnail from origin
contentstore().delete(thumbnail_content.get_id())
# remove from any caching
del_cached_content(thumbnail_content.location)
except:
pass # OK if this is left dangling
# delete the original
contentstore().delete(content.get_id())
# remove from cache
del_cached_content(content.location)
return HttpResponse()
示例15: restore_asset_from_trashcan
# 需要导入模块: from xmodule.contentstore.content import StaticContent [as 别名]
# 或者: from xmodule.contentstore.content.StaticContent import get_location_from_path [as 别名]
def restore_asset_from_trashcan(location):
'''
This method will restore an asset which got soft deleted and put back in the original course
'''
trash = contentstore('trashcan')
store = contentstore()
loc = StaticContent.get_location_from_path(location)
content = trash.find(loc)
# ok, save the content into the courseware
store.save(content)
# see if there is a thumbnail as well, if so move that as well
if content.thumbnail_location is not None:
try:
thumbnail_content = trash.find(content.thumbnail_location)
store.save(thumbnail_content)
except:
pass # OK if this is left dangling