ldp.py 21 KB

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