manage.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. If you do not want to drop or create the db add
  62. '-c' (to not create the db) and '-d' (to not drop the db)
  63. """
  64. if not dropdb:
  65. print("Dropping database...")
  66. db.drop_all()
  67. if not createdb:
  68. print("Creating database...")
  69. upgrade()
  70. app.logger.info("Creating test data...")
  71. create_test_data()
  72. @manager.option('-u', '--username', dest='username')
  73. @manager.option('-p', '--password', dest='password')
  74. @manager.option('-e', '--email', dest='email')
  75. def create_admin(username=None, password=None, email=None):
  76. """Creates the admin user."""
  77. if not (username and password and email):
  78. username = prompt("Username")
  79. email = prompt("A valid email address")
  80. password = prompt_pass("Password")
  81. create_admin_user(username=username, password=password, email=email)
  82. @manager.option('-u', '--username', dest='username')
  83. @manager.option('-p', '--password', dest='password')
  84. @manager.option('-e', '--email', dest='email')
  85. def install(username=None, password=None, email=None):
  86. """Installs FlaskBB with all necessary data."""
  87. print("Creating default data...")
  88. try:
  89. create_default_groups()
  90. create_default_settings()
  91. except IntegrityError:
  92. print("Couldn't create the default data because it already exist!")
  93. if prompt_bool("Found an existing database."
  94. "Do you want to recreate the database? (y/n)"):
  95. db.session.rollback()
  96. db.drop_all()
  97. upgrade()
  98. create_default_groups()
  99. create_default_settings()
  100. else:
  101. sys.exit(0)
  102. except OperationalError:
  103. print("No database found.")
  104. if prompt_bool("Do you want to create the database now? (y/n)"):
  105. db.session.rollback()
  106. upgrade()
  107. create_default_groups()
  108. create_default_settings()
  109. else:
  110. sys.exit(0)
  111. print("Creating admin user...")
  112. if username and password and email:
  113. create_admin_user(username=username, password=password, email=email)
  114. else:
  115. create_admin()
  116. print("Creating welcome forum...")
  117. create_welcome_forum()
  118. print("Compiling translations...")
  119. compile_translations()
  120. if prompt_bool("Do you want to use Emojis? (y/n)"):
  121. print("Downloading emojis. This can take a few minutes.")
  122. download_emoji()
  123. print("Congratulations! FlaskBB has been successfully installed")
  124. @manager.command
  125. def insertmassdata():
  126. """Warning: This can take a long time!.
  127. Creates 100 topics and each topic contains 100 posts.
  128. """
  129. insert_mass_data()
  130. @manager.option('-s', '--settings', dest="settings")
  131. @manager.option('-f', '--force', dest="force", default=False)
  132. def update(settings=None, force=False):
  133. """Updates the settings via a fixture. All fixtures have to be placed
  134. in the `fixture`.
  135. Usage: python manage.py update -s your_fixture
  136. """
  137. try:
  138. fixture = import_string(
  139. "flaskbb.fixtures.{}".format(settings)
  140. )
  141. fixture = fixture.fixture
  142. except ImportError:
  143. raise "{} fixture is not available".format(settings)
  144. if force:
  145. count = update_settings_from_fixture(fixture, overwrite_group=True,
  146. overwrite_setting=True)
  147. print("{} groups and {} settings forcefully updated.".format(
  148. count[0], count[1]))
  149. else:
  150. count = update_settings_from_fixture(fixture)
  151. print("{} groups and {} settings updated.".format(count[0], count[1]))
  152. @manager.command
  153. def update_translations():
  154. """Updates all translations."""
  155. # update flaskbb translations
  156. translations_folder = os.path.join(app.root_path, "translations")
  157. source_file = os.path.join(translations_folder, "messages.pot")
  158. subprocess.call(["pybabel", "extract", "-F", "babel.cfg",
  159. "-k", "lazy_gettext", "-o", source_file, "."])
  160. subprocess.call(["pybabel", "update", "-i", source_file,
  161. "-d", translations_folder])
  162. # updates all plugin translations too
  163. for plugin in plugin_manager.all_plugins:
  164. update_plugin_translations(plugin)
  165. @manager.command
  166. def add_translations(translation):
  167. """Adds a new language to the translations."""
  168. translations_folder = os.path.join(app.root_path, "translations")
  169. source_file = os.path.join(translations_folder, "messages.pot")
  170. subprocess.call(["pybabel", "extract", "-F", "babel.cfg",
  171. "-k", "lazy_gettext", "-o", source_file, "."])
  172. subprocess.call(["pybabel", "init", "-i", source_file,
  173. "-d", translations_folder, "-l", translation])
  174. @manager.command
  175. def compile_translations():
  176. """Compiles all translations."""
  177. # compile flaskbb translations
  178. translations_folder = os.path.join(app.root_path, "translations")
  179. subprocess.call(["pybabel", "compile", "-d", translations_folder])
  180. # compile all plugin translations
  181. for plugin in plugin_manager.all_plugins:
  182. compile_plugin_translations(plugin)
  183. # Plugin translation commands
  184. @manager.command
  185. def add_plugin_translations(plugin, translation):
  186. """Adds a new language to the plugin translations. Expects the name
  187. of the plugin and the translations name like "en".
  188. """
  189. plugin_folder = os.path.join(PLUGINS_FOLDER, plugin)
  190. translations_folder = os.path.join(plugin_folder, "translations")
  191. source_file = os.path.join(translations_folder, "messages.pot")
  192. subprocess.call(["pybabel", "extract", "-F", "babel.cfg",
  193. "-k", "lazy_gettext", "-o", source_file,
  194. plugin_folder])
  195. subprocess.call(["pybabel", "init", "-i", source_file,
  196. "-d", translations_folder, "-l", translation])
  197. @manager.command
  198. def update_plugin_translations(plugin):
  199. """Updates the plugin translations. Expects the name of the plugin."""
  200. plugin_folder = os.path.join(PLUGINS_FOLDER, plugin)
  201. translations_folder = os.path.join(plugin_folder, "translations")
  202. source_file = os.path.join(translations_folder, "messages.pot")
  203. subprocess.call(["pybabel", "extract", "-F", "babel.cfg",
  204. "-k", "lazy_gettext", "-o", source_file,
  205. plugin_folder])
  206. subprocess.call(["pybabel", "update", "-i", source_file,
  207. "-d", translations_folder])
  208. @manager.command
  209. def compile_plugin_translations(plugin):
  210. """Compile the plugin translations. Expects the name of the plugin."""
  211. plugin_folder = os.path.join(PLUGINS_FOLDER, plugin)
  212. translations_folder = os.path.join(plugin_folder, "translations")
  213. subprocess.call(["pybabel", "compile", "-d", translations_folder])
  214. @manager.command
  215. def download_emoji():
  216. """Downloads emojis from emoji-cheat-sheet.com."""
  217. HOSTNAME = "https://api.github.com"
  218. REPO = "/repos/arvida/emoji-cheat-sheet.com/contents/public/graphics/emojis"
  219. FULL_URL = "{}{}".format(HOSTNAME, REPO)
  220. DOWNLOAD_PATH = os.path.join(app.static_folder, "emoji")
  221. response = requests.get(FULL_URL)
  222. cached_count = 0
  223. count = 0
  224. for image in response.json():
  225. if not os.path.exists(os.path.abspath(DOWNLOAD_PATH)):
  226. print("{} does not exist.".format(os.path.abspath(DOWNLOAD_PATH)))
  227. sys.exit(1)
  228. full_path = os.path.join(DOWNLOAD_PATH, image["name"])
  229. if not os.path.exists(full_path):
  230. count += 1
  231. f = open(full_path, 'wb')
  232. f.write(requests.get(image["download_url"]).content)
  233. f.close()
  234. if count == cached_count+50:
  235. cached_count = count
  236. print("{} out of {} Emojis downloaded...".format(
  237. cached_count, len(response.json())))
  238. print("Finished downloading {} Emojis.".format(count))
  239. if __name__ == "__main__":
  240. manager.run()