utils.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # -*- coding: utf-8 -*-
  2. from flask import current_app
  3. from collections import OrderedDict
  4. from datetime import datetime
  5. import pytz
  6. import json
  7. from . import db
  8. def dict_to_geojson(d_in):
  9. """
  10. Encode a dict representing a GeoJSON object into a JSON string.
  11. This is needed because spatialite's GeoJSON parser is not really
  12. JSON-compliant and it fails when keys are not in the right order.
  13. """
  14. d=OrderedDict()
  15. d['type']=d_in['type']
  16. if 'crs' in d_in:
  17. d['crs']=d_in['crs']
  18. # our spatialite geo column is defined with EPSG SRID 4326 (WGS 84)
  19. d['crs'] = {'type': 'name', 'properties': {'name': 'urn:ogc:def:crs:EPSG:4326'}}
  20. if 'bbox' in d_in:
  21. d['bbox']=d_in['bbox']
  22. d['coordinates']=d_in['coordinates']
  23. return json.dumps(d)
  24. def check_geojson_spatialite(_gjson):
  25. """
  26. Checks if a GeoJSON dict is understood by spatialite
  27. >>> check_geojson_spatialite({'type': 'NOPE', 'coordinates': []})
  28. False
  29. >>> check_geojson_spatialite({'type': 'Polygon', 'coordinates': [
  30. ... [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]]
  31. ... ]})
  32. True
  33. """
  34. gjson=dict_to_geojson(_gjson)
  35. return bool(db.session.query(db.func.GeomFromGeoJSON(gjson) != None).first()[0])
  36. def utcnow():
  37. """
  38. Return the current UTC date and time as a datetime object with proper tzinfo.
  39. """
  40. return datetime.utcnow().replace(tzinfo=pytz.utc)
  41. def tosystemtz(d):
  42. """
  43. Convert the UTC datetime ``d`` to the system time zone defined in the settings
  44. """
  45. return d.astimezone(pytz.timezone(current_app.config['SYSTEM_TIME_ZONE']))
  46. def filesize_fmt(num):
  47. fmt = lambda num, unit: "%s %s" % (format(num, '.2f').rstrip('0').rstrip('.'), unit)
  48. for x in ['bytes', 'KiB', 'MiB', 'GiB']:
  49. if num < 1024.0:
  50. return fmt(num, x)
  51. num /= 1024.0
  52. return fmt(num, 'TiB')