1. Install Flask
pip install flask
2. Create a New Flask App
from flask import Flask
app = Flask(__name__)
3. Run the Flask App
if __name__ == '__main__':
app.run()
4. Define a Route
@app.route('/')
def home():
return 'Hello, World!'
5. Use a Template
from flask import render_template
@app.route('/')
def home():
return render_template('home.html')
6. Handle Form Data
from flask import request
@app.route('/submit', methods=['POST'])
def submit():
name = request.form['name']
return 'Hello, ' + name + '!'
7. Use a Database
from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
@app.route('/users')
def users():
users = User.query.all()
return render_template('users.html', users=users)
8. Use Flask-WTF for Forms
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
class MyForm(FlaskForm):
name = StringField('Name')
submit = SubmitField('Submit')
@app.route('/myform', methods=['GET', 'POST'])
def myform():
form = MyForm()
if form.validate_on_submit():
return 'Hello, ' + form.name.data + '!'
return render_template('myform.html', form=form)
9. Use Flask-Login for Authentication
from flask_login import LoginManager, UserMixin, login_user, logout_user
app.config['SECRET_KEY'] = 'secret_key'
login_manager = LoginManager(app)
class User(UserMixin):
def __init__(self, id):
self.id = id
@login_manager.user_loader
def load_user(user_id):
return User(user_id)
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = User(username)
login_user(user)
return 'Logged in!'
return render_template('login.html')
10. Use Flask-Mail for Email
from flask_mail import Mail, Message
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'your_email@gmail.com'
app.config['MAIL_PASSWORD'] = 'your_password'
mail = Mail(app)
@app.route('/send_email')
def send_email():
msg = Message('Hello', sender='your_email@gmail.com', recipients=['recipient_email@gmail.com'])
msg.body = 'This is a test email'
mail.send(msg)
return 'Email sent!'
11. Use Flask-RESTful for APIs
from flask_restful import Api, Resource
api = Api(app)
class HelloWorld(Resource):
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
12. Use Flask-Cors for CORS
from flask_cors import CORS
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
13. Use Flask-DebugToolbar for Debugging
from flask_debugtoolbar import DebugToolbarExtension
app.config['DEBUG_TB_ENABLED'] = True
toolbar = DebugToolbarExtension(app)
14. Use Flask-Profiler for Profiling
from flask_profiler import Profiler
profiler = Profiler(app)
15. Use Flask-Testing for Testing
from flask_testing import TestCase
class MyTest(TestCase):
def create_app(self):
app.config['TESTING'] = True
return app
def test_home(self):
response = self.client.get('/')
self.assertEqual(response.data, b'Hello, World!')
16. Use Flask-SocketIO for WebSockets
from flask_socketio import SocketIO
socketio = SocketIO(app)
@socketio.on('message')
def handle_message(msg):
print('Message: ' + msg)
17. Use Flask-Session for Server-Side Sessions
from flask_session import Session
app.config['SESSION_TYPE'] = 'filesystem'
Session(app)
18. Use Flask-Admin for Admin Interface
from flask_admin import Admin
admin = Admin(app)
admin.add_view(ModelView(User, db.session))
19. Use Flask-Migrate for Database Migrations
from flask_migrate import Migrate
migrate = Migrate(app, db)
20. Use Flask-Cache for Caching
from flask_caching import Cache
cache = Cache(app)
21. Use Flask-Babel for Internationalization
from flask_babel import Babel
babel = Babel(app)
22. Use Flask-RESTPlus for REST APIs
from flask_restplus import Api
api = Api(app)
23. Use Flask-Uploads for File Uploads
from flask_uploads import UploadSet, configure_uploads
photos = UploadSet('photos', ('jpg', 'png'))
configure_uploads(app, photos)
24. Use Flask-Admin for CRUD Operations
from flask_admin.contrib.sqla import ModelView
admin.add_view(ModelView(User, db.session))
25. Use Flask-RESTful for Resource-Based APIs
class UserResource(Resource):
def get(self, user_id):
user = User.query.get(user_id)
return {'name': user.name}
api.add_resource(UserResource, '/user/<int:user_id>')
26. Use Flask-Login for User Sessions
@app.route('/logout')
def logout():
logout_user()
return 'Logged out!'
27. Use Flask-WTF for CSRF Protection
@app.route('/form', methods=['GET', 'POST'])
def form():
form = MyForm()
if form.validate_on_submit():
return 'Form submitted!'
return render_template('form.html', form=form)
28. Use Flask-SQLAlchemy for ORM
db.create_all()
29. Use Flask-RESTful for Error Handling
@app.errorhandler(404)
def not_found(error):
return {'message': 'Not found'}, 404
30. Use Flask-RESTful for Input Validation
from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('name', type=str, required=True)
args = parser.parse_args()
31. Use Flask-RESTful for Pagination
@app.route('/users')
def get_users():
page = request.args.get('page', 1, type=int)
users = User.query.paginate(page, per_page=10)
return {'users': [user.name for user in users.items]}
32. Use Flask-RESTful for Filtering
@app.route('/users')
def get_filtered_users():
name = request.args.get('name')
users = User.query.filter(User.name.contains(name)).all()
return {'users': [user.name for user in users]}
33. Use Flask-RESTful for Sorting
@app.route('/users')
def get_sorted_users():
users = User.query.order_by(User.name).all()
return {'users': [user.name for user in users]}
34. Use Flask-RESTful for Batch Processing
@app.route('/users', methods=['POST'])
def create_users():
data = request.get_json()
for user_data in data['users']:
user = User(name=user_data['name'])
db.session.add(user)
db.session.commit()
return {'message': 'Users created!'}
35. Use Flask-RESTful for Rate Limiting
from flask_limiter import Limiter
limiter = Limiter(app, key_func=get_remote_address)
@app.route('/limited')
@limiter.limit("5 per minute")
def limited():
return 'This route is rate limited!'
36. Use Flask-RESTful for Caching
@app.route('/cached')
@cache.cached(timeout=60)
def cached():
return 'This response is cached for 60 seconds!'
37. Use Flask-RESTful for API Versioning
api_v1 = Api(app, version='1.0', title='API V1')
api_v2 = Api(app, version='2.0', title='API V2')
38. Use Flask-RESTful for Custom Error Messages
@app.errorhandler(400)
def bad_request(error):
return {'message': 'Bad request'}, 400
39. Use Flask-RESTful for Custom Response Formats
@app.route('/json')
def json_response():
return jsonify({'message': 'This is a JSON response!'})
40. Use Flask-RESTful for XML Responses
@app.route('/xml')
def xml_response():
return Response('<message>This is an XML response!</message>', mimetype='application/xml')
41. Use Flask-RESTful for File Downloads
@app.route('/download')
def download_file():
return send_file('path/to/file.txt', as_attachment=True)
42. Use Flask-RESTful for File Uploads
@app.route('/upload', methods=['POST'])
def upload_file():
file = request.files['file']
file.save('uploads/' + file.filename)
return 'File uploaded!'
43. Use Flask-RESTful for Background Tasks
from flask import jsonify
from threading import Thread
def background_task():
# Perform some background task
pass
@app.route('/start_task')
def start_task():
thread = Thread(target=background_task)
thread.start()
return jsonify({'message': 'Task started!'})
44. Use Flask-RESTful for WebSocket Communication
@socketio.on('connect')
def handle_connect():
print('Client connected!')
@socketio.on('disconnect')
def handle_disconnect():
print('Client disconnected!')
45. Use Flask-RESTful for JWT Authentication
from flask_jwt_extended import JWTManager, create_access_token
app.config['JWT_SECRET_KEY'] = 'your_jwt_secret_key'
jwt = JWTManager(app)
@app.route('/login', methods=['POST'])
def login():
username = request.json['username']
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token)
46. Use Flask-RESTful for OAuth2 Authentication
from flask_oauthlib.provider import OAuth2Provider
oauth = OAuth2Provider(app)
47. Use Flask-RESTful for API Documentation
from flask_restplus import Api
api = Api(app, doc='/docs')
48. Use Flask-RESTful for API Testing
from flask_testing import TestCase
class MyTest(TestCase):
def create_app(self):
app.config['TESTING'] = True
return app
def test_api(self):
response = self.client.get('/api/resource')
self.assertEqual(response.status_code, 200)
49. Use Flask-RESTful for API Rate Limiting
from flask_limiter import Limiter
limiter = Limiter(app)
@app.route('/rate_limited')
@limiter.limit("10 per hour")
def rate_limited():
return 'This route is rate limited!'
50. Use Flask-RESTful for API Versioning
api_v1 = Api(app, version='1.0', title='API V1')
api_v2 = Api(app, version='2.0', title='API V2')
51. Use Flask-RESTful for API Pagination
@app.route('/items')
def get_items():
page = request.args.get('page', 1, type=int)
items = Item.query.paginate(page, per_page=10)
return {'items': [item.name for item in items.items]}
52. Use Flask-RESTful for API Filtering
@app.route('/items')
def get_filtered_items():
name = request.args.get('name')
items = Item.query.filter(Item.name.contains(name)).all()
return {'items': [item.name for item in items]}
53. Use Flask-RESTful for API Sorting
@app.route('/items')
def get_sorted_items():
items = Item.query.order_by(Item.name).all()
return {'items': [item.name for item in items]}
54. Use Flask-RESTful for API Batch Processing
@app.route('/items', methods=['POST'])
def create_items():
data = request.get_json()
for item_data in data['items']:
item = Item(name=item_data['name'])
db.session.add(item)
db.session.commit()
return {'message': 'Items created!'}
55. Use Flask-RESTful for API Error Handling
@app.errorhandler(404)
def not_found(error):
return {'message': 'Not found'}, 404
56. Use Flask-RESTful for API Input Validation
from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('name', type=str, required=True)
args = parser.parse_args()
57. Use Flask-RESTful for API Response Formatting
@app.route('/json')
def json_response():
return jsonify({'message': 'This is a JSON response!'})
58. Use Flask-RESTful for XML Responses
@app.route('/xml')
def xml_response():
return Response('<message>This is an XML response!</message>', mimetype='application/xml')
59. Use Flask-RESTful for File Downloads
@app.route('/download')
def download_file():
return send_file('path/to/file.txt', as_attachment=True)
60. Use Flask-RESTful for File Uploads
@app.route('/upload', methods=['POST'])
def upload_file():
file = request.files['file']
file.save('uploads/' + file.filename)
return 'File uploaded!'
61. Use Flask-RESTful for Background Tasks
from threading import Thread
def background_task():
# Perform some background task
pass
@app.route('/start_task')
def start_task():
thread = Thread(target=background_task)
thread.start()
return jsonify({'message': 'Task started!'})
62. Use Flask-RESTful for WebSocket Communication
@socketio.on('connect')
def handle_connect():
print('Client connected!')
@socketio.on('disconnect')
def handle_disconnect():
print('Client disconnected!')
63. Use Flask-RESTful for JWT Authentication
from flask_jwt_extended import JWTManager, create_access_token
app.config['JWT_SECRET_KEY'] = 'your_jwt_secret_key'
jwt = JWTManager(app)
@app.route('/login', methods=['POST'])
def login():
username = request.json['username']
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token)
64. Use Flask-RESTful for OAuth2 Authentication
from flask_oauthlib.provider import OAuth2Provider
oauth = OAuth2Provider(app)
65. Use Flask-RESTful for API Documentation
from flask_restplus import Api
api = Api(app, doc='/docs')
66. Use Flask-RESTful for API Testing
from flask_testing import TestCase
class MyTest(TestCase):
def create_app(self):
app.config['TESTING'] = True
return app
def test_api(self):
response = self.client.get('/api/resource')
self.assertEqual(response.status_code, 200)
67. Use Flask-RESTful for API Rate Limiting
from flask_limiter import Limiter
limiter = Limiter(app)
@app.route('/rate_limited')
@limiter.limit("10 per hour")
def rate_limited():
return 'This route is rate limited!'
68. Use Flask-RESTful for API Versioning
api_v1 = Api(app, version='1.0', title='API V1')
api_v2 = Api(app, version='2.0', title='API V2')
69. Use Flask-RESTful for API Pagination
@app.route('/items')
def get_items():
page = request.args.get('page', 1, type=int)
items = Item.query.paginate(page, per_page=10)
return {'items': [item.name for item in items.items]}
70. Use Flask-RESTful for API Filtering
@app.route('/items')
def get_filtered_items():
name = request.args.get('name')
items = Item.query.filter(Item.name.contains(name)).all()
return {'items': [item.name for item in items]}
71. Use Flask-RESTful for API Sorting
@app.route('/items')
def get_sorted_items():
items = Item.query.order_by(Item.name).all()
return {'items': [item.name for item in items]}
72. Use Flask-RESTful for API Batch Processing
@app.route('/items', methods=['POST'])
def create_items():
data = request.get_json()
for item_data in data['items']:
item = Item(name=item_data['name'])
db.session.add(item)
db.session.commit()
return {'message': 'Items created!'}
73. Use Flask-RESTful for API Error Handling
@app.errorhandler(404)
def not_found(error):
return {'message': 'Not found'}, 404
74. Use Flask-RESTful for API Input Validation
from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('name', type=str, required=True)
args = parser.parse_args()
75. Use Flask-RESTful for API Response Formatting
@app.route('/json')
def json_response():
return jsonify({'message': 'This is a JSON response!'})
76. Use Flask-RESTful for XML Responses
@app.route('/xml')
def xml_response():
return Response('<message>This is an XML response!</message>', mimetype='application/xml')
77. Use Flask-RESTful for File Downloads
@app.route('/download')
def download_file():
return send_file('path/to/file.txt', as_attachment=True)
78. Use Flask-RESTful for File Uploads
@app.route('/upload', methods=['POST'])
def upload_file():
file = request.files['file']
file.save('uploads/' + file.filename)
return 'File uploaded!'
79. Use Flask-RESTful for Background Tasks
from threading import Thread
def background_task():
# Perform some background task
pass
@app.route('/start_task')
def start_task():
thread = Thread(target=background_task)
thread.start()
return jsonify({'message': 'Task started!'})
80. Use Flask-RESTful for WebSocket Communication
@socketio.on('connect')
def handle_connect():
print('Client connected!')
@socketio.on('disconnect')
def handle_disconnect():
print('Client disconnected!')
81. Use Flask-RESTful for JWT Authentication
from flask_jwt_extended import JWTManager, create_access_token
app.config['JWT_SECRET_KEY'] = 'your_jwt_secret_key'
jwt = JWTManager(app)
@app.route('/login', methods=['POST'])
def login():
username = request.json['username']
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token)
82. Use Flask-RESTful for OAuth2 Authentication
from flask_oauthlib.provider import OAuth2Provider
oauth = OAuth2Provider(app)
83. Use Flask-RESTful for API Documentation
from flask_restplus import Api
api = Api(app, doc='/docs')
84. Use Flask-RESTful for API Testing
from flask_testing import TestCase
class MyTest(TestCase):
def create_app(self):
app.config['TESTING'] = True
return app
def test_api(self):
response = self.client.get('/api/resource')
self.assertEqual(response.status_code, 200)
85. Use Flask-RESTful for API Rate Limiting
from flask_limiter import Limiter
limiter = Limiter(app)
@app.route('/rate_limited')
@limiter.limit("10 per hour")
def rate_limited():
return 'This route is rate limited!'
86. Use Flask-RESTful for API Versioning
api_v1 = Api(app, version='1.0', title='API V1')
api_v2 = Api(app, version='2.0', title='API V2')
87. Use Flask-RESTful for API Pagination
@app.route('/items')
def get_items():
page = request.args.get('page', 1, type=int)
items = Item.query.paginate(page, per_page=10)
return {'items': [item.name for item in items.items]}
88. Use Flask-RESTful for API Filtering
@app.route('/items')
def get_filtered_items():
name = request.args.get('name')
items = Item.query.filter(Item.name.contains(name)).all()
return {'items': [item.name for item in items]}
89. Use Flask-RESTful for API Sorting
@app.route('/items')
def get_sorted_items():
items = Item.query.order_by(Item.name).all()
return {'items': [item.name for item in items]}
90. Use Flask-RESTful for API Batch Processing
@app.route('/items', methods=['POST'])
def create_items():
data = request.get_json()
for item_data in data['items']:
item = Item(name=item_data['name'])
db.session.add(item)
db.session.commit()
return {'message': 'Items created!'}
91. Use Flask-RESTful for API Error Handling
@app.errorhandler(404)
def not_found(error):
return {'message': 'Not found'}, 404
92. Use Flask-RESTful for API Input Validation
from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('name', type=str, required=True)
args = parser.parse_args()
93. Use Flask-RESTful for API Response Formatting
@app.route('/json')
def json_response():
return jsonify({'message': 'This is a JSON response!'})
94. Use Flask-RESTful for XML Responses
@app.route('/xml')
def xml_response():
return Response('<message>This is an XML response!</message>', mimetype='application/xml')
95. Use Flask-RESTful for File Downloads
@app.route('/download')
def download_file():
return send_file('path/to/file.txt', as_attachment=True)
96. Use Flask-RESTful for File Uploads
@app.route('/upload', methods=['POST'])
def upload_file():
file = request.files['file']
file.save('uploads/' + file.filename)
return 'File uploaded!'
97. Use Flask-RESTful for Background Tasks
from threading import Thread
def background_task():
# Perform some background task
pass
@app.route('/start_task')
def start_task():
thread = Thread(target=background_task)
thread.start()
return jsonify({'message': 'Task started!'})
98. Use Flask-RESTful for WebSocket Communication
@socketio.on('connect')
def handle_connect():
print('Client connected!')
@socketio.on('disconnect')
def handle_disconnect():
print('Client disconnected!')
99. Use Flask-RESTful for JWT Authentication
from flask_jwt_extended import JWTManager, create_access_token
app.config['JWT_SECRET_KEY'] = 'your_jwt_secret_key'
jwt = JWTManager(app)
@app.route('/login', methods=['POST'])
def login():
username = request.json['username']
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token)
100. Use Flask-RESTful for OAuth2 Authentication
from flask_oauthlib.provider import OAuth2Provider
oauth = OAuth2Provider(app)