manage.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. #!/usr/bin/env python
  2. """
  3. flaskbb.manage
  4. ~~~~~~~~~~~~~~~~~~~~
  5. This script provides some easy to use commands for
  6. creating the database with or without some sample content.
  7. You can also run the development server with it.
  8. Just type `python manage.py` to see the full list of commands.
  9. TODO: When Flask 1.0 is released, get rid of Flask-Script and use click.
  10. Then it's also possible to split the commands in "command groups"
  11. which would make the commands better seperated from each other
  12. and less confusing.
  13. :copyright: (c) 2014 by the FlaskBB Team.
  14. :license: BSD, see LICENSE for more details.
  15. """
  16. import sys
  17. import os
  18. import subprocess
  19. from flask import current_app
  20. from werkzeug.utils import import_string
  21. from sqlalchemy.exc import IntegrityError, OperationalError
  22. from flask_script import (Manager, Shell, Server, prompt, prompt_pass,
  23. prompt_bool)
  24. from flask_migrate import MigrateCommand, upgrade
  25. from flaskbb import create_app
  26. from flaskbb.extensions import db
  27. from flaskbb.utils.populate import (create_test_data, create_welcome_forum,
  28. create_admin_user, create_default_groups,
  29. create_default_settings, insert_mass_data,
  30. update_settings_from_fixture)
  31. # Use the development configuration if available
  32. try:
  33. from flaskbb.configs.development import DevelopmentConfig as Config
  34. except ImportError:
  35. from flaskbb.configs.default import DefaultConfig as Config
  36. app = create_app(Config)
  37. manager = Manager(app)
  38. # Used to get the plugin translations
  39. PLUGINS_FOLDER = os.path.join(app.root_path, "plugins")
  40. # Run local server
  41. manager.add_command("runserver", Server("localhost", port=8080))
  42. # Migration commands
  43. manager.add_command('db', MigrateCommand)
  44. # Add interactive project shell
  45. def make_shell_context():
  46. return dict(app=current_app, db=db)
  47. manager.add_command("shell", Shell(make_context=make_shell_context))
  48. @manager.command
  49. def initdb():
  50. """Creates the database."""
  51. upgrade()
  52. @manager.command
  53. def dropdb():
  54. """Deletes the database."""
  55. db.drop_all()
  56. @manager.command
  57. def populate(dropdb=False, createdb=False):
  58. """Creates the database with some default data.
  59. If you do not want to drop or create the db add
  60. '-c' (to not create the db) and '-d' (to not drop the db)
  61. """
  62. if not dropdb:
  63. app.logger.info("Dropping database...")
  64. db.drop_all()
  65. if not createdb:
  66. app.logger.info("Creating database...")
  67. upgrade()
  68. app.logger.info("Creating test data...")
  69. create_test_data()
  70. @manager.option('-u', '--username', dest='username')
  71. @manager.option('-p', '--password', dest='password')
  72. @manager.option('-e', '--email', dest='email')
  73. def create_admin(username=None, password=None, email=None):
  74. """Creates the admin user."""
  75. if not (username and password and email):
  76. username = prompt("Username")
  77. email = prompt("A valid email address")
  78. password = prompt_pass("Password")
  79. create_admin_user(username=username, password=password, email=email)
  80. @manager.option('-u', '--username', dest='username')
  81. @manager.option('-p', '--password', dest='password')
  82. @manager.option('-e', '--email', dest='email')
  83. def init(username=None, password=None, email=None):
  84. """Initializes FlaskBB with all necessary data."""
  85. app.logger.info("Creating default data...")
  86. try:
  87. create_default_groups()
  88. create_default_settings()
  89. except IntegrityError:
  90. app.logger.error("Couldn't create the default data because it already "
  91. "exist!")
  92. if prompt_bool("Found an existing database."
  93. "Do you want to recreate the database? (y/n)"):
  94. db.session.rollback()
  95. db.drop_all()
  96. upgrade()
  97. create_default_groups()
  98. create_default_settings()
  99. else:
  100. sys.exit(0)
  101. except OperationalError:
  102. app.logger.error("No database found.")
  103. if prompt_bool("Do you want to create the database now? (y/n)"):
  104. db.session.rollback()
  105. upgrade()
  106. create_default_groups()
  107. create_default_settings()
  108. else:
  109. sys.exit(0)
  110. app.logger.info("Creating admin user...")
  111. if username and password and email:
  112. create_admin_user(username=username, password=password, email=email)
  113. else:
  114. create_admin()
  115. app.logger.info("Creating welcome forum...")
  116. create_welcome_forum()
  117. app.logger.info("Congratulations! FlaskBB has been successfully installed")
  118. @manager.command
  119. def insertmassdata():
  120. """Warning: This can take a long time!.
  121. Creates 100 topics and each topic contains 100 posts.
  122. """
  123. insert_mass_data()
  124. @manager.option('-s', '--settings', dest="settings")
  125. @manager.option('-f', '--force', dest="force", default=False)
  126. def update(settings=None, force=False):
  127. """Updates the settings via a fixture. All fixtures have to be placed
  128. in the `fixture`.
  129. Usage: python manage.py update -s your_fixture
  130. """
  131. try:
  132. fixture = import_string(
  133. "flaskbb.fixtures.{}".format(settings)
  134. )
  135. fixture = fixture.fixture
  136. except ImportError:
  137. raise "{} fixture is not available".format(settings)
  138. if force:
  139. count = update_settings_from_fixture(fixture, overwrite_group=True,
  140. overwrite_setting=True)
  141. app.logger.info(
  142. "{} groups and {} settings forcefully updated."
  143. .format(count[0], count[1])
  144. )
  145. else:
  146. count = update_settings_from_fixture(fixture)
  147. app.logger.info(
  148. "{} groups and {} settings updated.".format(count[0], count[1])
  149. )
  150. @manager.command
  151. def update_translations():
  152. """Updates the translations."""
  153. translations_folder = os.path.join(app.root_path, "translations")
  154. source_file = os.path.join(translations_folder, "messages.pot")
  155. subprocess.call(["pybabel", "extract", "-F", "babel.cfg",
  156. "-k", "lazy_gettext", "-o", source_file, "."])
  157. subprocess.call(["pybabel", "update", "-i", source_file,
  158. "-d", translations_folder])
  159. @manager.command
  160. def add_translations(translation):
  161. """Adds a new language to the translations."""
  162. translations_folder = os.path.join(app.root_path, "translations")
  163. source_file = os.path.join(translations_folder, "messages.pot")
  164. subprocess.call(["pybabel", "extract", "-F", "babel.cfg",
  165. "-k", "lazy_gettext", "-o", source_file, "."])
  166. subprocess.call(["pybabel", "init", "-i", source_file,
  167. "-d", translations_folder, "-l", translation])
  168. @manager.command
  169. def compile_translations():
  170. """Compiles the translations."""
  171. translations_folder = os.path.join(app.root_path, "translations")
  172. subprocess.call(["pybabel", "compile", "-d", translations_folder])
  173. # Plugin translation commands
  174. @manager.command
  175. def add_plugin_translations(plugin, translation):
  176. """Adds a new language to the plugin translations. Expects the name
  177. of the plugin and the translations name like "en".
  178. """
  179. plugin_folder = os.path.join(PLUGINS_FOLDER, plugin)
  180. translations_folder = os.path.join(plugin_folder, "translations")
  181. subprocess.call(["pybabel", "extract", "-F", "babel.cfg",
  182. "-k", "lazy_gettext", "-o", "messages.pot",
  183. plugin_folder])
  184. subprocess.call(["pybabel", "init", "-i", "messages.pot",
  185. "-d", translations_folder, "-l", translation])
  186. os.unlink('messages.pot')
  187. @manager.command
  188. def update_plugin_translations(plugin):
  189. """Updates the plugin translations. Expects the name of the plugin."""
  190. plugin_folder = os.path.join(PLUGINS_FOLDER, plugin)
  191. translations_folder = os.path.join(plugin_folder, "translations")
  192. subprocess.call(["pybabel", "extract", "-F", "babel.cfg",
  193. "-k", "lazy_gettext", "-o", "messages.pot",
  194. plugin_folder])
  195. subprocess.call(["pybabel", "update", "-i", "messages.pot",
  196. "-d", translations_folder])
  197. os.unlink("messages.pot")
  198. @manager.command
  199. def compile_plugin_translations(plugin):
  200. """Compile the plugin translations. Expects the name of the plugin."""
  201. plugin_folder = os.path.join(PLUGINS_FOLDER, plugin)
  202. translations_folder = os.path.join(plugin_folder, "translations")
  203. subprocess.call(["pybabel", "compile", "-d", translations_folder])
  204. if __name__ == "__main__":
  205. manager.run()