Try using the web application framework Flask

Ruby is a flexible programming language and has a handy and lightweight web application framework like Sinatra. Until now, as a language for analysis I used to visualize statistics and data mainly in Python, but of course Python also has a wide variety of web application frames. There is work.

If you want to provide a mechanism for performing numerical calculations in Python as a web system, it is more consistent to create the web part in the same language rather than using another language.

So this time, I'll use Flask, a small Python framework, to create a very simple web application.

Flask has a friendly user guide translated into Japanese. https://a2c.bitbucket.io/flask/

It's written so carefully that basically anyone can create a web system by reading this document and moving their hands.

However, even this is a lot, so if you are not good at programming, it may still be difficult to read this. Even if you don't have the time, it will be a hassle. So, as a simple introduction, I would like to quickly create an app that simply sends text data and returns the results.

All you need is a Python environment with Flask installed. Regarding environment construction, I will omit it because you can read Other articles.

The biggest merit of using Python is the numerical calculation and data analysis system represented by pandas and NumPy. It is the first time in the library of. So I decided to use NumPy in the sample application as well.

Implement the desired program

First of all, let's create the part of the purpose you want to achieve through the web. Also called business logic.

sample.py


#Import the required libraries such as Flask
from flask import Flask, render_template, request, redirect, url_for
import numpy as np

#Instantiate your name as app
app = Flask(__name__)

#Method to display messages randomly
def picked_up():
    messages = [
        "Hello, please enter your name",
        "Hi! what is your name?",
        "Tell me your name"
    ]
    #NumPy random.Randomly fetch from array with choice
    return np.random.choice(messages)

#Write the routing for your web application from here
#What happens when you access the index
@app.route('/')
def index():
    title = "Welcome"
    message = picked_up()
    # index.Render html
    return render_template('index.html',
                           message=message, title=title)

# /What happens when you access post
@app.route('/post', methods=['GET', 'POST'])
def post():
    title = "Hello"
    if request.method == 'POST':
        #Get the "name" from the request form
        name = request.form['name']
        # index.Render html
        return render_template('index.html',
                               name=name, title=title)
    else:
        #If you want to redirect due to an error etc., it looks like this
        return redirect(url_for('index'))

if __name__ == '__main__':
    app.debug = True #Debug mode enabled
    app.run(host='0.0.0.0') #Accessable from anywhere

Prompt for a name on the top screen and display it on the screen when it is sent. That's the only program. Except for the routing, you'll see that it's almost a normal Python program.

Use the render_template () method to render the template. At this time, if you attach the object you want to pass as an argument, it will be available in the view.

Implement the screen

The screen is also called the view. As you can see in the user guide, Flask has a template engine called Jinja2.

Jinja2 http://jinja.pocoo.org/docs/dev/

It's basically plain HTML, but with special notation in between, you can display objects passed by Python, and handle things like conditionals and loops.

Prepare the layout

Writing headers for loading CSS and JavaScript on every screen is tedious and wasteful. Therefore, in a web application, it is common to prepare one HTML for layout such as layout.html only for the common part.

This time, we will use the CSS framework Bootstrap. Flask puts files like CSS and JavaScript in the / static directory. So unzip the Bootstrap .zip that you downloaded from the official site (http://getbootstrap.com/) and deploy it under static.

Also, prepare a directory called templates and put HTML under this directory.

layout.html


<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    {% if title %}
      <title>{{ title }}</title>
    {% else %}
      <title>Bootstrap 101 Template</title>
    {% endif %}
    <!-- Bootstrap -->
    <link href="/static/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    {% block content %}{% endblock %}
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="/static/js/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="/static/js/bootstrap.min.js"></script>
  </body>
</html>

Basically, I wrote Bootstrap's Basic Template as it is.

The part enclosed in {% ...%} is Jinja2. In this example, if the title exists as an instance, it will be displayed, and a block named content will be inserted.

Create individual pages

This time it's easy because there is only one index.html page.

The first {% extends "layout.html"%} extends layout.html. Now you only have to write the parts other than the layout. Also, by enclosing it in {% block content%} {% endblock%}, it will be treated as a block named content. Now it will be rendered in the content block part of the layout.

index.html


{% extends "layout.html" %}
{% block content %}
  <!-- Form
  ================================================== -->
<div class="form">
  <div class="container">
    <div class="row">
      <div class="col-md-12">
        <p class="lead">
          {% if name %}
Hello{{ name }}Mr.
          {% else %}
            {{ message }}
          {% endif %}
        </p>
        <form action="/post" method="post" class="form-inline">
          <label for="name">name</label>
          <input type="text" class="form-control" id="name" name="name" placeholder="Name">
          <button type="submit" class="btn btn-default">Send</button>
        </form>
      </div>
    </div>
  </div>
</div>
{% endblock %}

If there is a name instance, it will display the name, otherwise it will display the message.

Launch the application

The application is now complete. After that, if you do something like python app.py, the web application will start on port 5000 on localhost.

1.png

The top page was displayed safely. The message is randomly selected and displayed by NumPy. Enter your name here and press the submit button to send it to / post.

2.png

Get the name from the request form and render index.html. This will display the name you entered on the screen.

Summary

You can see that you can easily create a web application with Python. It may be said that being able to describe not only the analysis part but also other parts such as the web in the same language is different from the R language.

When you want to prepare a calculation system with a simple response function, it is convenient to extend the Python program and implement it as a web application as it is.

You can easily store the sent data in the database and read the data from the database by combining SQLAlchemy. I think this alone has given me the feeling that a practical application can be created.

The source code of this article is available at here.

Recommended Posts

Try using the web application framework Flask
Try using the Python web framework Tornado Part 1
Try using the Python web framework Tornado Part 2
Creating a web application using Flask ②
Creating a web application using Flask ①
Creating a web application using Flask ③
Creating a web application using Flask ④
Try using the Python web framework Django (2) --Look at setting.py
Web application using Bottle (1)
Try using the Python web framework Django (1)-From installation to server startup
How to build an application from the cloud using the Django web framework
WEB application development using django-Development 1-
(Python) Try to develop a web application using Django
Try using the Twitter API
Web application development with Flask
Try using the Twitter API
Try using the PeeringDB 2.0 API
Web application with Python + Flask ② ③
Web application with Python + Flask ④
WEB application development using Django [Django startup]
WEB application development using Django [Application addition]
[Sakura rental server] Try using flask.
Try using the Python Cmd module
Web application created with Python + Flask (using VScode) # 1-Virtual environment construction-
Try using the Wunderlist API in Python
WEB application development using Django [Model definition]
WEB application development using Django [Initial settings]
Try using the Kraken API in Python
Try using the $ 6 discount LiDAR (Camsense X1)
Try using the HL band in order
WEB application development using django-Development environment construction-
Try using the camera with Python's OpenCV
Try cluster analysis using the K-means method
WEB application development using Django [Request processing]
WEB application development using Django [Template addition]
Create an application using the Spotify API
I tried benchmarking a web application framework
I want to make a web application using React and Python flask
Implement a simple application with Python full scratch without using a web framework.
Try to write code from 1 using the machine learning framework chainer (mnist edition)
Try using Tkinter
Try using docker-py
[Raspberry Pi] Publish a web application on https using Apache + WSGI + Python Flask
I compared the speed of go language web framework echo and python web framework flask
Try to separate Controllers using Blueprint in Flask
Try using cookiecutter
Try using PDFMiner
Python web framework Django vs Pyramid vs Flask December 2015
Hit the Web API using requests Example: Flickr
WEB application development using Django [Admin screen creation]
Try using the BitFlyer Ligntning API in Python
Python: Try using the UI on Pythonista 3 on iPad
The day when a beginner who started programming for two and a half months made a web application using Flask
Try using the Chinese morphological analysis engine jieba
Try using geopandas
Try using Selenium
Try using scipy
Flask application settings
Response the resized image using Flask and PILImage
Try using LINE Notify for the time being
Try using pandas.DataFrame