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.
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.
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.
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.
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.
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.
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.
Get the name from the request form and render index.html. This will display the name you entered on the screen.
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