The first artificial intelligence. Challenge web output with python. ~ Flask introduction

Now that I can use python, I want to output it on the Web!

After all, when I got to know python, I thought I had to output it somehow, and when I was looking for a python web framework, I came up with Flask and django.

It seems that there are many other things.

Reference: The hottest Python in 2016! Thorough comparison of three web frameworks http://www.sejuku.net/blog/3713#Python

If you make a mistake at the time of building the environment, you will lose your motivation at once, so I would like to try "Flask", which seems to be relatively easy to introduce.

Environmental setting

CentOS 7

Environment

** Install virtualenv **

Common to python2.7 series and 3.5 series

easy_install virtualenv

You can also use pip

# pip3 install virtualenv

Next, use Flask to create a directory to display the page.

# mkdir test
# cd test

Next, build an environment called env with virtualenv

# virtualenv env

Then activate this environment.

# . env/bin/activate

Flask installation

# easy_install Flask

By the way, it can also be installed with pip.

# pip install flask

Output python file to web

Create hello.py and make the directory structure as shown below.

test ┣ env ┗ hello.py

#hello.py

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return "Hello World!"

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

Do this.

# python hello.py
 * Running on http://localhost:5000/ (Press CTRL+C to quit)

Check directly from your local web browser. Enter ttp: // localhost: 5000 / or ttp: //127.0.0.1:5000/ in the address bar to open it.

flask01.jpg

Load HTML file as Templates and output

If the above is successful, I would like to continue loading the "HTML" file.

test ┣ env ┣ templates ┃ ┗ world.html ┗ hello.py

Build a directory like the one above.

Prepare the HTML to be loaded this time.

#world.html

<!doctype html>
<title>templates Hello World</title>
<h1>TEMPLATES Hello World</h1>

To load world.html, have hello.py import render_template to load the templates directory.

#hello.py

from flask import Flask,render_template  #<-- render_Load template
app = Flask(__name__)

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

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

flask02.jpg

Try to create a lower directory with Flask

By tweaking the @ app.route ('/') part of hello.py earlier, you can make it behave as if there is a lower directory. I will actually try it.

#hello.py

from flask import Flask,render_template 
app = Flask(__name__)

@app.route('/world/')  #<--Load as a virtual world directory
def hello():
    return render_template('hello.html')

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

In the above, @ app.route ('/') is changed to @ app.route ('/ world /').

Let's change the HTML so that you can see that it has also changed.

#world.html

<!doctype html>
<title>templates Hello World</title>
 <h1>WORLD Hello World</h1>

I will try it.

# python hello.py
 * Running on http://localhost:5000/ (Press CTRL+C to quit)

At ttp: //127.0.0.1:5000/, it will be Not Found and will not be displayed.

It will be displayed at ttp: //127.0.0.1:5000/world/.

flask03.jpg

By the way, if you leave it as it is, you can only see it locally on the server.

Since it is on the Web, it is meaningless if it can only be seen on the server local PC. Tweak hello.py a little. Modify the last code, app.run ().

    app.run()
    app.run(host='0.0.0.0')

Now you can access it from other PCs. Of course, it's a matter of course, but please keep port 5000 on the firewall open.

My blunder

When I created "hello.py", I thought it would be fine, so I named it "flask.py".

I'm using this name elsewhere, so I get an error saying that flask can't be imported.

# python flask.py
Traceback (most recent call last):
  File "flask.py", line 1, in <module>
    from flask import Flask
  File "/root/test/flask.py", line 1, in <module>
    from flask import Flask
ImportError: cannot import name 'Flask'

It was a coincidence, but I learned one thing.

Recommended Posts

The first artificial intelligence. Challenge web output with python. ~ Flask introduction
Introduction to Artificial Intelligence with Python 1 "Genetic Algorithm-Theory-"
Introduction to Artificial Intelligence with Python 2 "Genetic Algorithm-Practice-"
Web application with Python + Flask ② ③
Web application with Python + Flask ④
Web scraping with Python First step
Download files on the web with Python
Easy web app with Python + Flask + Heroku
The first web app created by Python beginners
Vienna with Python + Flask web app on Jenkins
Introduction to Tornado (1): Python web framework started with Tornado
[Introduction to Python3 Day 20] Chapter 9 Unraveling the Web (9.1-9.4)
Launch a web server with Python and Flask
Introduction to Python with Atom (on the way)
[Introduction to Udemy Python3 + Application] 9. First, print with print
Try to solve the programming challenge book with python3
[Introduction to Python] How to iterate with the range function?
The first algorithm to learn with Python: FizzBuzz problem
Playing with a user-local artificial intelligence API in Python
Parse and visualize JSON (Web application ⑤ with Python + Flask)
The first artificial intelligence. I wanted to try natural language processing, so I will try morphological analysis using MeCab with python3.
Python beginners get stuck with their first web scraping
Record of the first machine learning challenge with Keras
Programming with Python Flask
The first API to make with python Djnago REST framework
I made a simple book application with python + Flask ~ Introduction ~
[Part.2] Crawling with Python! Click the web page to move!
[CleanArchitecture with Python] Part2: Frameworks & Drivers Layer: Introducing the Web
[Python] The first step to making a game with Pyxel
Save images on the web to Drive with Python (Colab)
[Introduction to Python] How to get data with the listdir function
Easy deep learning web app with NNC and Python + Flask
Web scraping with python + JupyterLab
Predict candlesticks with artificial intelligence
Try Python output with Haxe 3.2
Web application development with Flask
First neuron simulation with NEURON + Python
Web API with Python + Falcon
Call the API with python3.
Web scraping beginner with python
Streamline web search with python
Web application created with Python + Flask (using VScode) # 1-Virtual environment construction-
[python, ruby] fetch the contents of a web page with selenium-webdriver
[Introduction to Python] How to split a character string with the split function
I want to output the beginning of the next month with Python
Output the contents of ~ .xlsx in the folder to HTML with Python
[Introduction to sinGAN-Tensorflow] I played with the super-resolution "Challenge Big Imayuyu" ♬
The first artificial intelligence. How to check the version of Tensorflow installed.
From the introduction of JUMAN ++ to morphological analysis of Japanese with Python
Visualize your pocket money files with the Python web framework Dash
Extract the xz file with python
SNS Python basics made with Flask
First Python 3 ~ The beginning of repetition ~
Challenge LOTO 6 with Python without discipline
Web scraping with Python ① (Scraping prior knowledge)
Getting Started with Python Web Applications
Output to csv file with Python
I tried web scraping with python.
Run the app with Flask + Heroku
Input / output with Python (Python learning memo ⑤)
Monitor Python web apps with Prometheus