Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

128 lines
4.5KB

  1. # @name: resources.py
  2. # @creation_date: 2022-02-23
  3. # @license: The MIT License <https://opensource.org/licenses/MIT>
  4. # @author: Simon Bowie <ad7588@coventry.ac.uk>
  5. # @purpose: functions for resources
  6. # @acknowledgements:
  7. # isbntools: https://isbntools.readthedocs.io/en/latest/info.html
  8. # regex for URLs: https://gist.github.com/gruber/249502
  9. from flask import Blueprint, render_template, request, flash, redirect, url_for
  10. from .models import Resource
  11. from werkzeug.exceptions import abort
  12. from . import db
  13. from .relationships import *
  14. from isbntools.app import *
  15. import requests
  16. import re
  17. from sqlalchemy.sql import func
  18. import markdown
  19. # function to retrieve data about a single resource from the database
  20. def get_resource(resource_id):
  21. resource = Resource.query.filter_by(id=resource_id).first()
  22. if resource is None:
  23. abort(404)
  24. return resource
  25. # function to retrieve data about a resource and its relationships
  26. def get_full_resource(resource_id):
  27. resource = get_resource(resource_id)
  28. resource = append_relationships(resource)
  29. if resource.type == 'book':
  30. # render Markdown as HTML
  31. resource.description = markdown.markdown(resource.description)
  32. # get additional book metadata
  33. book_data = get_book_data(resource.isbn)
  34. if book_data:
  35. resource.__dict__.update(book_data)
  36. return resource
  37. # function to get practice from Markdown file
  38. def get_practice_markdown(practice_name, option='html'):
  39. file_name = practice_name.replace(" ", "_")
  40. with open(f'content/practices/{file_name}.md', 'r') as f:
  41. practice_text = f.read()
  42. if option == 'html':
  43. practice_text = markdown.markdown(practice_text)
  44. return practice_text
  45. # function to write new or edited practice to Markdown file
  46. def write_practice_markdown(practice_name, markdown):
  47. practice_name = practice_name.replace(" ", "_")
  48. with open(f'content/practices/{practice_name}.md', 'w+') as f:
  49. f.write(markdown)
  50. # function to extract only the first paragraph of practice Markdown
  51. def extract_first_paragraph(markdown):
  52. # Split the text into lines
  53. lines = markdown.split("\n")
  54. # Initialize a flag to track when we find the first paragraph
  55. paragraph = []
  56. for line in lines:
  57. # Ignore headings (lines starting with #)
  58. if line.startswith("#"):
  59. continue
  60. # If the line is not empty, it's part of a paragraph
  61. if line.strip():
  62. paragraph.append(line.strip())
  63. elif paragraph: # Stop once we have collected a paragraph and hit an empty line
  64. break
  65. return " ".join(paragraph)
  66. # function to retrieve data about a curated list of resources
  67. def get_curated_resources(resource_ids):
  68. resources = Resource.query.filter(Resource.id.in_(resource_ids)).order_by(func.random()).all()
  69. # append relationships to each resource
  70. append_relationships_multiple(resources)
  71. return resources
  72. # function to delete a single resource
  73. def delete_resource(resource_id):
  74. deletion = Resource.query.get(resource_id)
  75. db.session.delete(deletion)
  76. db.session.commit()
  77. flash('Successfully deleted!')
  78. # function to get filters for a specific field
  79. def get_filter_values(field, type):
  80. # get field values for filter
  81. field_filter = Resource.query.filter_by(type=type).with_entities(getattr(Resource, field))
  82. # turn SQLAlchemy object into list
  83. field_filter = [i for i, in field_filter]
  84. # split each element on '/' (useful for scriptingLanguage only)
  85. field_filter = [y for x in field_filter for y in x.split(' / ')]
  86. # consolidate duplicate values
  87. field_filter = list(dict.fromkeys(field_filter))
  88. # filter None values from list
  89. field_filter = filter(None, field_filter)
  90. # sort list by alphabetical order
  91. field_filter = sorted(field_filter)
  92. return field_filter
  93. # function to get book data including metadata and covers
  94. def get_book_data(isbn):
  95. try:
  96. book = meta(isbn)
  97. description = {'desc': desc(isbn)}
  98. book.update(description)
  99. #book = get_book_cover(book)
  100. return book
  101. except:
  102. pass
  103. # function to get book cover data
  104. def get_book_cover(book):
  105. # get highest-resolution book cover possible
  106. openl_url = 'https://covers.openlibrary.org/b/isbn/' + book['ISBN-13'] + '-L.jpg?default=false'
  107. request = requests.get(openl_url)
  108. if request.status_code != 200:
  109. book.update(cover(isbn))
  110. else:
  111. book_cover = {'thumbnail': openl_url}
  112. book.update(book_cover)
  113. return book