How to write and deploy a basic python application using Duet AI on Google Cloud Shell Editor a step-by-step guide

ยท

7 min read

Ever wanted to create your own Python application but didn't know where to start? Look no further! In this guide, we'll explore how to harness the power of Duet AI and Google Cloud Shell Editor to craft a simple yet functional Python application. We will be building a simple todo list application using Python's Flask framework.

With the recent evolution in AI tools that can help developers with code suggestions, we will learn how Duet AI can be used to create and deploy a python application to Google Cloud. Whether you're a seasoned developer or just starting out, this guide has got you covered on how you can leverage AI to enhance your productivity.

Getting started with Google Cloud Shell Editor

The easiest way to start a Cloud Shell session and begin using Cloud Shell Editor is to directly launch a Cloud Shell Editor session with ide.cloud.google.com.

You can also access the Cloud Shell terminal by clicking Activate Cloud Shell in the Google Cloud Console,

Then click on Open Editor to start the Cloud Shell Editor

Enabling Duet AI

From the side panel of the Cloud Shell Editor, click Duet AI, then Select Duet AI Project where Cloud AI Companion API is enabled.

You can now start interacting with Duet AI ๐ŸŽ‰

Building Python API with Duet AI

Project Structure

Lets see if Duet AI can help us get started with the python project structure with the following prompt,

How do I initialise a python project using pipenv?

Duet AI has presented us with exactly what we need, here is the response with a few minor changes (like python version) to accomodate our project,

# Install pipenv to manage the virtual environment
pip install pipenv

# Create a directory for the project
mkdir python-api
cd python-api

# Initialize python environment
pipenv --python 3.9

# Install flask 
pipenv install flask Flask-SQLAlchemy

Let's initialize the pipenv project and install required python package. This process will generate a Pipfile, containing the packages and their respective versions, and a Pipfile.lock file, which ensures that packages are locked to the currently installed version

Flask API

Now that our Python project is initialized, let's explore how Duet AI can assist us in building a Flask API. We'll develop a todo list application where users can perform CRUD (create, read, update, delete) operations. This serves as our guiding prompt,

Create a python flask api for a todo list. Users should be able to perform CRUD (create, read, update and delete) operations.

Impressive! We have a Todo model with API routes for CRUD operations. We also have a temporary local sqlite database that Flask will connect to using SQLAlchemy toolkit.

The suggestion looks promising at a first glance, create a new module main.py and paste the code.

Building the UI

Now that we have built the API with the help of Duet AI, lets see if we can get some help around the UI where users can visually interact with the API. A simple prompt for this task,

Create a index.html for the todo app

Next, we need to integrate this newly created html file into our python application. Duet AI to the rescue,

How do I integrate this html file with the todo app

This is great, it has suggested moving index.html to templates directory which is the standard flask project file structure. Next suggestion is to add db.create_all() which will create our database tables and app.run() which will run the flask development server.

Validate AI Generated Code

We should always be validating code generated by AI. It seems Duet AI made a mistake and also missed out a few things in its example.

Duet AI suggested adding db.create_all() to the __main__ call but we need to run the code beforehand so the SQL database tables get created. Add a context manager before we call the module so it runs beforehand,

with app.app_context():
    db.create_all()

We also need to import render_template to the app.py module,

from flask import Flask, request, jsonify, render_template

Finally, we need to add a root URL which calls a function to render the html template,

@app.route('/')
def index():
    return render_template('index.html')

This is what main.py looks like after the changes,

Running the API

We have come a long way; starting with an empty code editor to leveraging the power of Duet AI and building a python Flask API from scratch.

Run the application to see it working in action. Run FLASK_APP=main.pypipenv run flask run (alternatively, pipenv shell then FLASK_APP=main.pyflask run) to start the Flask development server,

Navigate to http://127.0.0.1:5000 and voila, we can see the application running,

Lets create a Todo item,

Great, we have created our first todo item which is also displayed in the homepage. The UI is not very intuitive and its also missing ability to update and delete todo items but it proves that our solution works.

Invoking the API directly

Ask Duet AI how to create a todo item via the API using a curl command,

It suggested the command below to create a todo item,

curl -X POST -H "Content-Type: application/json" -d '{"title": "Buy milk", "description": "Need milk for breakfast"}' http://localhost:5000/todos

And to fetch all todo items,

curl -X GET -H "Content-Type: application/json" http://localhost:5000/todos

which returns all todo items,

[{"description":"Need milk for breakfast","id":1,"title":"Buy milk"}]

Deploying to Cloud Run

Cloud Run is a managed container service offering from Google Cloud that scales automatically based on demand. We deploy our application packaged as a docker container which contains all our source files and required packages.

We need to generate a requirements.txt file for cloud run, the packages will be installed alongside our application when the docker image is built. Lets use this prompt to ask Duet AI, whats the command to generate a requirements.txt file using pipenv

Using Google Cloud CLI, we will not even have to create a docker image ourselves. The gcloud run deploy command will copy all our source files, install packages and build a docker image, push the docker image to Artifact Registry and finally deploy the application to Google Cloud Run. Let's ask Duet AI how to deploy our python Flask API application,

whats the gcloud run deploy command to deploy this application to cloud run

Amazing, lets see if that works,

The application has successfully been deployed to Google Cloud Run, enter the provided application URL https://todo-app-y6r6yntwia-uc.a.run.app in your web browser,

We can also see application logs by navigating to cloud run console and selecting logs,

Lets also ask Duet AI how we can delete application resources at the end,

how would you delete this cloud run application and any associated docker images in artifact registry

Pretty accurate, these commands suggested by Duet AI are correct and will delete the cloud run service and the docker image respectively.

More ways to leverage Duet AI

Code Suggestion

We can easily request code suggestions from Duet AI by simply describing what we need in a comment. Take this example: if we wanted to implement a GET route to fetch a todo by title instead of ID, Duet AI offers code suggestion to do exactly that!

Explaining Code

Duet AI also does a great job explaining code which can be very beneficial when navigating through new or a large codebase or if you would like help in understanding a functionality better.

To get Duet AI to explain code, highlight the portion you would like explained, and click on the bulb icon (Show Code Actions) that appears,

Then click on Duet AI: Explain this,

Sure enough, we get a detailed breakdown of the get_todo function,

Writing tests

Wouldn't it be exciting to write more code and less tests? Can we get Duet AI to help write unit tests for our code? Lets ask!

Highlight a function to generate tests for, then click on Duet AI: Generate unit tests,

The tests themselves look functional but the test_client created during test setUp seems to be an unknown function. The test client would need to mock the database client in this scenario.

Conclusion

From initializing our Python project structure to building a Flask API for a todo list application, Duet AI provided valuable assistance every step of the way. Its ability to explain/generate code snippets tailored to our specific needs significantly expedited the development process, demonstrating how AI can enhance productivity for developers.

So why not give Duet AI a shot? It's like having a coding buddy who's always there to help you think while you focus on what you do best โ€“ coding with confidence!

As we continue to explore the frontiers of AI-driven development, the possibilities for creating impactful and transformative software solutions are boundless. Happy learning, sharing and growing!

ย