__init__.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import secrets
  2. import asyncio
  3. from shlex import quote
  4. from typing import Iterable, Union
  5. import aiofiles
  6. from .process import run_cmd, Process
  7. from .files import write_file
  8. from build_django import const
  9. def generate_env(debug: bool = False, hosts: str = '*') -> str:
  10. items = [
  11. f'SECRET_KEY={secrets.token_hex(128)}',
  12. f'ALLOWED_HOSTS={hosts}'
  13. ]
  14. if debug:
  15. items.append('DEBUG=True')
  16. return '\n\n'.join(items)
  17. async def edit_settings(file) -> list[str]:
  18. result = []
  19. async for line in file:
  20. if line.startswith('BASE_DIR'):
  21. result.append('\nfrom environ import Env\n')
  22. result.append(f'\n{line}\n')
  23. result.append(f'\nenv = Env({const.DEFAULT_ENV})\n')
  24. result.append('\nEnv.read_env(BASE_DIR / \'.env\')\n')
  25. elif line.startswith('SECRET_KEY'):
  26. result.append('SECRET_KEY = env(\'SECRET_KEY\')\n')
  27. elif line.startswith('ALLOWED_HOSTS'):
  28. result.append('ALLOWED_HOSTS = env.tuple(\'ALLOWED_HOSTS\')')
  29. elif line.startswith('DEBUG'):
  30. result.append('DEBUG = env(\'DEBUG\')\n')
  31. else:
  32. result.append(line)
  33. result.extend((
  34. '\n# Custom settings\n'
  35. "\nif env('USE_SSL'):\n",
  36. ' ' * 4 + "SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')"
  37. ))
  38. return result
  39. async def write_settings(path: str):
  40. async with aiofiles.open(path, 'r+') as file:
  41. result = await edit_settings(file)
  42. await file.seek(0)
  43. await file.writelines(result)
  44. async def write_requirements(path: str, pip_path: str):
  45. async with aiofiles.open(path, 'w') as file:
  46. await run_cmd((pip_path, 'freeze'), stdout=file)
  47. async def install_package(pip_path: str, package: str, *args: str) -> Process:
  48. return await run_cmd((
  49. pip_path,
  50. 'install',
  51. '--require-virtualenv',
  52. '-v',
  53. '--disable-pip-version-check',
  54. *args,
  55. quote(package)
  56. ))
  57. async def install_packages(
  58. pip_path: str,
  59. packages: Iterable[str],
  60. output: Union[None, str],
  61. *args: str
  62. ) -> list[Process]:
  63. added = set()
  64. tasks = []
  65. for package in packages:
  66. if package in added:
  67. continue
  68. added.add(package)
  69. tasks.append(install_package(pip_path, package, *args))
  70. result = await asyncio.gather(*tasks)
  71. if output:
  72. await write_requirements(output, pip_path)
  73. return result