manage.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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.option('-s', '--settings', dest="settings")
  57. @manager.option('-f', '--force', dest="force")
  58. def update(settings=None, force=False):
  59. """Updates the settings via a fixture. All fixtures have to be placed
  60. in the `fixture`.
  61. Usage: python manage.py update -s your_fixture
  62. """
  63. try:
  64. fixture = import_string(
  65. "flaskbb.fixtures.{}".format(settings)
  66. )
  67. fixture = fixture.fixture
  68. except ImportError:
  69. raise "{} fixture is not available".format(settings)
  70. if force:
  71. count = update_settings_from_fixture(fixture, overwrite_group=True,
  72. overwrite_setting=True)
  73. app.logger.info(
  74. "{} groups and {} settings forcefully updated."
  75. .format(count[0], count[1])
  76. )
  77. else:
  78. count = update_settings_from_fixture(fixture)
  79. app.logger.info(
  80. "{} groups and {} settings updated.".format(count[0], count[1])
  81. )
  82. @manager.command
  83. def createall(dropdb=False, createdb=False):
  84. """Creates the database with some testing content.
  85. If you do not want to drop or create the db add
  86. '-c' (to not create the db) and '-d' (to not drop the db)
  87. """
  88. if not dropdb:
  89. app.logger.info("Dropping database...")
  90. db.drop_all()
  91. if not createdb:
  92. app.logger.info("Creating database...")
  93. upgrade()
  94. app.logger.info("Creating test data...")
  95. create_test_data()
  96. @manager.option('-u', '--username', dest='username')
  97. @manager.option('-p', '--password', dest='password')
  98. @manager.option('-e', '--email', dest='email')
  99. def create_admin(username=None, password=None, email=None):
  100. """Creates the admin user"""
  101. if not (username and password and email):
  102. username = prompt("Username")
  103. email = prompt("A valid email address")
  104. password = prompt_pass("Password")
  105. create_admin_user(username=username, password=password, email=email)
  106. @manager.option('-u', '--username', dest='username')
  107. @manager.option('-p', '--password', dest='password')
  108. @manager.option('-e', '--email', dest='email')
  109. def initflaskbb(username=None, password=None, email=None):
  110. """Initializes FlaskBB with all necessary data"""
  111. app.logger.info("Creating default data...")
  112. try:
  113. create_default_groups()
  114. create_default_settings()
  115. except IntegrityError:
  116. app.logger.error("Couldn't create the default data because it already "
  117. "exist!")
  118. if prompt_bool("Do you want to recreate the database? (y/n)"):
  119. db.session.rollback()
  120. db.drop_all()
  121. upgrade()
  122. create_default_groups()
  123. create_default_settings()
  124. else:
  125. sys.exit(0)
  126. except OperationalError:
  127. app.logger.error("No database found.")
  128. if prompt_bool("Do you want to create the database now? (y/n)"):
  129. db.session.rollback()
  130. upgrade()
  131. create_default_groups()
  132. create_default_settings()
  133. else:
  134. sys.exit(0)
  135. app.logger.info("Creating admin user...")
  136. if username and password and email:
  137. create_admin_user(username=username, password=password, email=email)
  138. else:
  139. create_admin()
  140. app.logger.info("Creating welcome forum...")
  141. create_welcome_forum()
  142. app.logger.info("Congratulations! FlaskBB has been successfully installed")
  143. @manager.command
  144. def insertmassdata():
  145. """Warning: This can take a long time!.
  146. Creates 100 topics and each topic contains 100 posts.
  147. """
  148. insert_mass_data()
  149. @manager.command
  150. def update_translations():
  151. """
  152. Updates the translations
  153. """
  154. translations_folder = os.path.join(app.root_path, "translations")
  155. source_file = os.path.join(translations_folder, "messages.pot")
  156. subprocess.call(["pybabel", "extract", "-F", "babel.cfg",
  157. "-k", "lazy_gettext", "-o", source_file, "."])
  158. subprocess.call(["pybabel", "update", "-i", source_file,
  159. "-d", translations_folder])
  160. @manager.command
  161. def add_translations(translation):
  162. """
  163. Adds a new language to the translations
  164. """
  165. translations_folder = os.path.join(app.root_path, "translations")
  166. source_file = os.path.join(translations_folder, "messages.pot")
  167. subprocess.call(["pybabel", "extract", "-F", "babel.cfg",
  168. "-k", "lazy_gettext", "-o", source_file, "."])
  169. subprocess.call(["pybabel", "init", "-i", source_file,
  170. "-d", translations_folder, "-l", translation])
  171. @manager.command
  172. def compile_translations():
  173. """
  174. Compiles the translations.
  175. """
  176. translations_folder = os.path.join(app.root_path, "translations")
  177. subprocess.call(["pybabel", "compile", "-d", translations_folder])
  178. # Plugin translation commands
  179. @manager.command
  180. def add_plugin_translations(plugin, translation):
  181. """
  182. Adds a new language to the plugin translations
  183. Expects the name of the plugin and the translations name like "en"
  184. """
  185. plugin_folder = os.path.join(PLUGINS_FOLDER, plugin)
  186. translations_folder = os.path.join(plugin_folder, "translations")
  187. subprocess.call(["pybabel", "extract", "-F", "babel.cfg",
  188. "-k", "lazy_gettext", "-o", "messages.pot",
  189. plugin_folder])
  190. subprocess.call(["pybabel", "init", "-i", "messages.pot",
  191. "-d", translations_folder, "-l", translation])
  192. os.unlink('messages.pot')
  193. @manager.command
  194. def update_plugin_translations(plugin):
  195. """
  196. Updates the plugin translations
  197. Expects the name of the plugin.
  198. """
  199. plugin_folder = os.path.join(PLUGINS_FOLDER, plugin)
  200. translations_folder = os.path.join(plugin_folder, "translations")
  201. subprocess.call(["pybabel", "extract", "-F", "babel.cfg",
  202. "-k", "lazy_gettext", "-o", "messages.pot",
  203. plugin_folder])
  204. subprocess.call(["pybabel", "update", "-i", "messages.pot",
  205. "-d", translations_folder])
  206. os.unlink("messages.pot")
  207. @manager.command
  208. def compile_plugin_translations(plugin):
  209. """
  210. Compile the plugin translations.
  211. Expects the name of the plugin.
  212. """
  213. plugin_folder = os.path.join(PLUGINS_FOLDER, plugin)
  214. translations_folder = os.path.join(plugin_folder, "translations")
  215. subprocess.call(["pybabel", "compile", "-d", translations_folder])
  216. if __name__ == "__main__":
  217. manager.run()