app.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import uuid
  2. import os
  3. import zipfile
  4. import urllib.request
  5. import gzip
  6. from io import BytesIO
  7. import time
  8. from flask import Flask # using flask as the framework
  9. from flask import render_template
  10. from flask import request
  11. # Directory of this file
  12. this_path = os.path.dirname(os.path.realpath(__file__))
  13. # Where the user requested tile are stored
  14. output_path = os.path.join(this_path, '..', 'userRequestTerrain')
  15. # Where the data database is
  16. tile_path = os.path.join(this_path, '..', 'data', 'tiles')
  17. # The output folder for all gzipped terrain requests
  18. app = Flask(__name__, static_url_path='/terrain', static_folder=output_path,)
  19. def compressFiles(fileList, uuidkey):
  20. # create a zip file comprised of dat.gz tiles
  21. zipthis = os.path.join(output_path, uuidkey + '.zip')
  22. # create output dirs if needed
  23. try:
  24. os.makedirs(output_path)
  25. except OSError:
  26. pass
  27. try:
  28. os.makedirs(tile_path)
  29. except OSError:
  30. pass
  31. try:
  32. with zipfile.ZipFile(zipthis, 'w') as terrain_zip:
  33. for fn in fileList:
  34. if not os.path.exists(fn):
  35. #download if required
  36. print("Downloading " + os.path.basename(fn))
  37. g = urllib.request.urlopen('https://terrain.ardupilot.org/data/tiles/' +
  38. os.path.basename(fn))
  39. print("Downloaded " + os.path.basename(fn))
  40. with open(fn, 'b+w') as f:
  41. f.write(g.read())
  42. # need to decompress file and pass to zip
  43. with gzip.open(fn, 'r') as f_in:
  44. myio = BytesIO(f_in.read())
  45. print("Decomp " + os.path.basename(fn))
  46. # and add file to zip
  47. terrain_zip.writestr(os.path.basename(fn)[:-3], myio.read(),
  48. compress_type=zipfile.ZIP_DEFLATED)
  49. except Exception as ex:
  50. print("Unexpected error: {0}".format(ex))
  51. return False
  52. return True
  53. @app.route('/')
  54. def index():
  55. return render_template('index.html')
  56. @app.route('/generate', methods=['GET', 'POST'])
  57. def generate():
  58. if request.method == 'POST':
  59. # request.form['username']
  60. features = []
  61. for i in range(1,8):
  62. value = request.form["option" + str(i)]
  63. features.append(value)
  64. undefine = "undef " + value.split()[1]
  65. features.insert(0,undefine)
  66. extra_hwdef = '\n'.join(features)
  67. print("running...")
  68. file = open('extra_hwdef.dat',"w")
  69. file.write(extra_hwdef)
  70. file.close()
  71. # UUID for this terrain generation
  72. uuidkey = str(uuid.uuid1())
  73. # remove duplicates
  74. filelist = list(dict.fromkeys(filelist))
  75. print(filelist)
  76. #compress
  77. success = compressFiles(filelist, uuidkey)
  78. # as a cleanup, remove any generated terrain older than 24H
  79. for f in os.listdir(output_path):
  80. if os.stat(os.path.join(output_path, f)).st_mtime < time.time() - 24 * 60 * 60:
  81. print("Removing old file: " + str(os.path.join(output_path, f)))
  82. os.remove(os.path.join(output_path, f))
  83. if success:
  84. print("Generated " + "/terrain/" + uuidkey + ".zip")
  85. return render_template('generate.html', urlkey="/terrain/" + uuidkey + ".zip",
  86. uuidkey=uuidkey, outsideLat=outsideLat)
  87. else:
  88. print("Failed " + "/terrain/" + uuidkey + ".zip")
  89. return render_template('generate.html', error="Cannot generate terrain",
  90. uuidkey=uuidkey)
  91. else:
  92. print("Bad get")
  93. return render_template('generate.html', error="Need to use POST, not GET")
  94. if __name__ == "__main__":
  95. app.run()