Hey guys, In today’s blog we are going to Deploy a Flask app online using Pythonanywhere. The app we are going to deploy will be a Sketch Making Flask App that we created in the previous blog.
This is going to be a very interesting project because learning how to deploy an app online is a very important skill nowadays. So without any further due, let’s do it…
Check the video tutorial here – https://youtu.be/hsSs2qpLq9U
Snapshot of our Final app…
Let’s Deploy a Flask app online
Step 1 – Create an account on Pythonanywhere.
- When you create an account on Pythonanywhere and log in for the first time, your screen will look like this.
- Notice no apps under Web apps.
Step 2 – Create a Web App
- Click on the Web in the Header Menu.
- Click on Add a new web app.
- Click on Next.
- Select Flask on the Next Screen.
- Then Select the Python version you want to work in. I selected Python 3.9 & Flask 2.0.0.
- Here change flask_app.py to app.py (I will be uploading my Flask file with the name app.py, you can change it according to your file name) and click on Next.
Step 3 – Upload the required files.
- Now click on the Files section in the Header Menu.
- You will see a mysite folder there.
- This is the folder in which we need to place all our files.
- Upload the app.py file in mysite folder.
- Create an empty folder static. Now create one more empty folder called uploads in the static folder.
- Create empty folder templates.
- Upload home.html in the templates folder.
- Download home.html and app.py.
Step 4 – Let’s run the Flask app
- Now again go on the Web and hit the green Reload button.
- And now your website should be good to run online.
Step 5 – Let’s check our Deployed App online
- We can see that our website is running smoothly online.
- See the URL, it’s sharmaji270.pythonanywhere.com.
Final Results…
Source codes for your reference…
app.py
# Deploy a Flask app online import cv2 import os from werkzeug.utils import secure_filename from flask import Flask,request,render_template UPLOAD_FOLDER = 'mysite/static/uploads' ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg']) app = Flask(__name__) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.secret_key = "secret key" def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS def make_sketch(img): grayed = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) inverted = cv2.bitwise_not(grayed) blurred = cv2.GaussianBlur(inverted, (19, 19), sigmaX=0, sigmaY=0) final_result = cv2.divide(grayed, 255 - blurred, scale=256) return final_result @app.route('/') def home(): return render_template('home.html') @app.route('/sketch',methods=['POST']) def sketch(): file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) img = cv2.imread(UPLOAD_FOLDER+'/'+filename) sketch_img = make_sketch(img) sketch_img_name = filename.split('.')[0]+"_sketch.jpg" _ = cv2.imwrite(UPLOAD_FOLDER+'/'+sketch_img_name, sketch_img) return render_template('home.html',org_img_name=filename,sketch_img_name=sketch_img_name) if __name__ == '__main__': app.run(debug=True) # Deploy a Flask app online
home.html
<!doctype html> <html lang="en"> <style type='text/css'> body { font-family: sans-serif; margin-top: 40px; } .regform { width: 800px; background-color: rgb(0, 0, 0, 0.8); margin: auto; color: #FFFFFF; padding: 10px 0px 10px 0px; text-align: center; border-radius: 15px 15px 0px 0px; } .main-form { width: 800px; margin: auto; background-color: rgb(0, 0, 0, 0.7); padding-left: 50px; padding-right: 50px; padding-bottom: 20px; color: #FFFFFF; } img { max-height: 400px; max-width: 500px; height: auto; width: auto; } </style> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <title>Sketchy</title> </head> <body> <div class='regform mt-3'> <h1>Sketchy</h1> </div> <form action='/sketch' class='main-form' method="POST" enctype="multipart/form-data"> <div class='text-center'> <input type="file" id="file" name='file' style="margin-top:10px;margin-bottom:10px;"> <button type='submit' class='btn btn-outline-success'> Make Sketch </button> </div> </form> {% if sketch_img_name %} <div class="row" style="margin-top:10px;margin-bottom:10px;"> <div class="col text-center"> <h2>Original Image</h2><img src='../static/uploads/{{ org_img_name }}' style="display: block;margin-left: auto;margin-right: auto;"> </div> <div class="col text-center"> <h2>Sketch Image</h2><img src='../static/uploads/{{ sketch_img_name }}' style="display: block;margin-left: auto;margin-right: auto;"> </div> </div> {% endif %} </body> </html>
And this is how you Deploy a Flask app online…
Benefits of Deploying Flask Apps Online
Accessibility
Deploying a Flask app online ensures that users can access it from anywhere with an internet connection. Whether it’s a personal project or a business application, accessibility is key to reaching a broader audience.
Scalability
Online deployment allows Flask apps to scale seamlessly based on user demand. Whether the traffic spikes or decreases, cloud platforms can automatically adjust resources to ensure optimal performance.
Cost-effectiveness
Many cloud platforms offer free tiers or pay-as-you-go pricing models, making it cost-effective to deploy Flask apps online. Moreover, the scalability benefits help in managing resources efficiently, reducing overall costs.
Popular Platforms for Deploying Flask Apps
Heroku
Heroku is a cloud platform that simplifies the deployment process with its easy-to-use interface and seamless integration with Git. It supports various programming languages, including Python, and offers a free tier for hosting Flask apps.
PythonAnywhere
PythonAnywhere is another popular choice for deploying Flask apps, especially for beginners. It provides a web-based Python development environment with built-in support for Flask and allows users to deploy applications with a few clicks.
AWS Elastic Beanstalk
AWS Elastic Beanstalk is a fully managed service by Amazon Web Services (AWS) that automates the deployment, scaling, and management of web applications. It supports Flask and offers a scalable infrastructure to handle varying workloads.
Best Practices for Deploying Flask Apps
Using environment variables
Utilize environment variables to store sensitive information such as API keys and database credentials securely.
Ensuring security measures
Implement SSL/TLS encryption and secure authentication mechanisms to protect your Flask app from security threats.
Monitoring and logging
Set up monitoring tools and logging mechanisms to track the performance and health of your deployed Flask app.
Conclusion
Deploying a Flask app online is essential to make it accessible, scalable, and cost-effective. Whether you choose Heroku, PythonAnywhere, or AWS Elastic Beanstalk, following the step-by-step guides and best practices discussed in this article will help you deploy your Flask app with ease. So, take your Flask projects to the next level by making them available to users worldwide.
So this is all for this blog folks. Thanks for reading it and I hope you are taking something with you after reading this and till the next time …
FAQs on How to Deploy a Flask app online
Can I deploy multiple Flask apps on the same platform simultaneously?
Yes, most cloud platforms support deploying multiple applications within the same account, allowing you to manage them conveniently.
Is it necessary to use a cloud platform for deploying Flask apps online?
While using a cloud platform offers convenience and scalability, you can also deploy Flask apps on self-managed servers if preferred.
Are there any limitations to the free tiers offered by cloud platforms for hosting Flask apps?
Free tiers typically have resource limitations, such as limited storage, memory, and compute power. However, they are suitable for small-scale projects and experimentation.
Can I use Docker containers to deploy Flask apps online?
Yes, Docker containers provide a portable and consistent environment for deploying Flask apps across different platforms.
How can I monitor the performance of my deployed Flask app?
You can use monitoring tools like New Relic, Prometheus, or built-in platform metrics to monitor the performance metrics of your Flask app deployed online.
Read my previous post: Best way to Explore Data using Interactive EDA Reports in Python
Check out my other machine learning projects, deep learning projects, computer vision projects, NLP projects, and Flask projects at machinelearningprojects.net.