Table of contents
1.
Introduction📑
2.
Basic Configuration🧊
2.1.
Test💡
3.
Cohort Analysis📈
3.1.
HTML
3.2.
Python
3.3.
Python
3.4.
HTML           
4.
Frequently Asked Questions
4.1.
What is Bottle API?
4.2.
What are Flask and Django?
4.3.
Which is better suited, a bottle or a flask?
4.4.
Define Falcon API.
4.5.
What does a JSON in Python mean?
5.
Conclusion
Last Updated: Mar 27, 2024
Medium

Developing with Bottle Framework - Part 2

Author Ishita mishra
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction📑

This article in the Developing with Bottle Framework series will focus on HTML forms and GET and POST queries. It'll also demonstrate how to use the plot.ly API to access data. Additionally, you'll learn how to make a fantastic graph displaying cohort analysis research findings.

Developing with Bottle Framework.

Also, did you miss the Developing with Bottle Framework- Part 1? If yes, then worry not! Check it out here. Additionally, Bottle version 0.12.3 and Plotly version 1.2.6 are used in this tutorial.

Basic Configuration🧊

Download this Gist from Part 1 first, then execute it by running the following command:

$bash bottle.sh

 

Thus, a basic project structure will be produced:

├── app.py
├── requirements.txt
└── testenv

 

Start the virtualenv  in Bottle Framework:

$ cd bottle
$ source testenv/bin/activate

 

Install the necessary components:

$ pip install -r requirements.txt

 

To generate a new API key, go to this, register a new account, sign in, and then:

API Key


API Key
Copy the key and Set up plot.ly:

$ pip intall plotly== 1.2.6

 

The code in app.py will now be updated:

import os
from bottle import run, template, get, post, request
import plotly.plotly as py
from plotly.graph_objs import *

# add your username and API key
py.sign_in("Ninja", "BllXKIYQan1dvZQOX3e0")

@get('/plot')
def form():
    return '''<h2>Graph via Plot.ly</h2>
              <form method="POST" action="/plot">
                Name: <input name="mobile1" type="text" />
                Age: <input name="cost1" type="text" /><br/>
                Name: <input name="mobilr2" type="text" />
                Age: <input name="cost2" type="text" /><br/>
                Name: <input name="mobile3" type="text" />
                Age: <input name="cost3" type="text" /><br/>
                <input type="submit" />
              </form>'''

@post('/plot')
def submit():
    # grab data from form
    name1 = request.forms.get('mobile1')
    age1 = request.forms.get('cost1')
    name2 = request.forms.get('mobile2')
    age2 = request.forms.get('cost2')
    name3 = request.forms.get('mobile3')
    age3 = request.forms.get('cost3')
    data = Data([
        Bar(
            x=[mobile1, mobile2, mobile3],
            y=[cost1, cost2, cost3]
        )
    ])

# make API call
    response = py.plot(data, filename='bar')
    if response:
        return template('''
            <h1>HIIII!</h1>
            <div>
               here is your graph: <a href="{{response}}"</a>{{response}}
            </div>
            ''',
            response=response
        )
if __name__ == '__main__':
    port = int(os.environ.get('PORT', 8080))
    run(host='0.0.0.0', port=port, debug=True)

 

What is happening here?👀

⭐The first function, form(), generates an HTML form to collect the information required to produce a basic bar graph.

⭐The second function, submit(), takes the inputs from the form, assigns them to variables, and then invokes the plot.ly API, providing the data and our login information, to create a new chart. Make sure to use your credentials to replace my username and API key. Don't use mine. It won't function.

Test💡

Run your program locally, type http://localhost:8080/plot into your browser, and then run app.py in Python.

List the mobile brands and their prices. After pressing submit, you should see a congratulations message with a URL if everything went correctly. To view your graph, click here.

Python Graph Plot

Cohort Analysis📈

Cohort Analysis

Let's now examine a more challenging case to make a graph for the following cohort analysis statistics in Bottle Framework:

Cohort Analysis Table.

We'll extend the same app, app.py, but create a new file: Open app.py, then “Save As” cohort.py.

Please upgrade to the Simple Template Engine first so we may customize our templates with styles and Javascript libraries. Create a new directory called "views" and a new file called template.tpl. This code should be added to that file:

HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>{{ Python Graph }}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">  
    <style>
      body {
        padding: 60px 0px;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <h1>Graph via Plot.ly</h1>
      <form role="form" method="post" action="/plot">
        <table>
            <td>
              <h3>2019</h3>
              <div class="form-group" "col-md-2">
                <input type="number" name="y01" class="form-control" placeholder="Cohort 0">
                <input type="number" name="y02" class="form-control" placeholder="Cohort 1">
                <input type="number" name="y03" class="form-control" placeholder="Cohort 2">
                <input type="number" name="y04" class="form-control" placeholder="Cohort 3">
              </div>
            </td>
            <td>
              <h3>2020</h3>
              <div class="form-group" "col-md-2">
                <input type="number" name="y11" class="form-control" placeholder="Cohort 0">
                <input type="number" name="y12" class="form-control" placeholder="Cohort 1">
                <input type="number" name="y13" class="form-control" placeholder="Cohort 2">
                <input type="number" name="y44" class="form-control" placeholder="Cohort 3">
              </div>
            </td>
            <td>
              <h3>2021</h3>
              <div class="form-group" "col-md-2">
                <input type="number" name="y21" class="form-control" placeholder="Cohort 0">
                <input type="number" name="y22" class="form-control" placeholder="Cohort 1">
                <input type="number" name="y23" class="form-control" placeholder="Cohort 2">
                <input type="number" name="y24" class="form-control" placeholder="Cohort 3">
              </div>
            </td>
            <td>
              <h3>2022</h3>
              <div class="form-group" "col-md-2">
                <input type="number" name="y31" class="form-control" placeholder="Cohort 0">
                <input type="number" name="y32" class="form-control" placeholder="Cohort 1">
                <input type="number" name="y33" class="form-control" placeholder="Cohort 2">
                <input type="number" name="y34" class="form-control" placeholder="Cohort 3">
              </div>
            </td>
          </tr>
        </table>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
    </div>
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
  </body>
</html>

 

This appears to be an HTML file, as you can probably guess. The distinction is that we may now use the syntax python variable to pass Python variables to the file.

Add your Plot.ly username and API key to a data.json file in Bottle Framework. The sample file is accessible here.

When we make the API connection, we'll utilize the credentials from the JSON. To access the information, add the following code to cohort.py.

Python

import os
from bottle import run, template, get, post, request

import plotly.plotly as py
from plotly.graph_objs import *

import json

# grab username and key from config/data file
with open('data.json') as config_file:
    config_data = json.load(config_file)
username = config_data["user"]
key = config_data["key"]

py.sign_in(username, key)
You can also try this code with Online Python Compiler
Run Code

 

We are no longer required to reveal our key to the entire cosmos. Just be careful not to put it under version control.

The functionalities will then be updated:

Python

import os
from bottle import run, template, get, post, request

import plotly.plotly as py
from plotly.graph_objs import *

import json

# grab username and key from config/data file
with open('data.json') as config_file:
    config_data = json.load(config_file)
username = config_data["user"]
key = config_data["key"]

py.sign_in(username, key)

@get('/plot')
def form():
    return template('template', title='Plot.ly Graph')

@post('/plot')
def submit():
    # grab data from form
    y01 = request.forms.get('y01')
    y02 = request.forms.get('y02')
    y03 = request.forms.get('y03')
    y04 = request.forms.get('y04')
    y11 = request.forms.get('y11')
    y12 = request.forms.get('y12')
    y13 = request.forms.get('y13')
    y14 = request.forms.get('y14')
    y21 = request.forms.get('y21')
    y22 = request.forms.get('y22')
    y23 = request.forms.get('y23')
    y24 = request.forms.get('y24')
    y31 = request.forms.get('y31')
    y32 = request.forms.get('y32')
    y33 = request.forms.get('y33')
    y34 = request.forms.get('y34')

    trace1 = Scatter(
        x=[1, 2, 3, 4],
        y=[y01, y02, y03, y04]
    )
    trace2 = Scatter(
        x=[1, 2, 3, 4],
        y=[y11, y12, y13, y14]
    )
    trace3 = Scatter(
        x=[1, 2, 3, 4],
        y=[y21, y22, y23, y24]
    )
    trace4 = Scatter(
        x=[1, 2, 3, 4],
        y=[y31, y32, y33, y34]
    )
    data = Data([trace1, trace2, trace3, trace4])

    # api call
    plot_url = py.plot(data, filename='basic-line')
    return template('template2', title='Plot.ly Graph', plot_url=str(plot_url))

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 8080))
    run(host='0.0.0.0', port=port, debug=True)
You can also try this code with Online Python Compiler
Run Code

 

The return statement is visible. Along with any variables, we're sending in the template name. Let's build the new template, which will be called template2.tpl in Bottle Framework:

HTML           

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>{{ Python Graph }}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
    <style>
      body {
        padding: 60px 0px;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <h1>Graph via Plot.ly</h1>
      <br>
      <a href="/plot"><button class="btn btn-default">Back</button></a>
      <br><br>
      <iframe id="igraph" src={{plot_url}} width="900" height="450" seamless="seamless" scrolling="no"></iframe>
    </div>
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
  </body>
</html>

 

We may update the form and display the accurate information or chart with the updated changes due to the iframe. To display the graph, we do not need to navigate away from the current page.

Run it. Increase the form's value and then send it. You should see the following in your graph made using the Bottle Framework:

Cohort Analysis Chart

Frequently Asked Questions

What is Bottle API?

The Bottle Framework is a Python WSGI micro web framework that is quick, easy, and lightweight.

What are Flask and Django?

Django, a full-stack web framework, offers applications that are ready to use with its batteries-included approach. Flask is a simple framework with many built-in functionalities, none of which require third-party libraries.

Which is better suited, a bottle or a flask?

Flask supports many features and offers helpful assistance through online forums or tutorials. The Bottle Framework is best for projects that must be completed rapidly.

Define Falcon API.

Falcon is a lightning-quick, simplistic Python web API framework for creating reliable app backends and microservices.

What does a JSON in Python mean?

A standardized format called JavaScript Object Notation (JSON) is frequently used to transmit data as text across a network.

Conclusion

In this blog, we have extensively discussed how to plot a graph and how to study cohort analysis using Bottle Framework in Python. Now go ahead, try to plot a similar chart, and see for yourself how it works!

Be Curious Image

Explore our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, interview bundle, follow guided paths for placement preparations, and much more. Also, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs to help other ninjas grow!

Happy Learning, ninjas!!

Thankyou Image.
Live masterclass