bearer_data_source.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # [REVIEW] Implement if Needed? Do we need a new type of data source
  2. from abc import abstractmethod
  3. import requests
  4. from api.models.source import DataSourceBearerBinding
  5. from flask_login import current_user
  6. from extensions.ext_database import db
  7. class BearerDataSource:
  8. def __init__(self, api_key: str, api_base_url: str):
  9. self.api_key = api_key
  10. self.api_base_url = api_base_url
  11. @abstractmethod
  12. def validate_bearer_data_source(self):
  13. """
  14. Validate the data source
  15. """
  16. class FireCrawlDataSource(BearerDataSource):
  17. def validate_bearer_data_source(self):
  18. TEST_CRAWL_SITE_URL = "https://www.google.com"
  19. FIRECRAWL_API_VERSION = "v0"
  20. test_api_endpoint = self.api_base_url.rstrip('/') + f"/{FIRECRAWL_API_VERSION}/scrape"
  21. headers = {
  22. "Authorization": f"Bearer {self.api_key}",
  23. "Content-Type": "application/json",
  24. }
  25. data = {
  26. "url": TEST_CRAWL_SITE_URL,
  27. }
  28. response = requests.get(test_api_endpoint, headers=headers, json=data)
  29. return response.json().get("status") == "success"
  30. def save_credentials(self):
  31. # save data source binding
  32. data_source_binding = DataSourceBearerBinding.query.filter(
  33. db.and_(
  34. DataSourceBearerBinding.tenant_id == current_user.current_tenant_id,
  35. DataSourceBearerBinding.provider == 'firecrawl',
  36. DataSourceBearerBinding.endpoint_url == self.api_base_url,
  37. DataSourceBearerBinding.bearer_key == self.api_key
  38. )
  39. ).first()
  40. if data_source_binding:
  41. data_source_binding.disabled = False
  42. db.session.commit()
  43. else:
  44. new_data_source_binding = DataSourceBearerBinding(
  45. tenant_id=current_user.current_tenant_id,
  46. provider='firecrawl',
  47. endpoint_url=self.api_base_url,
  48. bearer_key=self.api_key
  49. )
  50. db.session.add(new_data_source_binding)
  51. db.session.commit()