SECRET OF CSS

Run a QR Code Generator on Google Cloud Run


In this tutorial, we’ll build a QR Code generator in Python and deploy it to Cloud Run on the Google Cloud Platform where it will return QR Codes in response to HTTP requests.

1*XCVmOkmB3Z8Lj10VzIB8VQ

Cloud Run is a managed platform that lets you run containers directly on top of Google’s scalable infrastructure. A common use case is to have a container that responds to web requests, and Google allows you to use their run.app domain or you can use your own custom domain. In addition, there is a very generous free tier allowing up to 2 million requests per month at no cost.

In this tutorial, we’re going to build a web application that will take in a url parameter and return a QR Code png image. The application will be packaged using a Dockerfile and will be run on Cloud Run.

Solution Overview for QR Code Generator

The first step in this solution will be to code our QR Code Generator. For this we’re going to use an existing Python library qrcode.

In your project directory, create a file called main.py with the following contents. We shall discuss what this is doing afterwards.

import io
import os
from flask import Flask, request, send_file
import qrcode
application = Flask(__name__)def generate_qr(url):
qr = qrcode.QRCode(version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4)
qr.add_data(url)
qr.make(fit=True)
img = qr.make_image()
return img
@application.route("/")
def r_qrcode():
url = request.args.get('url', default='https://www.google.com')
img_buf = io.BytesIO()
img = generate_qr(url)
img.save(img_buf)
img_buf.seek(0)
return send_file(img_buf, mimetype='image/png')
# run the app.
if __name__ == "__main__":
application.run(debug=True,
host="0.0.0.0",
port=int(os.environ.get("PORT", 8080)))
Flask==2.1.2
gunicorn==20.1.0
qrcode[pil]==7.3.1

To test out the code locally, install all the dependencies with pip install -r requirements.txt and run the application with python main.py. You should be able to hit the endpoint at http://127.0.0.1:8080/ and see a QR Code.

QR Code for https://www.google.com

By default, this code will generate a QR Code for “https://www.google.com”. You can generate QR Codes for other sites by providing a url parameter, for example http://127.0.0.1:8080/?url=https://twitter.com for Twitter.

Now that it’s working, let’s talk about the code a little.

We’re using the qrcode library to generate a QR Code for a given url. This function will return the image (png format) as a byte sequence.

def generate_qr(url):
qr = qrcode.QRCode(version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4)
qr.add_data(url)
qr.make(fit=True)
img = qr.make_image()
return img

We then need to define our Flask route. We get the url parameter and call our generate_qr function. This is all managed in-memory — we don’t use local disk — so the image bytes get stored in a buffer and then returned using Flask’s inbuilt send_file method.

@application.route("/")
def r_qrcode():
url = request.args.get('url', default='https://www.google.com')
img_buf = io.BytesIO()
img = generate_qr(url)
img.save(img_buf)
img_buf.seek(0)
return send_file(img_buf, mimetype='image/png')

Now that we have completed our QR Code Generator solution, we need to package it as a container image and deploy it so that people can access it.

The first step is to generate a Dockerfile to build the container image. In the same directory as before, create the file with the following contents.

FROM python:3.10-slimENV PYTHONUNBUFFERED TrueENV APP_HOME /app
WORKDIR $APP_HOME
COPY . ./
RUN pip install --no-cache-dir -r requirements.txtCMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:application

You can build your image and deploy it to Cloud Run with a single command gcloud run deploy using the gcloud SDK. The first time you run this command you will be asked a series of questions, accept the defaults and answer Y to enable Artifact Registry. Once the job has completed, you will see the following output:

Done.                                                                                                                                                  
Service [python-flask-qrcode] revision [python-flask-qrcode-00002-zaz] has been deployed and is serving 100 percent of traffic.
Service URL: https://python-flask-qrcode-3ojizuvfpa-ue.a.run.app

That’s your url, so try it in the browser, and you should see the same results as you did in your local testing.

You can navigate to the Cloud Run Console to view logs, metrics, and revision history.





News Credit

%d bloggers like this: