Easy to use Flask

A lightweight framework for Python. Minimal usage of Flask. For the time being, check the range you use and make a note.

All you have to do is Quick Start. If you're a Django person, check out here.

Preparation and easy usage

environment

A state where Python3 is installed on Mac and a virtual environment is created with venv.

Installation

pip install Flask

Hello World

Create a working folder. Anything is fine for the time being.

cd
mkdir flask
cd flask

Write the code with the name hello.py.

hello.py


from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
	name = "Hello World"
	return name

@app.route('/good')
def good():
	name = "Good"
	return name

##Magic
if __name__ == "__main__":
	app.run(debug=True)

Run

Try to run it.

python hello.py

Try to access the following URL.

http://localhost:5000/ http://localhost:5000/good

It was displayed safely. Easy.

Use Jinja2

Flask comes with a template engine called Jinja2 as standard, so let's use it. Create a folder called templates. Put the html there.

Common template

First of all, from the common template. Footers and headers. I'll cut corners here. It's written very similar to Django.

layout.html


<!doctype html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
{% block content %}
<!--Write the main content here-->
{% endblock %}
</body>
</html>

Individual page

Next is an individual page. Define the contents of {% block content%}.

hello.html


{% extends "layout.html" %}
{% block content %}
<h3>Hello</h3>
Hello.{{ name }}Mr.
{% endblock %}

Modify hello.py

Modify hello.py to use the template and pass variables.

hello.py


from flask import Flask, render_template #add to

app = Flask(__name__)

@app.route('/')
def hello():
	name = "Hoge"
	#return name
	return render_template('hello.html', title='flask test', name=name) #Change

##Magic
if __name__ == "__main__":
	app.run(debug=True)

After making changes, try accessing http: // localhost: 5000 /.

Use DB (MySQL)

Since it's a big deal, I'll try using the database (MySQL). First, let's play with hello.py. PyMySQL is used to connect to MySQL.

If you haven't installed it yet

pip install PyMySQL

Please install with.

Logic implementation

It's not so much logic, but I did it as follows. I think it's better to use common parts for connection information, etc., or use the with clause, but for the time being. .. ..

hello.py


from flask import Flask, render_template #add to
import pymysql #add to

app = Flask(__name__)

@app.route('/')
def hello():

	#db setting
	db = pymysql.connect(
			host='localhost',
			user='root',
			password='root',
			db='testdb',
			charset='utf8',
			cursorclass=pymysql.cursors.DictCursor,
		)

	cur = db.cursor()
	sql = "select * from members"
	cur.execute(sql)
	members = cur.fetchall()

	cur.close()
	db.close()
	
	#return name
	return render_template('hello.html', title='flask test', members=members) #Change

##Magic
if __name__ == "__main__":
	app.run(debug=True)

Individual page change

Let's display the contents in a loop with for. it's simple.

hello.html


{% extends "layout.html" %}
{% block content %}
<h3>List</h3>
<ul>
{% for member in members %}
	<li>{{ member.name}} : {{ member.email }}</li>
{% endfor %}
</ul>
{% endblock %}

It went well.

Parameter linkage

Next, simple parameter interlocking.

From URL

modern. Try to get the value from the URL.

hello.py


from flask import Flask, render_template

app = Flask(__name__)

@app.route('/hello/<name>')
def hello(name=None):
	#return name
	return render_template('hello.html', title='flask test', name=name) 
	
##Magic
if __name__ == "__main__":
	app.run(debug=True)

Try to access it with the following URL.

http://localhsot:5000/hello/hoge

From POST

Next is POST. HTML of form is omitted. Make a from to post normally and try posting. If you don't specify the method, you will get a "Method not allowed" error.

from flask import Flask, render_template, request #add to

app = Flask(__name__)

@app.route('/hello', methods=['POST']) #Method must be specified
def hello():
	if request.method == 'POST':
		name = request.form['name']
	else:
		name = "no name."
	return render_template('hello.html', title='flask test', name=name) 

##Magic
if __name__ == "__main__":
	app.run(debug=True)

From GET

Finally, GET or QueryString.

hello.py


from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/hello')
def hello():
	name = request.args.get('name')
	return render_template('hello.html', title='flask test', name=name) 

##Magic
if __name__ == "__main__":
	app.run(debug=True)

Try to access it with the following URL.

http://127.0.0.1:5000/hello?name=hoge

Returns JSON

Finally I would like to return JSON. It's easy if you use jsonify, but it supports garbled Japanese characters and sort order. Whether it is correct or not is subtle, but for the time being.

Returns a manually generated dictionary

hello.py


from flask import Flask, render_template, request, jsonify #add to

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False #Measures against garbled Japanese characters
app.config["JSON_SORT_KEYS"] = False #Sort as it is

@app.route('/hello')
def hello():
	data = [
		{"name":"Yamada"},
		{"age":30}
	]
	return jsonify({
			'status':'OK',
			'data':data
		})

##Magic
if __name__ == "__main__":
	app.run(debug=True)

Returns the result of DB

I would like to return the SELECT result of DB. In the above example, I tried to generalize the connection information part of the DB.

hello.py


from flask import Flask, render_template, jsonify #add to
import pymysql #add to

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False #Measures against garbled Japanese characters
app.config["JSON_SORT_KEYS"] = False #Sort as it is

def getConnection():
	return pymysql.connect(
        host='localhost',
        user='root',
        password='root',
        db='testdb',
        charset='utf8',
        cursorclass=pymysql.cursors.DictCursor,
    )

@app.route('/')
def hello():
	db = getConnection()
	cur = db.cursor()
	sql = "select * from members"
	cur.execute(sql)
	members = cur.fetchall()
	cur.close()
	db.close()
    
	return jsonify({
		'status':'OK',
		'members':members
		})

##Magic
if __name__ == "__main__":
    app.run(debug=True)

The following JSON will be returned.

{
  "status": "OK", 
  "members": [
    {
      "id": 1, 
      "name": "hoge", 
      "email": "[email protected]"
    }, 
    {
      "id": 2, 
      "name": "foo", 
      "email": "[email protected]"
    }
  ]
}

that's all. I would like to add it as needed.

Recommended Posts

Easy to use Flask
Easy to use SQLite3
Easy to use E-Cell 4 Intermediate
Easy to use E-Cell 4 Beginner's edition
Use Flask to run external files
Easy to use E-Cell 4 Advanced Edition
Easy to use Jupyter notebook (Python3.5)
Easy way to use Wikipedia in Python
Minimum knowledge to use Form in Flask
Let's make jupyter lab easy to use
How to use xml.etree.ElementTree
How to use Python-shell
How to use tf.data
How to use virtualenv
How to use Seaboan
How to use image-match
How to use Pandas 2
Easy way to use Python 2.7 on Cent OS 6
How to use Virtualenv
How to use pytest_report_header
How to use partial
How to use Bio.Phylo
How to use SymPy
How to use x-means
How to use WikiExtractor.py
How to use IPython
How to use virtualenv
How to use Matplotlib
How to use iptables
How to use numpy
Reasons to use logarithm
How to use TokyoTechFes2015
How to use venv
How to use dictionary {}
How to use Pyenv
How to use list []
How to use python-kabusapi
Python-How to use pyinstaller
How to use OptParse
How to use return
How to use dotenv
How to use pyenv-virtualenv
How to use Go.mod
How to use imutils
How to use import
[Introduction to WordCloud] It's easy to use even with Jetson-nano ♬
How to use Qt Designer
How to use search sorted
[gensim] How to use Doc2Vec
python3: How to use bottle (2)
Understand how to use django-filter
Use MeCab to fetch readings
[Python] How to use list 1
QSM analysis-How to use MEDI-
How to use FastAPI ③ OpenAPI
Easy to read control flow
How to use Python argparse
Easy to make with syntax
How to use IPython Notebook
How to use Pandas Rolling
[Note] How to use virtualenv