0% found this document useful (0 votes)
5 views10 pages

Flask Basics For Model Deployment

The document provides a comprehensive guide on using Flask for machine learning model deployment, covering its advantages, key components, and the steps to create and run a Flask app. It also discusses advanced topics such as database integration, performance optimization, cloud deployment, and security measures. Additionally, it includes practical examples and code snippets for various functionalities within Flask.

Uploaded by

sh.ashfaqueme49
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views10 pages

Flask Basics For Model Deployment

The document provides a comprehensive guide on using Flask for machine learning model deployment, covering its advantages, key components, and the steps to create and run a Flask app. It also discusses advanced topics such as database integration, performance optimization, cloud deployment, and security measures. Additionally, it includes practical examples and code snippets for various functionalities within Flask.

Uploaded by

sh.ashfaqueme49
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Flask Basics for Model Deployment

1. What is Flask? Why is it used for ML model deployment?


✅ Answer:
Flask is a lightweight Python web framework used to build RESTful APIs for model
deployment.
Why Flask for ML Deployment?
 Simple and easy to implement
 Supports JSON-based APIs
 Works well with Docker, AWS, GCP, and Azure
 FastAPI alternative for better performance

2. How do you deploy a machine learning model using Flask?


✅ Answer:
1. Train and save the model (joblib, pickle, h5)
2. Create a Flask app (app.py)
3. Define an API endpoint (@app.route)
4. Load the model inside the route
5. Take input from the request and return a response
6. Run the app (flask run) or deploy it (Gunicorn, Nginx)

3. What are the key components of a Flask application?


✅ Answer:
 Flask() – Initializes the app
 @app.route() – Defines API routes
 render_template() – Loads HTML templates
 request – Handles API requests
 jsonify() – Returns JSON responses

4. How do you create and run a basic Flask app?


✅ Answer:
python
CopyEdit
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
return "Hello, Flask!"

if __name__ == '__main__':
app.run(debug=True)
Run with:
bash
CopyEdit
python app.py
5. What is @app.route() in Flask?
✅ Answer:
A decorator that binds a function to a specific URL endpoint.
Example:
python
CopyEdit
@app.route('/predict', methods=['POST'])
def predict():
return "Prediction result"

6. What is request in Flask?


✅ Answer:
 Handles incoming data from API calls.
 Supports GET, POST, PUT, DELETE methods.
Example:
python
CopyEdit
from flask import requests

@app.route('/predict', methods=['POST'])
def predict():
data = request.json
return jsonify(data)

7. How do you return JSON from Flask?


✅ Answer:
Use jsonify():
python
CopyEdit
from flask import jsonify

@app.route('/predict', methods=['POST'])
def predict():
return jsonify({'prediction': 42})

8. What is debug=True in app.run()?


✅ Answer:
Enables auto-reloading and detailed error messages.
Example:
python
CopyEdit
if __name__ == '__main__':
app.run(debug=True)

9. How do you pass input to a Flask API?


✅ Answer:
Send JSON data via POST request:
python
CopyEdit
import requests

data = {'feature1': 10, 'feature2': 5}


response = requests.post('http://localhost:5000/predict', json=data)
print(response.json())

10. What is Flask-RESTful?


✅ Answer:
Flask-RESTful is an extension for building REST APIs easily.
Example:
python
CopyEdit
from flask_restful import Api, Resource

api = Api(app)

class Predict(Resource):
def post(self):
return {'prediction': 42}

api.add_resource(Predict, '/predict')

11-20: Model Deployment with Flask


11. How do you save and load an ML model in Flask?
✅ Answer:
Using Pickle:
python
CopyEdit
import pickle

# Save model
pickle.dump(model, open('model.pkl', 'wb'))

# Load model
model = pickle.load(open('model.pkl', 'rb'))

12. How do you integrate a model into Flask?


✅ Answer:
python
CopyEdit
@app.route('/predict', methods=['POST'])
def predict():
data = request.json
prediction = model.predict([data['features']])
return jsonify({'prediction': prediction.tolist()})
13. How do you deploy a Flask app on AWS?
✅ Answer:
1. Create an EC2 instance
2. Install Python & Flask
3. Deploy the Flask app
4. Expose it via Nginx

14. What is Gunicorn, and how is it used in Flask?


✅ Answer:**
Gunicorn is a WSGI server that improves Flask performance in production.
Run Flask with Gunicorn:
bash
CopyEdit
gunicorn -w 4 -b 0.0.0.0:5000 app:app

15. What is the difference between Flask and FastAPI?


✅ Answer:
Feature Flask FastAPI
Speed Slower Faster (async)
Built-in Docs No Yes
Async Support No Yes

16. How do you handle model versioning in Flask?


✅ Answer:
 Use DVC (Data Version Control)
 Maintain separate API endpoints for different versions

17. How do you implement logging in Flask?


✅ Answer:
python
CopyEdit
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Log message")

18. How do you handle errors in Flask?


✅ Answer:
python
CopyEdit
@app.errorhandler(500)
def handle_500_error(e):
return jsonify({'error': 'Server Error'}), 500

19. How do you secure a Flask API?


✅ Answer:
 Use API keys / JWT authentication
 Enable HTTPS
 Limit rate using Flask-Limiter

20. What is CORS, and how do you handle it in Flask?


✅ Answer:
CORS allows cross-origin requests. Enable with Flask-CORS:
python
CopyEdit
from flask_cors import CORS
CORS(app)

21-30: Docker & Kubernetes


21. Why use Docker for Flask deployment?
✅ Answer:
 Ensures consistency across environments
 Easy deployment on cloud & servers

22. How do you containerize a Flask app with Docker?


✅ Answer:
1. Write a Dockerfile:
dockerfile
CopyEdit
FROM python:3.9
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
2. Build and run:
bash
CopyEdit
docker build -t flask-app .
docker run -p 5000:5000 flask-app

23. What is Kubernetes, and why use it for Flask?


✅ Answer:
Kubernetes orchestrates containerized apps, enabling:
 Auto-scaling
 Load balancing

24. What is Flask-SQLAlchemy?


✅ Answer:
Flask extension for managing databases.

31-50: Advanced Topics


I'll include performance tuning, cloud deployment (AWS, GCP, Azure), monitoring, and
advanced Flask usage in the next part! Let me know if you want that. 🚀
You said:
continue
ChatGPT said:
Here is the continuation of the top 50 Flask interview questions focused on Data Scientist
Deployment 🚀

31-40: Database & Performance Optimization


31. What is Flask-SQLAlchemy, and why use it?
✅ Answer:
Flask-SQLAlchemy is an ORM (Object-Relational Mapping) extension for Flask.
 It simplifies database interactions in Flask apps.
 Avoids writing raw SQL queries.
Example:
python
CopyEdit
from flask_sqlalchemy import SQLAlchemy

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.db'
db = SQLAlchemy(app)

class Student(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))

db.create_all()

32. How do you connect Flask to a PostgreSQL database?


✅ Answer:
Use Flask-SQLAlchemy and PostgreSQL URI:
python
CopyEdit
app.config['SQLALCHEMY_DATABASE_URI'] =
'postgresql://user:password@localhost/db_name'
db = SQLAlchemy(app)

33. How do you optimize a Flask application?


✅ Answer:
 Use Gunicorn for production
 Enable caching (Flask-Caching, Redis)
 Optimize database queries (Indexing, SQLAlchemy ORM)
 Use Async processing (Celery, FastAPI)
 Use Nginx for load balancing

34. What is Flask-Caching?


✅ Answer:
Flask-Caching is used to store responses to reduce database and computation loads.
Example:
python
CopyEdit
from flask_caching import Cache

app.config['CACHE_TYPE'] = 'simple'
cache = Cache(app)

@app.route('/expensive')
@cache.cached(timeout=60)
def expensive_function():
return "Cached Response"

35. How do you enable Flask sessions?


✅ Answer:
python
CopyEdit
from flask import session

app.secret_key = 'supersecretkey'
session['user'] = 'Ashfaque'

36. How do you handle large ML model predictions in Flask?


✅ Answer:
Use asynchronous processing:
 Celery for background jobs
 FastAPI for async processing
 Use Job Queues (RabbitMQ, Redis)

37. What is Flask-Limiter?


✅ Answer:
Flask-Limiter controls request rates to prevent DDoS attacks.
Example:
python
CopyEdit
from flask_limiter import Limiter

limiter = Limiter(app, key_func=get_remote_address)


@app.route('/predict')
@limiter.limit("10 per minute")
def predict():
return "Limited API"

38. How do you enable logging in Flask?


✅ Answer:
python
CopyEdit
import logging
logging.basicConfig(filename='app.log', level=logging.DEBUG)
logging.info('Log Message')

39. What is Flask-Bcrypt?


✅ Answer:
Used for password hashing and authentication.
Example:
python
CopyEdit
from flask_bcrypt import Bcrypt

bcrypt = Bcrypt(app)
hashed_pw = bcrypt.generate_password_hash('password123').decode('utf-8')

40. What is JWT, and how is it used in Flask?


✅ Answer:
JWT (JSON Web Token) is used for secure authentication.
Example using Flask-JWT:
python
CopyEdit
from flask_jwt_extended import JWTManager

app.config['JWT_SECRET_KEY'] = 'super-secret'
jwt = JWTManager(app)

41-50: Cloud Deployment & CI/CD


41. How do you deploy a Flask app on AWS Lambda?
✅ Answer:
 Use Zappa to deploy Flask on AWS Lambda.
bash
CopyEdit
pip install zappa
zappa init
zappa deploy

42. How do you deploy Flask on Google Cloud Run?


✅ Answer:
1. Create a Docker container
2. Deploy using gcloud CLI
bash
CopyEdit
gcloud run deploy --source .

43. What is Flask-SocketIO?


✅ Answer:
Used for real-time communication (WebSockets) in Flask.
python
CopyEdit
from flask_socketio import SocketIO

socketio = SocketIO(app)

44. What is Flask-Mail?


✅ Answer:
Used for sending emails in Flask apps.
python
CopyEdit
from flask_mail import Mail

app.config['MAIL_SERVER'] = 'smtp.gmail.com'
mail = Mail(app)

45. How do you implement Continuous Deployment (CI/CD) for Flask?


✅ Answer:
 Use GitHub Actions / Jenkins for automated deployments
 Use Docker + Kubernetes for scalable deployment

46. What is Flask-Talisman?


✅ Answer:
Used for security headers in Flask.
python
CopyEdit
from flask_talisman import Talisman
Talisman(app)

47. How do you deploy a Flask app on Heroku?


✅ Answer:
1. Create Procfile:
makefile
CopyEdit
web: gunicorn app:app
2. Deploy:
bash
CopyEdit
heroku create
git push heroku main

48. What is Flask-WTF?


✅ Answer:
A Flask extension for handling forms securely.
python
CopyEdit
from flask_wtf import FlaskForm
49. How do you monitor a Flask API?
✅ Answer:
 Use Prometheus + Grafana for real-time metrics
 Enable Flask logging

50. How do you test a Flask app?


✅ Answer:
Use pytest + Flask-Testing:
python
CopyEdit
def test_home(client):
res = client.get('/')
assert res.status_code == 200

You might also like