Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

resources.py 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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. # function to retrieve data about a single resource from the database
  18. def get_resource(resource_id):
  19. resource = Resource.query.filter_by(id=resource_id).first()
  20. if resource is None:
  21. abort(404)
  22. return resource
  23. # function to retrieve data about a resource and its relationships
  24. def get_full_resource(resource_id):
  25. resource = get_resource(resource_id)
  26. relationships = get_relationships(resource_id)
  27. for relationship in relationships:
  28. if relationship.type == 'tool':
  29. if 'tools' not in resource.__dict__.keys():
  30. resource.__dict__['tools'] = relationship
  31. elif type(resource.__dict__['tools']) == list:
  32. resource.__dict__['tools'].append(relationship)
  33. else:
  34. resource.__dict__['tools'] = [resource.__dict__['tools'], relationship]
  35. elif relationship.type == 'practice':
  36. if 'practices' not in resource.__dict__.keys():
  37. resource.__dict__['practices'] = relationship
  38. elif type(resource.__dict__['practices']) == list:
  39. resource.__dict__['practices'].append(relationship)
  40. else:
  41. resource.__dict__['practices'] = [resource.__dict__['practices'], relationship]
  42. elif relationship.type == 'book':
  43. if 'books' not in resource.__dict__.keys():
  44. resource.__dict__['books'] = relationship
  45. elif type(resource.__dict__['books']) == list:
  46. resource.__dict__['books'].append(relationship)
  47. else:
  48. resource.__dict__['books'] = [resource.__dict__['books'], relationship]
  49. if resource.type == 'book':
  50. book_data = get_book_data(resource.isbn)
  51. resource.__dict__.update(book_data)
  52. return resource
  53. # function to delete a single resource
  54. def delete_resource(resource_id):
  55. deletion = Resource.query.get(resource_id)
  56. db.session.delete(deletion)
  57. db.session.commit()
  58. flash('Successfully deleted!')
  59. # function to get filters for a specific field
  60. def get_filter_values(field, type):
  61. # get field values for filter
  62. field_filter = Resource.query.filter_by(type=type).with_entities(getattr(Resource, field))
  63. # turn SQLAlchemy object into list
  64. field_filter = [i for i, in field_filter]
  65. # split each element on '/' (useful for scriptingLanguage only)
  66. field_filter = [y for x in field_filter for y in x.split(' / ')]
  67. # consolidate duplicate values
  68. field_filter = list(dict.fromkeys(field_filter))
  69. # filter None values from list
  70. field_filter = filter(None, field_filter)
  71. # sort list by alphabetical order
  72. field_filter = sorted(field_filter)
  73. return field_filter
  74. # function to get book data including metadata and covers
  75. def get_book_data(isbn):
  76. try:
  77. book = meta(isbn)
  78. description = {'desc': desc(isbn)}
  79. book.update(description)
  80. # get highest-resolution book cover possible
  81. openl_url = 'https://covers.openlibrary.org/b/isbn/' + book['ISBN-13'] + '-L.jpg?default=false'
  82. request = requests.get(openl_url)
  83. if request.status_code != 200:
  84. book.update(cover(isbn))
  85. else:
  86. book_cover = {'thumbnail': openl_url}
  87. book.update(book_cover)
  88. return book
  89. except:
  90. pass
  91. # function to get full metadata for a book and combine into one object
  92. def get_book(resource_id):
  93. book = get_resource(resource_id)
  94. book_data = get_book_data(book.isbn)
  95. book.__dict__.update(book_data)
  96. return book
  97. # function to replace embedded URL strings with href links
  98. def replace_urls(input):
  99. # Compile a regular expression to match URLs.
  100. # This regular expression is not exhaustive and may not match all possible URLs.
  101. # It is intended to be a starting point and can be refined and expanded as needed.
  102. url_regex = re.compile(r'((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)/)(?:[^\s()<>{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:\'\".,<>?«»“”‘’])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)\b/?(?!@)))')
  103. # Find all URLs in the input string using the regular expression.
  104. # This will return a list of Match objects, each of which represents a single URL in the string.
  105. matches = url_regex.finditer(input)
  106. # Iterate over the list of matches and replace each URL with an HTML link.
  107. for match in matches:
  108. # Get the full URL from the Match object.
  109. url = match.group(0)
  110. # Create the HTML link by wrapping the URL in an <a> tag.
  111. # If the URL does not include a protocol (e.g. "http://" or "https://"),
  112. # then add "http://" as the default protocol.
  113. if not url.startswith('http'):
  114. link = f'<a href="http://{url}">{url}</a>'
  115. else:
  116. link = f'<a href="{url}">{url}</a>'
  117. # Replace the URL in the original string with the HTML link.
  118. input = input.replace(url, link)
  119. return input