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.
A state where Python3 is installed on Mac and a virtual environment is created with venv.
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)
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.
Flask comes with a template engine called Jinja2 as standard, so let's use it. Create a folder called templates. Put the html there.
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>
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 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 /.
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.
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)
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.
Next, simple parameter interlocking.
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
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)
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
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.
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)
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