manage.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. from __future__ import print_function
  17. import sys
  18. import os
  19. import subprocess
  20. import requests
  21. from flask import current_app
  22. from werkzeug.utils import import_string
  23. from sqlalchemy.exc import IntegrityError, OperationalError
  24. from flask_script import (Manager, Shell, Server, prompt, prompt_pass,
  25. prompt_bool)
  26. from flask_migrate import MigrateCommand, upgrade
  27. from flaskbb import create_app
  28. from flaskbb.extensions import db, plugin_manager
  29. from flaskbb.utils.populate import (create_test_data, create_welcome_forum,
  30. create_admin_user, create_default_groups,
  31. create_default_settings, insert_mass_data,
  32. update_settings_from_fixture)
  33. # Use the development configuration if available
  34. try:
  35. from flaskbb.configs.development import DevelopmentConfig as Config
  36. except ImportError:
  37. from flaskbb.configs.default import DefaultConfig as Config
  38. app = create_app(Config)
  39. manager = Manager(app)
  40. # Used to get the plugin translations
  41. PLUGINS_FOLDER = os.path.join(app.root_path, "plugins")
  42. # Run local server
  43. manager.add_command("runserver", Server("localhost", port=8080))
  44. # Migration commands
  45. manager.add_command('db', MigrateCommand)
  46. # Add interactive project shell
  47. def make_shell_context():
  48. return dict(app=current_app, db=db)
  49. manager.add_command("shell", Shell(make_context=make_shell_context))
  50. @manager.command
  51. def initdb():
  52. """Creates the database."""
  53. upgrade()
  54. @manager.command
  55. def dropdb():
  56. """Deletes the database."""
  57. db.drop_all()
  58. @manager.command
  59. def populate(dropdb=False, createdb=False):
  60. """Creates the database with some default data.
  61. To drop or create the databse use the '-d' or '-c' options.
  62. """
  63. if dropdb:
  64. print("Dropping database...")
  65. db.drop_all()
  66. if createdb:
  67. print("Creating database...")
  68. upgrade()
  69. app.logger.info("Creating test data...")
  70. create_test_data()
  71. @manager.option('-u', '--username', dest='username')
  72. @manager.option('-p', '--password', dest='password')
  73. @manager.option('-e', '--email', dest='email')
  74. def create_admin(username=None, password=None, email=None):
  75. """Creates the admin user."""
  76. if not (username and password and email):
  77. username = prompt("Username")
  78. email = prompt("A valid email address")
  79. password = prompt_pass("Password")
  80. create_admin_user(username=username, password=password, email=email)
  81. @manager.option('-u', '--username', dest='username')
  82. @manager.option('-p', '--password', dest='password')
  83. @manager.option('-e', '--email', dest='email')
  84. def install(username=None, password=None, email=None):
  85. """Installs FlaskBB with all necessary data."""
  86. print("Creating default data...")
  87. try:
  88. create_default_groups()
  89. create_default_settings()
  90. except IntegrityError:
  91. print("Couldn't create the default data because it already 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. print("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. print("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. print("Creating welcome forum...")
  116. create_welcome_forum()
  117. print("Compiling translations...")
  118. compile_translations()
  119. if prompt_bool("Do you want to use Emojis? (y/n)"):
  120. print("Downloading emojis. This can take a few minutes.")
  121. download_emoji()
  122. print("Congratulations! FlaskBB has been successfully installed")
  123. @manager.command
  124. def insertmassdata():
  125. """Warning: This can take a long time!.
  126. Creates 100 topics and each topic contains 100 posts.
  127. """
  128. insert_mass_data()
  129. @manager.option('-s', '--settings', dest="settings")
  130. @manager.option('-f', '--force', dest="force", default=False)
  131. def update(settings=None, force=False):
  132. """Updates the settings via a fixture. All fixtures have to be placed
  133. in the `fixture`.
  134. Usage: python manage.py update -s your_fixture
  135. """
  136. try:
  137. fixture = import_string(
  138. "flaskbb.fixtures.{}".format(settings)
  139. )
  140. fixture = fixture.fixture
  141. except ImportError:
  142. raise "{} fixture is not available".format(settings)
  143. overwrite_group = overwrite_setting = False
  144. if force:
  145. overwrite_group = overwrite_setting = True
  146. count = update_settings_from_fixture(
  147. fixture=fixture,
  148. overwrite_group=overwrite_group,
  149. overwrite_setting=overwrite_setting
  150. )
  151. print("{} groups and {} settings updated.".format(
  152. len(count.keys()), len(count.values()))
  153. )
  154. @manager.command
  155. def update_translations():
  156. """Updates all translations."""
  157. # update flaskbb translations
  158. translations_folder = os.path.join(app.root_path, "translations")
  159. source_file = os.path.join(translations_folder, "messages.pot")
  160. subprocess.call(["pybabel", "extract", "-F", "babel.cfg",
  161. "-k", "lazy_gettext", "-o", source_file, "."])
  162. subprocess.call(["pybabel", "update", "-i", source_file,
  163. "-d", translations_folder])
  164. # updates all plugin translations too
  165. for plugin in plugin_manager.all_plugins:
  166. update_plugin_translations(plugin)
  167. @manager.command
  168. def add_translations(translation):
  169. """Adds a new language to the translations."""
  170. translations_folder = os.path.join(app.root_path, "translations")
  171. source_file = os.path.join(translations_folder, "messages.pot")
  172. subprocess.call(["pybabel", "extract", "-F", "babel.cfg",
  173. "-k", "lazy_gettext", "-o", source_file, "."])
  174. subprocess.call(["pybabel", "init", "-i", source_file,
  175. "-d", translations_folder, "-l", translation])
  176. @manager.command
  177. def compile_translations():
  178. """Compiles all translations."""
  179. # compile flaskbb translations
  180. translations_folder = os.path.join(app.root_path, "translations")
  181. subprocess.call(["pybabel", "compile", "-d", translations_folder])
  182. # compile all plugin translations
  183. for plugin in plugin_manager.all_plugins:
  184. compile_plugin_translations(plugin)
  185. # Plugin translation commands
  186. @manager.command
  187. def add_plugin_translations(plugin, translation):
  188. """Adds a new language to the plugin translations. Expects the name
  189. of the plugin and the translations name like "en".
  190. """
  191. plugin_folder = os.path.join(PLUGINS_FOLDER, plugin)
  192. translations_folder = os.path.join(plugin_folder, "translations")
  193. source_file = os.path.join(translations_folder, "messages.pot")
  194. subprocess.call(["pybabel", "extract", "-F", "babel.cfg",
  195. "-k", "lazy_gettext", "-o", source_file,
  196. plugin_folder])
  197. subprocess.call(["pybabel", "init", "-i", source_file,
  198. "-d", translations_folder, "-l", translation])
  199. @manager.command
  200. def update_plugin_translations(plugin):
  201. """Updates the plugin translations. Expects the name of the plugin."""
  202. plugin_folder = os.path.join(PLUGINS_FOLDER, plugin)
  203. translations_folder = os.path.join(plugin_folder, "translations")
  204. source_file = os.path.join(translations_folder, "messages.pot")
  205. subprocess.call(["pybabel", "extract", "-F", "babel.cfg",
  206. "-k", "lazy_gettext", "-o", source_file,
  207. plugin_folder])
  208. subprocess.call(["pybabel", "update", "-i", source_file,
  209. "-d", translations_folder])
  210. @manager.command
  211. def compile_plugin_translations(plugin):
  212. """Compile the plugin translations. Expects the name of the plugin."""
  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. @manager.command
  217. def download_emoji():
  218. """Downloads emojis from emoji-cheat-sheet.com."""
  219. HOSTNAME = "https://api.github.com"
  220. REPO = "/repos/arvida/emoji-cheat-sheet.com/contents/public/graphics/emojis"
  221. FULL_URL = "{}{}".format(HOSTNAME, REPO)
  222. DOWNLOAD_PATH = os.path.join(app.static_folder, "emoji")
  223. response = requests.get(FULL_URL)
  224. cached_count = 0
  225. count = 0
  226. for image in response.json():
  227. if not os.path.exists(os.path.abspath(DOWNLOAD_PATH)):
  228. print("{} does not exist.".format(os.path.abspath(DOWNLOAD_PATH)))
  229. sys.exit(1)
  230. full_path = os.path.join(DOWNLOAD_PATH, image["name"])
  231. if not os.path.exists(full_path):
  232. count += 1
  233. f = open(full_path, 'wb')
  234. f.write(requests.get(image["download_url"]).content)
  235. f.close()
  236. if count == cached_count + 50:
  237. cached_count = count
  238. print("{} out of {} Emojis downloaded...".format(
  239. cached_count, len(response.json())))
  240. print("Finished downloading {} Emojis.".format(count))
  241. if __name__ == "__main__":
  242. manager.run()