Flask starter template for better structuring and fast programming.
Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions.
Unlike django this does not have starter pack and developers have to write each and everything to start with flask. This can get pretty much boring. Same for me.
It pushed me to make a flask starter pack to solve the problem. In usual manner flask app are developed as single file app. But as application gets bigger it starts to look clutterd. It gets very herd to manage all the configs, views, models etc from a single file. May be it doesn't make sense when project is small but when project gets expanded we realize that how importent is to scale the project. It enables the freedom of flask with scalability of django. like stuff made in heaven.
- Pre-configured to use
- Suitable for big applications.
- Full-Stack experience.
- Admin Dashboard with Flask-admin
- login or authentication with flask-login
- ORM features with FLASK-SQLAlchemy
- DB Migrations with Flask-Migrate
- Recommnded for small and mediam sized apps or for more control over code.
- For larger app please use frameworks like djnago/djnago-rest-framework. (from my own experience)
- install docker.
- run the following commands
to build and start development server
docker compose up --build
- Sync the code automatically on docker development container.
open a another terminal in the same location and run
docker compose watch
Now any change in code will reflect in your development server automatically.
git clone https://github.com/tirtharajsinha/Flask-starter.git
2. if youremove the .git folder. remember that .git folder is a hidden folder. you can do it either manually in the file explorer or from the comand line
For windows use-
rmdir /s .git
for linux
rm -r .git
git init
echo "# New flask App" > README.md
git add -A
git commit -m "good first commit"
git remote add origin [newGithubURL]
git push origin master
5. create a virtual environment and install requirements.(Recommended)
- if you want to download the repository | click here.
- Unzip it and start building your app.
- create a virtual environment and install requirements.(recommended)
virtualenv venv
./venv/Scripts/activate
pip install -r requirements.txt
deactivate
python manage.py init
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
From second time only
python manage.py runserver
If everything go accordingly and does not throw error you are mostly done.
Open Your web Browser and put http://127.0.0.1:5000
and press enter you should show see a welcome screen.
python manage.py --help
-
urls.py : Direct all the url requests to the assigned functions.
-
views.py : Contains all view functions, or view for short, that takes a web request and returns a web response.
-
app.py : Manage flask settings.
-
Model.py : Stores models. A model is a class that represents table or collection in our DB, and where every attribute of the class is a field of the table or collection.
-
Manage.py : It is a controller of app to perform configuere tasks like starting server, superuser creation, migrate database etc. Run
python manage.py --help
for more info. -
backup_tools.py : A tool to backup your database or port your data to one database to other database. you can backup form remote database to local sqlite file or vice versa. to use it correctly configuere it properly. Use it if know what you are doing. using it wrong can wipe your data completely or corrupt your files. Distribute it with caution cuz it may contains security access details of your database.
-
admin/config.py : Contains runtime config profiles.
-
admin/auth.py : Contains authentication and authorization rules for users like login, logout, isuser etc.
-
admin/adminconsole.py : Contains settings for admin dashboard. To see your model in the
/admin/
page register the model here. Follow the docs in the following file to know how to register a model.
Put your HTML files in templates and use it in views.
Put your static files like images,audio,css,js files in it to use it in html files. suppose you have css file named style.css
or img.jpg
. import it in html as
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<img src="{{ url_for('static', filename='img.jpg') }}">
if you are using oracle, postgresql, Mysql you must have DB URI Or by default we use SqLite.
Set up your database in admin/config.py
file and replace your URL with default one.
SQLALCHEMY_DATABASE_URI = "<YOUR-DATABASE-URI>"
Create model in models.py
suppose your database name is PROJECT then create a class called project and add all the attribute for more details follow Flask-SQLALchemy Docs.
After creating or altering anything in model.py you have to run
python manage.py makemigrations
python manage.py migrate
Now you have to register the model in admin/adminconsole.py
.
- Import your model
from models import project
- Register your model in
add_adminview
function in line before return statement.
admin.add_view(DBModelView(project, db.session))
As we are using Flask-sqlalchemy flask-sqlalchemy docs is the best page to refer.
from models import *
There is your database ready to use. Now to create some users:
newuser = User(username='admin', email='[email protected]')
db.session.add(newuser)
db.session.commit()
User.query.all()
>>> [<User u'admin'>, <User u'guest'>]
User.query.filter_by(username='admin').first()
>>> <User u'admin'>
ouruser = User.query.filter_by(username='admin').first()
ouruser.email="[email protected]"
db.session.commit()
ouruser2 = User.query.get(1)
ouruser2.username = 'New Name'
db.session.commit()
user = User.query.get(id)
db.session.delete(user)
db.session.commit()
# OR
# Without creating query
User.query.filter_by(id=123).delete()
db.session.commit()
allusers = db.engine.execute("select * from users")
Note : Don't ever put
db.create_all()
in your code. It may crash you app on deploy.
python manage.py createsuperuser
Put your views in views.py
file.
urls.py contains instruction how flask have to response on perticular request. Python functions in views.py take the web request from urls.py and give the web response to templates.
To register new url to your application and bind it with a view add a like like this in add_url
functions before return function.
app.add_url_rule('/<YOUR-PATH>', view_func=views.<YOUR-VIEW>,methods=['GET', 'POST'])
- Replace with the url path you want to bind your view.
- Replace with your view form views.py
Flask-Mail is configured through the standard Flask config API. These are the available options (each is explained later in the documentation):
- MAIL_SERVER : Name/IP address of the email server.
- MAIL_PORT : Port number of server used.
- MAIL_USE_TLS : Enable/disable Transport Security Layer encryption.
- MAIL_USE_SSL : Enable/disable Secure Sockets Layer encryption
- MAIL_DEBUG : Debug support. The default is Flask application’s debug status.
- MAIL_USERNAME : Username of the sender
- MAIL_PASSWORD : The password of the corresponding Username of the sender.
- MAIL_ASCII_ATTACHMENTS : If set to true, attached filenames converted to ASCII.
- MAIL_DEFAULT_SENDER : sets default sender
- MAIL_SUPPRESS_SEND : Sending suppressed if app.testing set to true
- MAIL_MAX_EMAILS : Sets maximum mails to be sent
Note : Not all of the configuration is to be set.
- Install Flask-Mail package using
pip install Flask-Mail
pip freeze > requirements.txt
- On
admin/config.py
put you mail server configuration.
MAIL_SERVER = "smtp-relay.brevo.com"
MAIL_PORT = 587
MAIL_USERNAME = "<YOUR-Mail-ID>"
MAIL_PASSWORD = "<YOUR-PASSWORD>"
MAIL_USE_TLS = False
MAIL_USE_SSL = False
- Enable mail service in
app.py
import mail as mailConfig
mail,app = mailConfig(app)
- Send mail from your view
from flask_mail import Mail, Message
from mail import mail
def send_mail():
msg = Message(
'<SUBJECT>',
sender ='[email protected]',
recipients = ['receiver’[email protected]']
)
msg.body = f'''Hello Flask message sent from Flask-Mail'''
mail.send(msg)
return 'Sent'
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead
As of Flask 2.2, the development server always shows this warning, it is not possible to disable it. The development server is not intended for use in production. It is not designed to be particularly efficient, stable, or secure. Use a production WSGI server instead. See the deployment docs from Flask for more information.
That warning is just a warning though, it's not an error preventing your app from running. If your app isn't working, there's something else wrong with your code.
That warning applies to the development server, not Flask itself. The Flask framework is appropriate for any type of application and deployment.
Most of the case it is not required still if you want here the step.
pip install waitress
In app.py
replace the __main__
section with this
if __name__ == "__main__":
from waitress import serve
serve(
app,
host=currentAppConfig.host,
port=currentAppConfig.port
)