A Simple Flask Application



How To Build A Flask Ajax Template

We'll need to create some directories and files first. Here's a nice tree.

├── run.py
├── static
│   ├── css
│   │   └── styles.css
│   └── js
│       └── scripts.js
└── templates
    └── index.html

run.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    title = 'WELCOME TO FLASK'
    subtitle = 'HAVE A NICE DAY'
    description = 'SOME COOL LETTERS & THINGS HERE'
    footer = 'FOOTER TEXT'
    return render_template('index.html', title=title, subtitle=subtitle, description=description, footer=footer)

@app.route('/do_something', methods=['POST'])
def do_something():
    msg = 'DOING PYTHON STUFF'
    print(msg)
    return msg

if __name__ == '__main__':
    app.run(debug=True)

static/css/styles.css

.footer {
  padding-top: 6rem !important;
  padding-bottom: 6rem !important;
}

static/js/scripts.js

$(function() {

  $('#go').click(function() {
    $('#go').addClass('is-loading');
    $.ajax({
      url: '/do_something',
      type: 'POST',
      success: function(response) {
        $('#results').html(response);
        $('#go').removeClass('is-loading');
      }
    });
  });

});

templates/index.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Flask Tutorial</title>
  <link rel=stylesheet type=text/css href="{{ url_for('static', filename='css/styles.css') }}">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css">
</head>

<body>

  <section class="hero is-primary is-medium is-bold">
    <div class="hero-body">
      <div class="container">
        <h1 class="title">{{title}}</h1>
        <h2 class="subtitle">{{subtitle}}</h2>
        <p>{{description}}</p>
      </div>
    </div>
  </section>

  <section class="hero is-danger is-medium is-bold">
    <div class="hero-body">
      <div class="container has-text-centered">
        <div class="columns">
          <div class="column is-6">
            <a class="button" id="go">RUN PYTHON FUNCTION</a>
          </div>
          <div class="column is-6">
            <div id="results"></div>
          </div>
        </div>
      </div>
    </div>
  </section>

  <footer class="footer">
    <div class="content has-text-centered">
      <p>{{footer}}</p>
    </div>
  </footer>

  <script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script src="{{ url_for('static', filename='js/scripts.js') }}"></script>

</body>

</html>

Thanks for reading. x

Resources