Best Python code snippet using avocado_python
upload_utils.py
Source:upload_utils.py
...47 # are both allowed.48 registry.update_image_metadata(req.context, image_id,49 {'status': 'killed'},50 from_state=from_state)51def safe_kill(req, image_id, from_state):52 """53 Mark image killed without raising exceptions if it fails.54 Since _kill is meant to be called from exceptions handlers, it should55 not raise itself, rather it should just log its error.56 :param req: The WSGI/Webob Request object57 :param image_id: Opaque image identifier58 :param from_state: Permitted current status for transition to 'killed'59 """60 try:61 _kill(req, image_id, from_state)62 except Exception:63 LOG.exception(_LE("Unable to kill image %(id)s: ") % {'id': image_id})64def upload_data_to_store(req, image_meta, image_data, store, notifier):65 """66 Upload image data to specified store.67 Upload image data to the store and cleans up on error.68 """69 image_id = image_meta['id']70 db_api = glance.db.get_api(v1_mode=True)71 image_size = image_meta.get('size')72 try:73 # By default image_data will be passed as CooperativeReader object.74 # But if 'user_storage_quota' is enabled and 'remaining' is not None75 # then it will be passed as object of LimitingReader to76 # 'store_add_to_backend' method.77 image_data = utils.CooperativeReader(image_data)78 remaining = glance.api.common.check_quota(79 req.context, image_size, db_api, image_id=image_id)80 if remaining is not None:81 image_data = utils.LimitingReader(image_data, remaining)82 (uri,83 size,84 checksum,85 location_metadata) = store_api.store_add_to_backend(86 image_meta['id'],87 image_data,88 image_meta['size'],89 store,90 context=req.context)91 location_data = {'url': uri,92 'metadata': location_metadata,93 'status': 'active'}94 try:95 # recheck the quota in case there were simultaneous uploads that96 # did not provide the size97 glance.api.common.check_quota(98 req.context, size, db_api, image_id=image_id)99 except exception.StorageQuotaFull:100 with excutils.save_and_reraise_exception():101 LOG.info(_LI('Cleaning up %s after exceeding '102 'the quota'), image_id)103 store_utils.safe_delete_from_backend(104 req.context, image_meta['id'], location_data)105 def _kill_mismatched(image_meta, attr, actual):106 supplied = image_meta.get(attr)107 if supplied and supplied != actual:108 msg = (_("Supplied %(attr)s (%(supplied)s) and "109 "%(attr)s generated from uploaded image "110 "(%(actual)s) did not match. Setting image "111 "status to 'killed'.") % {'attr': attr,112 'supplied': supplied,113 'actual': actual})114 LOG.error(msg)115 safe_kill(req, image_id, 'saving')116 initiate_deletion(req, location_data, image_id)117 raise webob.exc.HTTPBadRequest(explanation=msg,118 content_type="text/plain",119 request=req)120 # Verify any supplied size/checksum value matches size/checksum121 # returned from store when adding image122 _kill_mismatched(image_meta, 'size', size)123 _kill_mismatched(image_meta, 'checksum', checksum)124 # Update the database with the checksum returned125 # from the backend store126 LOG.debug("Updating image %(image_id)s data. "127 "Checksum set to %(checksum)s, size set "128 "to %(size)d", {'image_id': image_id,129 'checksum': checksum,130 'size': size})131 update_data = {'checksum': checksum,132 'size': size}133 try:134 try:135 state = 'saving'136 image_meta = registry.update_image_metadata(req.context,137 image_id,138 update_data,139 from_state=state)140 except exception.Duplicate:141 image = registry.get_image_metadata(req.context, image_id)142 if image['status'] == 'deleted':143 raise exception.ImageNotFound()144 else:145 raise146 except exception.NotAuthenticated as e:147 # Delete image data due to possible token expiration.148 LOG.debug("Authentication error - the token may have "149 "expired during file upload. Deleting image data for "150 " %s " % image_id)151 initiate_deletion(req, location_data, image_id)152 raise webob.exc.HTTPUnauthorized(explanation=e.msg, request=req)153 except exception.ImageNotFound:154 msg = _("Image %s could not be found after upload. The image may"155 " have been deleted during the upload.") % image_id156 LOG.info(msg)157 # NOTE(jculp): we need to clean up the datastore if an image158 # resource is deleted while the image data is being uploaded159 #160 # We get "location_data" from above call to store.add(), any161 # exceptions that occur there handle this same issue internally,162 # Since this is store-agnostic, should apply to all stores.163 initiate_deletion(req, location_data, image_id)164 raise webob.exc.HTTPPreconditionFailed(explanation=msg,165 request=req,166 content_type='text/plain')167 except store_api.StoreAddDisabled:168 msg = _("Error in store configuration. Adding images to store "169 "is disabled.")170 LOG.exception(msg)171 safe_kill(req, image_id, 'saving')172 notifier.error('image.upload', msg)173 raise webob.exc.HTTPGone(explanation=msg, request=req,174 content_type='text/plain')175 except (store_api.Duplicate, exception.Duplicate) as e:176 msg = (_("Attempt to upload duplicate image: %s") %177 encodeutils.exception_to_unicode(e))178 LOG.warn(msg)179 # NOTE(dosaboy): do not delete the image since it is likely that this180 # conflict is a result of another concurrent upload that will be181 # successful.182 notifier.error('image.upload', msg)183 raise webob.exc.HTTPConflict(explanation=msg,184 request=req,185 content_type="text/plain")186 except exception.Forbidden as e:187 msg = (_("Forbidden upload attempt: %s") %188 encodeutils.exception_to_unicode(e))189 LOG.warn(msg)190 safe_kill(req, image_id, 'saving')191 notifier.error('image.upload', msg)192 raise webob.exc.HTTPForbidden(explanation=msg,193 request=req,194 content_type="text/plain")195 except store_api.StorageFull as e:196 msg = (_("Image storage media is full: %s") %197 encodeutils.exception_to_unicode(e))198 LOG.error(msg)199 safe_kill(req, image_id, 'saving')200 notifier.error('image.upload', msg)201 raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg,202 request=req,203 content_type='text/plain')204 except store_api.StorageWriteDenied as e:205 msg = (_("Insufficient permissions on image storage media: %s") %206 encodeutils.exception_to_unicode(e))207 LOG.error(msg)208 safe_kill(req, image_id, 'saving')209 notifier.error('image.upload', msg)210 raise webob.exc.HTTPServiceUnavailable(explanation=msg,211 request=req,212 content_type='text/plain')213 except exception.ImageSizeLimitExceeded as e:214 msg = (_("Denying attempt to upload image larger than %d bytes.")215 % CONF.image_size_cap)216 LOG.warn(msg)217 safe_kill(req, image_id, 'saving')218 notifier.error('image.upload', msg)219 raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg,220 request=req,221 content_type='text/plain')222 except exception.StorageQuotaFull as e:223 msg = (_("Denying attempt to upload image because it exceeds the "224 "quota: %s") % encodeutils.exception_to_unicode(e))225 LOG.warn(msg)226 safe_kill(req, image_id, 'saving')227 notifier.error('image.upload', msg)228 raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg,229 request=req,230 content_type='text/plain')231 except webob.exc.HTTPError:232 # NOTE(bcwaldon): Ideally, we would just call 'raise' here,233 # but something in the above function calls is affecting the234 # exception context and we must explicitly re-raise the235 # caught exception.236 msg = _LE("Received HTTP error while uploading image %s") % image_id237 notifier.error('image.upload', msg)238 with excutils.save_and_reraise_exception():239 LOG.exception(msg)240 safe_kill(req, image_id, 'saving')241 except (ValueError, IOError) as e:242 msg = _("Client disconnected before sending all data to backend")243 LOG.warn(msg)244 safe_kill(req, image_id, 'saving')245 raise webob.exc.HTTPBadRequest(explanation=msg,246 content_type="text/plain",247 request=req)248 except Exception as e:249 msg = _("Failed to upload image %s") % image_id250 LOG.exception(msg)251 safe_kill(req, image_id, 'saving')252 notifier.error('image.upload', msg)253 raise webob.exc.HTTPInternalServerError(explanation=msg,254 request=req,255 content_type='text/plain')...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!