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.

server.py 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import glob
  2. import mimetypes
  3. import random
  4. import string
  5. from http import HTTPStatus
  6. from pathlib import Path
  7. import filetype
  8. from roll import Roll
  9. from roll.extensions import simple_server, static
  10. from wand.exceptions import MissingDelegateError
  11. from wand.image import Image
  12. app = Roll()
  13. static(app)
  14. upload_path = Path("uploaded_images")
  15. def _get_random_filename():
  16. random_string = "".join(
  17. random.choices(
  18. string.ascii_lowercase + string.digits + string.ascii_uppercase, k=15
  19. )
  20. )
  21. file_exists = len(glob.glob(f"{upload_path}/{random_string}.*")) > 0
  22. if file_exists:
  23. return _get_random_filename()
  24. return random_string
  25. @app.route("/")
  26. async def home(request, response):
  27. response.headers["Content-Type"] = "text/html; charset=utf-8"
  28. response.body = open("index.html").read()
  29. @app.route("/upload_images", methods=["POST"])
  30. async def upload_images(request, response):
  31. images = request.files.list("images")
  32. for image in images:
  33. random_string = _get_random_filename()
  34. tmp_filepath = Path("/tmp/") / random_string
  35. tmp_filepath.write_bytes(image.read())
  36. output_type = filetype.guess_extension(str(tmp_filepath))
  37. error = None
  38. try:
  39. with Image(filename=tmp_filepath) as img:
  40. img.strip()
  41. with img.convert(output_type) as converted:
  42. output_filename = f"{random_string}.{output_type}"
  43. output_path = upload_path / output_filename
  44. if output_type not in ["gif"]:
  45. converted.sequence = [converted.sequence[0]]
  46. converted.save(filename=str(output_path))
  47. except MissingDelegateError:
  48. error = "Invalid Filetype"
  49. finally:
  50. if tmp_filepath.exists():
  51. tmp_filepath.unlink()
  52. # TODO: deal with errors!
  53. response.status = HTTPStatus.FOUND
  54. response.headers["Location"] = "/"
  55. if __name__ == "__main__":
  56. simple_server(app)