ldp.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. import logging
  2. import pdb
  3. from collections import defaultdict
  4. from io import BytesIO
  5. from pprint import pformat
  6. from uuid import uuid4
  7. import arrow
  8. from flask import (
  9. Blueprint, Response, g, make_response, render_template,
  10. request, send_file)
  11. from rdflib import Graph, plugin, parser#, serializer
  12. from lakesuperior.api import resource as rsrc_api
  13. from lakesuperior.dictionaries.namespaces import ns_collection as nsc
  14. from lakesuperior.dictionaries.namespaces import ns_mgr as nsm
  15. from lakesuperior.exceptions import (ResourceNotExistsError, TombstoneError,
  16. ServerManagedTermError, InvalidResourceError, SingleSubjectError,
  17. ResourceExistsError, IncompatibleLdpTypeError)
  18. from lakesuperior.globals import RES_CREATED
  19. from lakesuperior.model.ldp_factory import LdpFactory
  20. from lakesuperior.model.ldp_nr import LdpNr
  21. from lakesuperior.model.ldp_rs import LdpRs
  22. from lakesuperior.model.ldpr import Ldpr
  23. from lakesuperior.store.ldp_rs.lmdb_store import TxnManager
  24. from lakesuperior.toolbox import Toolbox
  25. DEFAULT_RDF_MIMETYPE = 'text/turtle'
  26. """
  27. Fallback serialization format used when no acceptable formats are specified.
  28. """
  29. logger = logging.getLogger(__name__)
  30. rdf_parsable_mimetypes = {
  31. mt.name for mt in plugin.plugins()
  32. if mt.kind is parser.Parser and '/' in mt.name
  33. }
  34. """MIMEtypes that can be parsed into RDF."""
  35. rdf_serializable_mimetypes = {
  36. #mt.name for mt in plugin.plugins()
  37. #if mt.kind is serializer.Serializer and '/' in mt.name
  38. 'application/ld+json',
  39. 'application/n-triples',
  40. 'application/rdf+xml',
  41. 'text/turtle',
  42. 'text/n3',
  43. }
  44. """
  45. MIMEtypes that RDF can be serialized into.
  46. These are not automatically derived from RDFLib because only triple
  47. (not quad) serializations are applicable.
  48. """
  49. accept_patch = (
  50. 'application/sparql-update',
  51. )
  52. std_headers = {
  53. 'Accept-Patch' : ','.join(accept_patch),
  54. 'Accept-Post' : ','.join(rdf_parsable_mimetypes),
  55. }
  56. """Predicates excluded by view."""
  57. vw_blacklist = {
  58. }
  59. ldp = Blueprint(
  60. 'ldp', __name__, template_folder='templates',
  61. static_url_path='/static', static_folder='templates/static')
  62. """
  63. Blueprint for LDP REST API. This is what is usually found under ``/rest/`` in
  64. standard fcrepo4. Here, it is under ``/ldp`` but initially ``/rest`` will be
  65. kept for backward compatibility.
  66. """
  67. ## ROUTE PRE- & POST-PROCESSING ##
  68. @ldp.url_defaults
  69. def bp_url_defaults(endpoint, values):
  70. url_prefix = getattr(g, 'url_prefix', None)
  71. if url_prefix is not None:
  72. values.setdefault('url_prefix', url_prefix)
  73. @ldp.url_value_preprocessor
  74. def bp_url_value_preprocessor(endpoint, values):
  75. g.url_prefix = values.pop('url_prefix')
  76. g.webroot = request.host_url + g.url_prefix
  77. # Normalize leading slashes for UID.
  78. if 'uid' in values:
  79. values['uid'] = '/' + values['uid'].lstrip('/')
  80. if 'parent_uid' in values:
  81. values['parent_uid'] = '/' + values['parent_uid'].lstrip('/')
  82. @ldp.before_request
  83. def log_request_start():
  84. logger.info('** Start {} {} **'.format(request.method, request.url))
  85. @ldp.before_request
  86. def instantiate_req_vars():
  87. g.tbox = Toolbox()
  88. @ldp.after_request
  89. def log_request_end(rsp):
  90. logger.info('** End {} {} **'.format(request.method, request.url))
  91. return rsp
  92. ## REST SERVICES ##
  93. @ldp.route('/<path:uid>', methods=['GET'], strict_slashes=False)
  94. @ldp.route('/', defaults={'uid': '/'}, methods=['GET'], strict_slashes=False)
  95. @ldp.route('/<path:uid>/fcr:metadata', defaults={'out_fmt' : 'rdf'},
  96. methods=['GET'])
  97. @ldp.route('/<path:uid>/fcr:content', defaults={'out_fmt' : 'non_rdf'},
  98. methods=['GET'])
  99. def get_resource(uid, out_fmt=None):
  100. r"""
  101. https://www.w3.org/TR/ldp/#ldpr-HTTP_GET
  102. Retrieve RDF or binary content.
  103. :param str uid: UID of resource to retrieve. The repository root has
  104. an empty string for UID.
  105. :param str out_fmt: Force output to RDF or non-RDF if the resource is
  106. a LDP-NR. This is not available in the API but is used e.g. by the
  107. ``\*/fcr:metadata`` and ``\*/fcr:content`` endpoints. The default is
  108. False.
  109. """
  110. logger.info('UID: {}'.format(uid))
  111. out_headers = std_headers
  112. repr_options = defaultdict(dict)
  113. if 'prefer' in request.headers:
  114. prefer = g.tbox.parse_rfc7240(request.headers['prefer'])
  115. logger.debug('Parsed Prefer header: {}'.format(pformat(prefer)))
  116. if 'return' in prefer:
  117. repr_options = parse_repr_options(prefer['return'])
  118. try:
  119. rsrc = rsrc_api.get(uid, repr_options)
  120. except ResourceNotExistsError as e:
  121. return str(e), 404
  122. except TombstoneError as e:
  123. return _tombstone_response(e, uid)
  124. else:
  125. if out_fmt is None:
  126. rdf_mimetype = _best_rdf_mimetype()
  127. out_fmt = (
  128. 'rdf'
  129. if isinstance(rsrc, LdpRs) or rdf_mimetype is not None
  130. else 'non_rdf')
  131. out_headers.update(_headers_from_metadata(rsrc))
  132. uri = g.tbox.uid_to_uri(uid)
  133. if out_fmt == 'rdf':
  134. if locals().get('rdf_mimetype', None) is None:
  135. rdf_mimetype = DEFAULT_RDF_MIMETYPE
  136. ggr = g.tbox.globalize_graph(rsrc.out_graph)
  137. ggr.namespace_manager = nsm
  138. return _negotiate_content(
  139. ggr, rdf_mimetype, out_headers, uid=uid, uri=uri)
  140. else:
  141. if not getattr(rsrc, 'local_path', False):
  142. return ('{} has no binary content.'.format(rsrc.uid), 404)
  143. logger.debug('Streaming out binary content.')
  144. rsp = make_response(send_file(
  145. rsrc.local_path, as_attachment=True,
  146. attachment_filename=rsrc.filename,
  147. mimetype=rsrc.mimetype))
  148. logger.debug('Out headers: {}'.format(out_headers))
  149. rsp.headers.add('Link',
  150. '<{}/fcr:metadata>; rel="describedby"'.format(uri))
  151. for link in out_headers['Link']:
  152. rsp.headers.add('Link', link)
  153. return rsp
  154. @ldp.route('/<path:uid>/fcr:versions', methods=['GET'])
  155. def get_version_info(uid):
  156. """
  157. Get version info (`fcr:versions`).
  158. :param str uid: UID of resource to retrieve versions for.
  159. """
  160. rdf_mimetype = _best_rdf_mimetype() or DEFAULT_RDF_MIMETYPE
  161. try:
  162. gr = rsrc_api.get_version_info(uid)
  163. except ResourceNotExistsError as e:
  164. return str(e), 404
  165. except InvalidResourceError as e:
  166. return str(e), 409
  167. except TombstoneError as e:
  168. return _tombstone_response(e, uid)
  169. else:
  170. return _negotiate_content(g.tbox.globalize_graph(gr), rdf_mimetype)
  171. @ldp.route('/<path:uid>/fcr:versions/<ver_uid>', methods=['GET'])
  172. def get_version(uid, ver_uid):
  173. """
  174. Get an individual resource version.
  175. :param str uid: Resource UID.
  176. :param str ver_uid: Version UID.
  177. """
  178. rdf_mimetype = _best_rdf_mimetype() or DEFAULT_RDF_MIMETYPE
  179. try:
  180. gr = rsrc_api.get_version(uid, ver_uid)
  181. except ResourceNotExistsError as e:
  182. return str(e), 404
  183. except InvalidResourceError as e:
  184. return str(e), 409
  185. except TombstoneError as e:
  186. return _tombstone_response(e, uid)
  187. else:
  188. return _negotiate_content(g.tbox.globalize_graph(gr), rdf_mimetype)
  189. @ldp.route('/<path:parent_uid>', methods=['POST'], strict_slashes=False)
  190. @ldp.route('/', defaults={'parent_uid': '/'}, methods=['POST'],
  191. strict_slashes=False)
  192. def post_resource(parent_uid):
  193. """
  194. https://www.w3.org/TR/ldp/#ldpr-HTTP_POST
  195. Add a new resource in a new URI.
  196. """
  197. out_headers = std_headers
  198. try:
  199. slug = request.headers['Slug']
  200. logger.debug('Slug: {}'.format(slug))
  201. except KeyError:
  202. slug = None
  203. handling, disposition = set_post_put_params()
  204. stream, mimetype = _bistream_from_req()
  205. if mimetype in rdf_parsable_mimetypes:
  206. # If the content is RDF, localize in-repo URIs.
  207. global_rdf = stream.read()
  208. rdf_data = g.tbox.localize_payload(global_rdf)
  209. rdf_fmt = mimetype
  210. stream = mimetype = None
  211. else:
  212. rdf_data = rdf_fmt = None
  213. try:
  214. uid = rsrc_api.create(
  215. parent_uid, slug, stream=stream, mimetype=mimetype,
  216. rdf_data=rdf_data, rdf_fmt=rdf_fmt, handling=handling,
  217. disposition=disposition)
  218. except ResourceNotExistsError as e:
  219. return str(e), 404
  220. except InvalidResourceError as e:
  221. return str(e), 409
  222. except TombstoneError as e:
  223. return _tombstone_response(e, uid)
  224. except ServerManagedTermError as e:
  225. return str(e), 412
  226. uri = g.tbox.uid_to_uri(uid)
  227. hdr = {'Location' : uri}
  228. if mimetype and rdf_fmt is None:
  229. hdr['Link'] = '<{0}/fcr:metadata>; rel="describedby"; anchor="{0}"'\
  230. .format(uri)
  231. out_headers.update(hdr)
  232. return uri, 201, out_headers
  233. @ldp.route('/<path:uid>', methods=['PUT'], strict_slashes=False)
  234. @ldp.route('/<path:uid>/fcr:metadata', defaults={'force_rdf' : True},
  235. methods=['PUT'])
  236. def put_resource(uid):
  237. """
  238. https://www.w3.org/TR/ldp/#ldpr-HTTP_PUT
  239. Add or replace a new resource at a specified URI.
  240. """
  241. # Parse headers.
  242. logger.debug('Request headers: {}'.format(request.headers))
  243. rsp_headers = {'Content-Type' : 'text/plain; charset=utf-8'}
  244. handling, disposition = set_post_put_params()
  245. stream, mimetype = _bistream_from_req()
  246. if mimetype in rdf_parsable_mimetypes:
  247. # If the content is RDF, localize in-repo URIs.
  248. global_rdf = stream.read()
  249. rdf_data = g.tbox.localize_payload(global_rdf)
  250. rdf_fmt = mimetype
  251. stream = mimetype = None
  252. else:
  253. rdf_data = rdf_fmt = None
  254. try:
  255. evt = rsrc_api.create_or_replace(
  256. uid, stream=stream, mimetype=mimetype,
  257. rdf_data=rdf_data, rdf_fmt=rdf_fmt, handling=handling,
  258. disposition=disposition)
  259. except (InvalidResourceError, ResourceExistsError) as e:
  260. return str(e), 409
  261. except (ServerManagedTermError, SingleSubjectError) as e:
  262. return str(e), 412
  263. except IncompatibleLdpTypeError as e:
  264. return str(e), 415
  265. except TombstoneError as e:
  266. return _tombstone_response(e, uid)
  267. uri = g.tbox.uid_to_uri(uid)
  268. if evt == RES_CREATED:
  269. rsp_code = 201
  270. rsp_headers['Location'] = rsp_body = uri
  271. if mimetype and not rdf_data:
  272. rsp_headers['Link'] = (
  273. '<{0}/fcr:metadata>; rel="describedby"'.format(uri))
  274. else:
  275. rsp_code = 204
  276. rsp_body = ''
  277. return rsp_body, rsp_code, rsp_headers
  278. @ldp.route('/<path:uid>', methods=['PATCH'], strict_slashes=False)
  279. @ldp.route('/', defaults={'uid': '/'}, methods=['PATCH'],
  280. strict_slashes=False)
  281. def patch_resource(uid, is_metadata=False):
  282. """
  283. https://www.w3.org/TR/ldp/#ldpr-HTTP_PATCH
  284. Update an existing resource with a SPARQL-UPDATE payload.
  285. """
  286. rsp_headers = {'Content-Type' : 'text/plain; charset=utf-8'}
  287. if request.mimetype != 'application/sparql-update':
  288. return 'Provided content type is not a valid parsable format: {}'\
  289. .format(request.mimetype), 415
  290. update_str = request.get_data().decode('utf-8')
  291. local_update_str = g.tbox.localize_ext_str(update_str, nsc['fcres'][uid])
  292. try:
  293. rsrc = rsrc_api.update(uid, local_update_str, is_metadata)
  294. except ResourceNotExistsError as e:
  295. return str(e), 404
  296. except TombstoneError as e:
  297. return _tombstone_response(e, uid)
  298. except (ServerManagedTermError, SingleSubjectError) as e:
  299. return str(e), 412
  300. except InvalidResourceError as e:
  301. return str(e), 415
  302. else:
  303. rsp_headers.update(_headers_from_metadata(rsrc))
  304. return '', 204, rsp_headers
  305. @ldp.route('/<path:uid>/fcr:metadata', methods=['PATCH'])
  306. def patch_resource_metadata(uid):
  307. return patch_resource(uid, True)
  308. @ldp.route('/<path:uid>', methods=['DELETE'])
  309. def delete_resource(uid):
  310. """
  311. Delete a resource and optionally leave a tombstone.
  312. This behaves differently from FCREPO. A tombstone indicated that the
  313. resource is no longer available at its current location, but its historic
  314. snapshots still are. Also, deleting a resource with a tombstone creates
  315. one more version snapshot of the resource prior to being deleted.
  316. In order to completely wipe out all traces of a resource, the tombstone
  317. must be deleted as well, or the ``Prefer:no-tombstone`` header can be used.
  318. The latter will forget (completely delete) the resource immediately.
  319. """
  320. headers = std_headers
  321. if 'prefer' in request.headers:
  322. prefer = g.tbox.parse_rfc7240(request.headers['prefer'])
  323. leave_tstone = 'no-tombstone' not in prefer
  324. else:
  325. leave_tstone = True
  326. try:
  327. rsrc_api.delete(uid, leave_tstone)
  328. except ResourceNotExistsError as e:
  329. return str(e), 404
  330. except TombstoneError as e:
  331. return _tombstone_response(e, uid)
  332. return '', 204, headers
  333. @ldp.route('/<path:uid>/fcr:tombstone', methods=['GET', 'POST', 'PUT',
  334. 'PATCH', 'DELETE'])
  335. def tombstone(uid):
  336. """
  337. Handle all tombstone operations.
  338. The only allowed methods are POST and DELETE; any other verb will return a
  339. 405.
  340. """
  341. try:
  342. rsrc = rsrc_api.get(uid)
  343. except TombstoneError as e:
  344. if request.method == 'DELETE':
  345. if e.uid == uid:
  346. rsrc_api.delete(uid, False)
  347. return '', 204
  348. else:
  349. return _tombstone_response(e, uid)
  350. elif request.method == 'POST':
  351. if e.uid == uid:
  352. rsrc_uri = rsrc_api.resurrect(uid)
  353. headers = {'Location' : rsrc_uri}
  354. return rsrc_uri, 201, headers
  355. else:
  356. return _tombstone_response(e, uid)
  357. else:
  358. return 'Method Not Allowed.', 405
  359. except ResourceNotExistsError as e:
  360. return str(e), 404
  361. else:
  362. return '', 404
  363. @ldp.route('/<path:uid>/fcr:versions', methods=['POST', 'PUT'])
  364. def post_version(uid):
  365. """
  366. Create a new resource version.
  367. """
  368. if request.method == 'PUT':
  369. return 'Method not allowed.', 405
  370. ver_uid = request.headers.get('slug', None)
  371. try:
  372. ver_uid = rsrc_api.create_version(uid, ver_uid)
  373. except ResourceNotExistsError as e:
  374. return str(e), 404
  375. except InvalidResourceError as e:
  376. return str(e), 409
  377. except TombstoneError as e:
  378. return _tombstone_response(e, uid)
  379. else:
  380. return '', 201, {'Location': g.tbox.uid_to_uri(ver_uid)}
  381. @ldp.route('/<path:uid>/fcr:versions/<ver_uid>', methods=['PATCH'])
  382. def patch_version(uid, ver_uid):
  383. """
  384. Revert to a previous version.
  385. NOTE: This creates a new version snapshot.
  386. :param str uid: Resource UID.
  387. :param str ver_uid: Version UID.
  388. """
  389. try:
  390. rsrc_api.revert_to_version(uid, rsrc_uid)
  391. except ResourceNotExistsError as e:
  392. return str(e), 404
  393. except InvalidResourceError as e:
  394. return str(e), 409
  395. except TombstoneError as e:
  396. return _tombstone_response(e, uid)
  397. else:
  398. return '', 204
  399. ## PRIVATE METHODS ##
  400. def _best_rdf_mimetype():
  401. """
  402. Check if any of the 'Accept' header values provided is a RDF parsable
  403. format.
  404. """
  405. for accept in request.accept_mimetypes:
  406. mimetype = accept[0]
  407. if mimetype in rdf_parsable_mimetypes:
  408. return mimetype
  409. return None
  410. def _negotiate_content(gr, rdf_mimetype, headers=None, **vw_kwargs):
  411. """
  412. Return HTML or serialized RDF depending on accept headers.
  413. """
  414. if request.accept_mimetypes.best == 'text/html':
  415. return render_template(
  416. 'resource.html', gr=gr, nsc=nsc, nsm=nsm,
  417. blacklist=vw_blacklist, arrow=arrow, **vw_kwargs)
  418. else:
  419. for p in vw_blacklist:
  420. gr.remove((None, p, None))
  421. return Response(
  422. gr.serialize(format=rdf_mimetype), 200, headers,
  423. mimetype=rdf_mimetype)
  424. def _bistream_from_req():
  425. """
  426. Find how a binary file and its MIMEtype were uploaded in the request.
  427. """
  428. #logger.debug('Content type: {}'.format(request.mimetype))
  429. #logger.debug('files: {}'.format(request.files))
  430. #logger.debug('stream: {}'.format(request.stream))
  431. if request.mimetype == 'multipart/form-data':
  432. # This seems the "right" way to upload a binary file, with a
  433. # multipart/form-data MIME type and the file in the `file`
  434. # field. This however is not supported by FCREPO4.
  435. stream = request.files.get('file').stream
  436. mimetype = request.files.get('file').content_type
  437. # @TODO This will turn out useful to provide metadata
  438. # with the binary.
  439. #metadata = request.files.get('metadata').stream
  440. else:
  441. # This is a less clean way, with the file in the form body and
  442. # the request as application/x-www-form-urlencoded.
  443. # This is how FCREPO4 accepts binary uploads.
  444. stream = request.stream
  445. # @FIXME Must decide what to do with this.
  446. mimetype = request.mimetype
  447. if mimetype == '' or mimetype == 'application/x-www-form-urlencoded':
  448. if getattr(stream, 'limit', 0) == 0:
  449. stream = mimetype = None
  450. else:
  451. mimetype = 'application/octet-stream'
  452. return stream, mimetype
  453. def _tombstone_response(e, uid):
  454. headers = {
  455. 'Link': '<{}/fcr:tombstone>; rel="hasTombstone"'.format(request.url),
  456. } if e.uid == uid else {}
  457. return str(e), 410, headers
  458. def set_post_put_params():
  459. """
  460. Sets handling and content disposition for POST and PUT by parsing headers.
  461. """
  462. handling = 'strict'
  463. if 'prefer' in request.headers:
  464. prefer = g.tbox.parse_rfc7240(request.headers['prefer'])
  465. logger.debug('Parsed Prefer header: {}'.format(prefer))
  466. if 'handling' in prefer:
  467. handling = prefer['handling']['value']
  468. try:
  469. disposition = g.tbox.parse_rfc7240(
  470. request.headers['content-disposition'])
  471. except KeyError:
  472. disposition = None
  473. return handling, disposition
  474. def parse_repr_options(retr_opts):
  475. """
  476. Set options to retrieve IMR.
  477. Ideally, IMR retrieval is done once per request, so all the options
  478. are set once in the `imr()` property.
  479. :param dict retr_opts:: Options parsed from `Prefer` header.
  480. """
  481. logger.debug('Parsing retrieval options: {}'.format(retr_opts))
  482. imr_options = {}
  483. if retr_opts.get('value') == 'minimal':
  484. imr_options = {
  485. 'embed_children' : False,
  486. 'incl_children' : False,
  487. 'incl_inbound' : False,
  488. 'incl_srv_mgd' : False,
  489. }
  490. else:
  491. # Default.
  492. imr_options = {
  493. 'embed_children' : False,
  494. 'incl_children' : True,
  495. 'incl_inbound' : False,
  496. 'incl_srv_mgd' : True,
  497. }
  498. # Override defaults.
  499. if 'parameters' in retr_opts:
  500. include = retr_opts['parameters']['include'].split(' ') \
  501. if 'include' in retr_opts['parameters'] else []
  502. omit = retr_opts['parameters']['omit'].split(' ') \
  503. if 'omit' in retr_opts['parameters'] else []
  504. logger.debug('Include: {}'.format(include))
  505. logger.debug('Omit: {}'.format(omit))
  506. if str(Ldpr.EMBED_CHILD_RES_URI) in include:
  507. imr_options['embed_children'] = True
  508. if str(Ldpr.RETURN_CHILD_RES_URI) in omit:
  509. imr_options['incl_children'] = False
  510. if str(Ldpr.RETURN_INBOUND_REF_URI) in include:
  511. imr_options['incl_inbound'] = True
  512. if str(Ldpr.RETURN_SRV_MGD_RES_URI) in omit:
  513. imr_options['incl_srv_mgd'] = False
  514. logger.debug('Retrieval options: {}'.format(pformat(imr_options)))
  515. return imr_options
  516. def _headers_from_metadata(rsrc):
  517. """
  518. Create a dict of headers from a metadata graph.
  519. :param lakesuperior.model.ldpr.Ldpr rsrc: Resource to extract metadata
  520. from.
  521. """
  522. out_headers = defaultdict(list)
  523. digest = rsrc.metadata.value(nsc['premis'].hasMessageDigest)
  524. if digest:
  525. etag = digest.identifier.split(':')[-1]
  526. etag_str = (
  527. 'W/"{}"'.format(etag)
  528. if nsc['ldp'].RDFSource in rsrc.ldp_types
  529. else etag)
  530. out_headers['ETag'] = etag_str,
  531. last_updated_term = rsrc.metadata.value(nsc['fcrepo'].lastModified)
  532. if last_updated_term:
  533. out_headers['Last-Modified'] = arrow.get(last_updated_term)\
  534. .format('ddd, D MMM YYYY HH:mm:ss Z')
  535. for t in rsrc.ldp_types:
  536. out_headers['Link'].append(
  537. '{};rel="type"'.format(t.n3()))
  538. mimetype = rsrc.metadata.value(nsc['ebucore'].hasMimeType)
  539. if mimetype:
  540. out_headers['Content-Type'] = mimetype
  541. return out_headers