I am working on a flask application which I need to create different types of user roles using a superuser. What is the best way to create a superuser? Some of ways that I am thinking is:
Create a custom command and execute the command in production.
import click
from flask import Flask
app = Flask(__name__)
@app.cli.command("create-superuser")
@click.argument("name")
def create_superuser(name):
...
Create a function and execute before first request.
@app.before_first_request
def init_db():
db.create_all()
insert_superuser()
Or just sql insert a superuser in the database.
If I am doing this wrong or this is a bad practice to do in production please tell me. I am still new to this.
By the way, I'm sorry but you tagged your question flask_restful
, and I really think everyone should use flask_restplus
(being now flask_restx
, forked due to change of maintainers).
I could change the tags, but I want to leave you the choice of doing it
This is what pleases you the most. There is no best way. It depends of your use-case. However, I dislike the 2nd method (before_first_request).
If you want to put this task in the hand of a person, you can use this. People will come to someone that will add them or not on the admin side.
You can use the @app.before_request()
decorator so that the action is performed each and every time, but do not set the database each and everytime you light up the app. Use a database, and it leads us to the 3rd one.
Superuser in database (password hashed with sha256).
Usually, if the system is in production, you don't want to mess with the admin too much.
There is another way : The JWT token.