No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

69 líneas
2.5 KiB

  1. import os
  2. import argparse
  3. from dotenv import dotenv_values
  4. from db import create_tables, get_session
  5. from db.actions import create_user
  6. def create_secret(_args):
  7. """
  8. Creates a secret and stores it in a .env file in the current working directory
  9. Use `python main.py create-secret --help` for more options
  10. Args:
  11. _args: The parsed command line arguments
  12. """
  13. config = dotenv_values('.env')
  14. # No .env file exists or no secret key has been set
  15. if config is None or config.get('SECRET') is None:
  16. with open('.env', 'a') as f:
  17. f.write(f'SECRET={os.urandom(24).hex()}')
  18. print(f"Secret stored at {os.path.abspath('.env')}")
  19. else:
  20. print("A secret already exists. Use --overwrite to create a new secret.")
  21. if _args.overwrite:
  22. with open('.env', 'w') as f:
  23. for key, value in config.items():
  24. if key == 'SECRET':
  25. value = os.urandom(24).hex()
  26. f.write(f"{key}={value}")
  27. def run(_args):
  28. import uvicorn
  29. from app import app
  30. uvicorn.run(app,host="0.0.0.0", port=5050, reload=True)
  31. def create_admin(_args):
  32. session = next(get_session())
  33. create_user(args.username, args.password, session, is_admin=True)
  34. print("Admin created.")
  35. parser = argparse.ArgumentParser(description='CLI to setup our blogging API.')
  36. subparsers = parser.add_subparsers()
  37. secret_parser = subparsers.add_parser('create-secret', help="Writes a suitable secret key to a .env file in the current working directory.")
  38. secret_parser.add_argument('--overwrite', action='store_true', help="Overwrite the present secret value.")
  39. secret_parser.set_defaults(func=create_secret)
  40. db_parser = subparsers.add_parser('create-db', help="Creates the tables and the databses for the project")
  41. db_parser.set_defaults(func=create_tables)
  42. admin_parser = subparsers.add_parser('create-admin', help="Creates a admin user with the given password and username.")
  43. admin_parser.add_argument('username', help="Username of the admin.")
  44. admin_parser.add_argument('password', help="Password of the admin.")
  45. admin_parser.set_defaults(func=create_admin)
  46. start_parser = subparsers.add_parser('start', help="Starts the API")
  47. start_parser.set_defaults(func=run)
  48. if __name__ == '__main__':
  49. args = parser.parse_args()
  50. args.func(args) # Call the function with the given arguments, it is assumed that every parser sets the corresponding function
  51. #import uvicorn
  52. #from app import app
  53. #uvicorn.run(app,host="0.0.0.0", port=5050, reload=True)