__init__.py 2.2 KB

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