Flask It's a lightweight based on Python Of web frame .
The code in this document uses Python 3 function .
Yes , So readers need to install on their own computers Python 3 and pip3. It is recommended to install the latest version , I'm using Python 3.6.4
.
Installation method , You can Google or Baidu by yourself .
It is suggested that linux Practice the command line operation in this tutorial 、 Execute code .
adopt pip3 install Flask that will do :
$ sudo pip3 install Flask
Get into python In interactive mode Flask Introduction and version of :
$ python3
>>> import flask
>>> print(flask.__doc__)
flask
~~~~~
A microframework based on Werkzeug. It's extensively documented
and follows best practice patterns.
:copyright: 2010 by the Pallets team.
:license: BSD, see LICENSE for more details.
>>> print(flask.__version__)
1.0.2
The main content of this section : Use Flask Write a display ”Hello World!” Of web Program , How to configure 、 debugging Flask.
Follow the command below to create Flask project HelloWorld:
mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
static
and templates
Directory is the default configuration , among static
Used to store static resources , For example, pictures 、js、css Documents, etc. .templates
Store template files .
Our website logic is basically server.py
In file , Of course , You can also give this file another name .
stay server.py
Add the following :
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
function server.py
:
$ python3 server.py
* Running on http://127.0.0.1:5000/
Open browser access http://127.0.0.1:5000/
, The browse page will appear Hello World!
.
The following information will be displayed in the terminal :
127.0.0.1 - - [16/May/2014 10:29:08] "GET / HTTP/1.1" 200 -
Variable app It's a Flask example , By :
@app.route('/')
def hello_world():
return 'Hello World!'
When the client accesses /
when , Will respond hello_world()
The function returns . Be careful , This is not a return Hello World!
So simple ,Hello World!
It's just HTTP The physical part of the response message , Information such as status code can be represented by Flask Automatic processing , Can also be programmed to develop .
app = Flask(__name__)
In the above code ,python Built-in variables __name__
The value of is a string __main__
.Flask Class takes this parameter as the program name . Of course, this can be customized , such as app = Flask("my-app")
.
Flask By default static
The directory stores static resources ,templates
Directory to store templates , This can be changed by setting parameters :
app = Flask("my-app", static_folder="path1", template_folder="path2")
For more parameters, please refer to __doc__
:
from flask import Flask
print(Flask.__doc__)
above server.py China and Israel app.run()
Way to run , In this way , If an error occurs on the server side, it will not be displayed on the client side . But in the development environment , It is necessary to display error messages , To display an error message , It should run in the following way Flask:
app.run(debug=True)
take debug
Set to True
Another benefit of , After the program starts , It will automatically detect whether the source code has changed , If there is any change, the program will be restarted automatically . This can save us a lot of time .
By default ,Flask binding IP by 127.0.0.1
, Port is 5000
. We can also customize it in the following way :
app.run(host='0.0.0.0', port=80, debug=True)
0.0.0.0
It's all about computers IP.80
yes HTTP Default port for Web Services . What is default ? such as , We visit the website http://www.example.com
, It's actually an interview http://www.example.com:80
, It's just :80
You can omit it .
Because of binding 80 port , Need to use root Permission to run server.py
. That is to say :
$ sudo python3 server.py
URL Parameters appear in url Key value pairs in , for example http://127.0.0.1:5000/?disp=3
Medium url Parameter is {'disp':3}
.
Follow the command below to create Flask project HelloWorld:
mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
stay server.py To add the following :
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def hello_world():
return request.args.__str__()
if __name__ == '__main__':
app.run(port=5000, debug=True)
Access in a browser http://127.0.0.1:5000/?user=Flask&time&p=7&p=8
, Will be displayed :
ImmutableMultiDict([('user', 'Flask'), ('time', ''), ('p', '7'), ('p', '8')])
Newer browsers also support direct access to url Input Chinese ( The latest Firefox browser will help convert Chinese to conform to URL Data specification ), Access in a browser http://127.0.0.1:5000/?info= It's love ,
, Will be displayed :
ImmutableMultiDict([('info', ' It's love ,')])
The browser passed it to us Flask What does the data of the service look like ? Can pass request.full_path
and request.path
Take a look at :
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def hello_world():
print(request.path)
print(request.full_path)
return request.args.__str__()
if __name__ == '__main__':
app.run(port=5000, debug=True)
Browser access http://127.0.0.1:5000/?info= It's love ,
, function server.py
The terminal will output :
//?info=%E8%BF%99%E6%98%AF%E7%88%B1%EF%BC%8C
for example , To get keys info
Corresponding value , Modified as follows server.py
:
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def hello_world():
return request.args.get('info')
if __name__ == '__main__':
app.run(port=5000)
function server.py
, Access in a browser http://127.0.0.1:5000/?info=hello
, The browser will show :
hello
however , When we visit http://127.0.0.1:5000/
But then it happened 500 error , Browser display :
If it's on Debug Pattern , Will be displayed :
Why is that ?
It's because there's no one here URL Found... In parameter info
. therefore request.args.get('info')
return Python Built in None, and Flask Return... Is not allowed None.
The solution is simple , Let's first judge whether it is None:
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def hello_world():
r = request.args.get('info')
if r==None:
# do something
return ''
return r
if __name__ == '__main__':
app.run(port=5000, debug=True)
Another way is , Set the default value , That is, use this value when you can't get data :
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def hello_world():
r = request.args.get('info', 'hi')
return r
if __name__ == '__main__':
app.run(port=5000, debug=True)
function request.args.get
The second parameter of is used to set the default value . At this point in the browser access http://127.0.0.1:5000/
, Will be displayed :
hi
Remember there was a request like this ? http://127.0.0.1:5000/?user=Flask&time&p=7&p=8
, Take a close look at ,p
There are two values .
If our code is :
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def hello_world():
r = request.args.get('p')
return r
if __name__ == '__main__':
app.run(port=5000, debug=True)
When requested in the browser , We'll only see 7
. If we need to put p
Get all the values of , What should I do ?
no need get
, use getlist
:
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def hello_world():
r = request.args.getlist('p') # Return to one list
return str(r)
if __name__ == '__main__':
app.run(port=5000, debug=True)
Browser input http://127.0.0.1:5000/?user=Flask&time&p=7&p=8
, We'll see ['7', '8']
.
As a kind of HTTP Request method ,POST Used to submit the data to be processed to the specified resource . We register users on a website 、 When writing an article , Data needs to be transferred to the web server . It's not suitable to put data into URL Parameters in , Put the password in URL Parameters are easy to see , There are too many article data , Browsers don't necessarily support too long URL. At this time , In general use POST Method .
This article USES the python Of requests Library simulation browser .
Installation method :
$ sudo pip3 install requests
Follow the command below to create Flask project HelloWorld:
mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
Take user registration as an example , We need to report to the server /register
Send user name name
And password password
. Write as follows HelloWorld/server.py
.
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'hello world'
@app.route('/register', methods=['POST'])
def register():
print(request.headers)
print(request.stream.read())
return 'welcome'
if __name__ == '__main__':
app.run(port=5000, debug=True)
[`@app.route](mailto:`@app.route)(‘/register’, methods=[‘POST’])` Refer to url`/register` We only accept POST Method . Can be modified as needed `methods` Parameters , For example, if you want it to support GET and POST, Write it like this :
@app.route('/register', methods=['GET', 'POST'])
Browser simulation tool client.py
The contents are as follows :
import requests
user_info = {
'name': 'letian', 'password': '123'}
r = requests.post("http://127.0.0.1:5000/register", data=user_info)
print(r.text)
function HelloWorld/server.py
, And then run client.py
.client.py
Will output :
welcome
and HelloWorld/server.py
Output the following debugging information in the terminal ( adopt print
Output ):
Host: 127.0.0.1:5000
User-Agent: python-requests/2.19.1
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Length: 24
Content-Type: application/x-www-form-urlencoded
b'name=letian&password=123'
front 6 Line is client.py Generated HTTP Request header , from print(request.headers)
Output .
Data of the request body , We go through print(request.stream.read())
Output , The result is :
b'name=letian&password=123'
above , We see post The data content is :
b'name=letian&password=123'
We have to find a way to get what we want name、password extracted , How to do it? ? Write it yourself ? no need ,Flask The parser has been built in request.form
.
We changed the service code to :
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'hello world'
@app.route('/register', methods=['POST'])
def register():
print(request.headers)
# print(request.stream.read()) # Do not use , Otherwise the following form No data
print(request.form)
print(request.form['name'])
print(request.form.get('name'))
print(request.form.getlist('name'))
print(request.form.get('nickname', default='little apple'))
return 'welcome'
if __name__ == '__main__':
app.run(port=5000, debug=True)
perform client.py
Request data , The server code will be output at the terminal :
Host: 127.0.0.1:5000
User-Agent: python-requests/2.19.1
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Length: 24
Content-Type: application/x-www-form-urlencoded
ImmutableMultiDict([('name', 'letian'), ('password', '123')])
letian
letian
['letian']
little apple
request.form
Will automatically parse the data .
request.form['name']
and request.form.get('name')
You can get name
Corresponding value . about request.form.get()
It can be a parameter default
Specify a value as the default . therefore :
print(request.form.get('nickname', default='little apple'))
The output is the default value
little apple
If name
There are multiple values , have access to request.form.getlist('name')
, This method will return a list . We will client.py Change it :
import requests
user_info = {
'name': ['letian', 'letian2'], 'password': '123'}
r = requests.post("http://127.0.0.1:5000/register", data=user_info)
print(r.text)
At this time to run client.py
,print(request.form.getlist('name'))
Will output :
[u'letian', u'letian2']
Use HTTP POST There are many kinds of data formats that can be transmitted to the website server , such as 「5. obtain POST Method to transfer data 」 About name=letian&password=123
This is used &
Symbol segmentation key-value Key value pair format . We can also use JSON Format 、XML Format . comparison XML Weight of 、 Cumbersome specification ,JSON It looks very small and easy to use .
Follow the command below to create Flask project HelloWorld:
mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
If POST The data of JSON Format ,request.json
Will automatically json Data to Python type ( Dictionary or list ).
To write server.py
:
from flask import Flask, request
app = Flask("my-app")
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/add', methods=['POST'])
def add():
print(request.headers)
print(type(request.json))
print(request.json)
result = request.json['a'] + request.json['b']
return str(result)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000, debug=True)
To write client.py
Simulate browser request :
import requests
json_data = {
'a': 1, 'b': 2}
r = requests.post("http://127.0.0.1:5000/add", json=json_data)
print(r.text)
function server.py
, And then run client.py
,client.py
It will output at the terminal :
3
server.py
It will output at the terminal :
Host: 127.0.0.1:5000
User-Agent: python-requests/2.19.1
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Length: 16
Content-Type: application/json
<class 'dict'>
{
'a': 1, 'b': 2}
Be careful , Request header Content-Type
The value of is application/json
.
Respond to JSON when , In addition to changing the response style to JSON Format , Of the response head Content-Type
Also set it to application/json
.
To write server2.py
:
from flask import Flask, request, Response
import json
app = Flask("my-app")
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/add', methods=['POST'])
def add():
result = {
'sum': request.json['a'] + request.json['b']}
return Response(json.dumps(result), mimetype='application/json')
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000, debug=True)
Run after modification .
To write client2.py
:
import requests
json_data = {
'a': 1, 'b': 2}
r = requests.post("http://127.0.0.1:5000/add", json=json_data)
print(r.headers)
print(r.text)
function client.py
, Will be displayed :
{
'Content-Type': 'application/json', 'Content-Length': '10', 'Server': 'Werkzeug/0.14.1 Python/3.6.4', 'Date': 'Sat, 07 Jul 2018 05:23:00 GMT'}
{
"sum": 3}
The first paragraph above is the response header of the server , The second paragraph is the response body , That is, the server returns JSON Format data .
in addition , If you need a server HTTP The response header has better customizability , For example, customization Server
, It can be modified as follows add()
function :
@app.route('/add', methods=['POST'])
def add():
result = {
'sum': request.json['a'] + request.json['b']}
resp = Response(json.dumps(result), mimetype='application/json')
resp.headers.add('Server', 'python flask')
return resp
client2.py
It will output :
{
'Content-Type': 'application/json', 'Content-Length': '10', 'Server': 'python flask', 'Date': 'Sat, 07 Jul 2018 05:26:40 GMT'}
{
"sum": 3}
Use jsonify Tool functions can be used .
from flask import Flask, request, jsonify
app = Flask("my-app")
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/add', methods=['POST'])
def add():
result = {
'sum': request.json['a'] + request.json['b']}
return jsonify(result)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000, debug=True)
Upload files , In general, it is also used POST Method .
Follow the command below to create Flask project HelloWorld:
mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
The code in this part refers to How to upload a file to the server in Flask.
Let's take the above pictures as an example :
Suppose that the pictures to be uploaded only allow ’png’、’jpg’、’jpeg’、’gif’ There are four formats , adopt url/upload
Use POST Upload , The uploaded pictures are stored in the server static/uploads
Under the table of contents .
First in the project HelloWorld
Create directory in static/uploads
:
mkdir HelloWorld/static/uploads
werkzeug
The library can determine whether the file name is safe , For example, prevent the file name from being ../../../a.png
, Install this library :
$ sudo pip3 install werkzeug
server.py
Code :
from flask import Flask, request
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
# File upload directory
app.config['UPLOAD_FOLDER'] = 'static/uploads/'
# Supported file formats
app.config['ALLOWED_EXTENSIONS'] = {
'png', 'jpg', 'jpeg', 'gif'} # Collection types
# Determine whether the file name is in the format we support
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
@app.route('/')
def hello_world():
return 'hello world'
@app.route('/upload', methods=['POST'])
def upload():
upload_file = request.files['image']
if upload_file and allowed_file(upload_file.filename):
filename = secure_filename(upload_file.filename)
# Save file to static/uploads Catalog , The file name is the same as the file name used when uploading
upload_file.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename))
return 'info is '+request.form.get('info', '')+'. success'
else:
return 'failed'
if __name__ == '__main__':
app.run(port=5000, debug=True)
app.config
Medium config It's a subclass of a dictionary , It can be used to set its own configuration information , You can also set your own configuration information . function allowed_file(filename)
Used to determine filename
Whether there is a suffix and whether the suffix is in app.config['ALLOWED_EXTENSIONS']
in .
The pictures uploaded by the client must be in image01
identification .upload_file
Is the object corresponding to the uploaded file .app.root_path
obtain server.py
The path to the file system is in the absolute directory .upload_file.save(path)
Used to put upload_file
Saved in the file system of the server , The best parameter is the absolute path , Otherwise, an error will be reported ( Many codes on the Internet use relative paths , However, the author always reports an error when using the relative path , Said the path could not be found ). function os.path.join()
Used to combine paths using appropriate path separators .
Okay , Custom client client.py
:
import requests
file_data = {
'image': open('Lenna.jpg', 'rb')}
user_info = {
'info': 'Lenna'}
r = requests.post("http://127.0.0.1:5000/upload", data=user_info, files=file_data)
print(r.text)
function client.py
, In the current directory Lenna.jpg
Upload to the server .
then , We can do it in static/uploads
See file in Lenna.jpg
.
To control the size of the production file , You can set the size of the request entity , for example :
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 #16MB
however , When processing uploaded files , Need to use try:...except:...
.
If you want to get the content of the uploaded file, you can :
file_content = request.files['image'].stream.read()
Simply speaking ,Restful URL It's right URL Substitution of parameters .
Follow the command below to create Flask project HelloWorld:
mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
edit server.py:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'hello world'
@app.route('/user/<username>')
def user(username):
print(username)
print(type(username))
return 'hello ' + username
@app.route('/user/<username>/friends')
def user_friends(username):
print(username)
print(type(username))
return 'hello ' + username
if __name__ == '__main__':
app.run(port=5000, debug=True)
function HelloWorld/server.py
. Use browser access http://127.0.0.1:5000/user/letian
,HelloWorld/server.py Will output :
letian
<class 'str'>
And access http://127.0.0.1:5000/user/letian/
, The response is a 404 Not Found.
Browser access http://127.0.0.1:5000/user/letian/friends
, You can see :
Hello letian. They are your friends.
HelloWorld/server.py
Output :
letian
<class 'str'>
As can be seen from the above example , Use Restful URL The obtained variable defaults to str object . If we need to display the query results in pages , So you need to url There are numbers in the to specify the number of pages . Follow the above method , You can get str After type page variable , Convert it to int type . however , There are more convenient ways , Just use flask Built in conversion mechanism , That is to say route Specifies how to convert .
New server code :
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'hello world'
@app.route('/page/<int:num>')
def page(num):
print(num)
print(type(num))
return 'hello world'
if __name__ == '__main__':
app.run(port=5000, debug=True)
[`@app.route](mailto:`@app.route)(‘/page/int:num‘)` Will num Variables are automatically converted to int type .
Run the above program , Access in a browser http://127.0.0.1:5000/page/1
,HelloWorld/server.py The following will be output :
1
<class 'int'>
If the interview is http://127.0.0.1:5000/page/asd
, We will get 404 Respond to .
In official information , Said there was 3 A default Converter :
int accepts integers
float like int but for floating point values
path like the default but also accepts slashes
Looks like enough .
Write the server code as follows :
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'hello world'
@app.route('/page/<int:num1>-<int:num2>')
def page(num1, num2):
print(num1)
print(num2)
return 'hello world'
if __name__ == '__main__':
app.run(port=5000, debug=True)
Access in a browser http://127.0.0.1:5000/page/11-22
,HelloWorld/server.py
Will be output :
11
22
The custom converter is an inheritance werkzeug.routing.BaseConverter
Class , modify to_python
and to_url
The method can .to_python
Method is used to url After the variable in... Is converted [`@app.route](mailto:`@app.route)` Wrapped functions use ,`to_url` Method is used for `flask.url_for` Parameter conversion in .
Here's an example , take HelloWorld/server.py
Revised as follows :
from flask import Flask, url_for
from werkzeug.routing import BaseConverter
class MyIntConverter(BaseConverter):
def __init__(self, url_map):
super(MyIntConverter, self).__init__(url_map)
def to_python(self, value):
return int(value)
def to_url(self, value):
return value * 2
app = Flask(__name__)
app.url_map.converters['my_int'] = MyIntConverter
@app.route('/')
def hello_world():
return 'hello world'
@app.route('/page/<my_int:num>')
def page(num):
print(num)
print(url_for('page', num=123)) # page The corresponding is page function ,num Corresponding to `/page/<my_int:num>` Medium num, Must be str
return 'hello world'
if __name__ == '__main__':
app.run(port=5000, debug=True)
Browser access http://127.0.0.1:5000/page/123
after ,HelloWorld/server.py
The output message is :
123/page/123123
understand RESTful framework .
url_for
Generate links Tool function url_for
It allows you to generate... In the form of soft coding url, Provide development efficiency .
Follow the command below to create Flask project HelloWorld:
mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
edit HelloWorld/server.py
:
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def hello_world():
pass
@app.route('/user/<name>')
def user(name):
pass
@app.route('/page/<int:num>')
def page(num):
pass
@app.route('/test')
def test():
print(url_for('hello_world'))
print(url_for('user', name='letian'))
print(url_for('page', num=1, q='hadoop mapreduce 10%3'))
print(url_for('static', filename='uploads/01.jpg'))
return 'Hello'
if __name__ == '__main__':
app.run(debug=True)
function HelloWorld/server.py
. It is then accessed in a browser http://127.0.0.1:5000/test
,HelloWorld/server.py
The following information will be output :
/
/user/letian
/page/1?q=hadoop+mapreduce+10%253
/static/uploads/01.jpg
redirect
Function for redirection , The implementation mechanism is simple , That's to say to the client ( browser ) Send a redirected HTTP message , The browser will access the url.
Follow the command below to create Flask project HelloWorld:
mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
Use redirect
when , Just give it a string parameter .
edit HelloWorld/server.py
:
from flask import Flask, url_for, redirect
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'hello world'
@app.route('/test1')
def test1():
print('this is test1')
return redirect(url_for('test2'))
@app.route('/test2')
def test2():
print('this is test2')
return 'this is test2'
if __name__ == '__main__':
app.run(debug=True)
function HelloWorld/server.py
, Access in a browser http://127.0.0.1:5000/test1
, Browser's url Will become http://127.0.0.1:5000/test2
, And display :
this is test2
The template engine is responsible for MVC Medium V(view, View ) This part .Flask By default Jinja2 template engine .
Flask The functions related to the template are :
The first two functions are commonly used .
Template inheritance is used in this example 、if Judge 、for loop .
Follow the command below to create Flask project HelloWorld:
mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
The contents are as follows :
<html>
<head>
<title>
{
% if page_title %}
{
{
page_title }}
{
% endif %}
</title>
</head>
<body>
{
% block body %}{
% endblock %}
You can see , stay In the label if Judge , If passed to the template `page_title` Variable , Show it , otherwise , No display .
A tag named body
Of block, Used to be inherited by other template files .
The contents are as follows :
{% extends "default.html" %}
{% block body %}
{% for key in user_info %}
{
{ key }}: {
{ user_info[key] }}
{% endfor %}
{% endblock %}
Variable user_info
It should be a dictionary ,for Loop is used to loop out key value pairs .
The contents are as follows :
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'hello world'
@app.route('/user')
def user():
user_info = {
'name': 'letian',
'email': '[email protected]',
'age':0,
'github': 'https://github.com/letiantian'
}
return render_template('user_info.html', page_title='letian\'s info', user_info=user_info)
if __name__ == '__main__':
app.run(port=5000, debug=True)
render_template()
The first parameter of the function specifies the template file , The following parameters are the data to be passed .
function HelloWorld/server.py:
$ python3 HelloWorld/server.py
Access in a browser http://127.0.0.1:5000/user
, The renderings are as follows :
View source code of webpage :
<html>
<head>
<title>
letian's info
</title>
</head>
<body>
name: letian <br/>
email: [email protected] <br/>
age: 0 <br/>
github: https://github.com/letiantian <br/>
</body>
</html>
To deal with HTTP error , have access to flask.abort
function .
establish Flask project
Follow the command below to create Flask project HelloWorld:
mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
Code
edit HelloWorld/server.py
:
from flask import Flask, render_template_string, abort
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'hello world'
@app.route('/user')
def user():
abort(401) # Unauthorized unauthorized
print('Unauthorized, Please log in first ')
if __name__ == '__main__':
app.run(port=5000, debug=True)
effect
function HelloWorld/server.py
, Browser access http://127.0.0.1:5000/user
, The effect is as follows :
It should be noted that ,HelloWorld/server.py
in abort(401)
After print
It's not implemented .
Code
Change the server code to :
from flask import Flask, render_template_string, abort
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'hello world'
@app.route('/user')
def user():
abort(401) # Unauthorized
@app.errorhandler(401)
def page_unauthorized(error):
return render_template_string('<h1> Unauthorized </h1><h2>{
{ error_info }}</h2>', error_info=error), 401
if __name__ == '__main__':
app.run(port=5000, debug=True)
page_unauthorized
Function returns a tuple ,401 representative HTTP Response status code . If omitted 401, The response status code will become the default 200.
effect
function HelloWorld/server.py
, Browser access http://127.0.0.1:5000/user
, The effect is as follows :
session Used to record the login status of users , Generally based on cookie Realization .
Here is a simple example .
Follow the command below to create Flask project HelloWorld:
mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
HelloWorld/server.py
The contents are as follows :
from flask import Flask, render_template_string, \
session, request, redirect, url_for
app = Flask(__name__)
app.secret_key = 'F12Zr47j\3yX [email protected]!jLwf/T'
@app.route('/')
def hello_world():
return 'hello world'
@app.route('/login')
def login():
page = ''' <form action="{
{ url_for('do_login') }}" method="post"> <p>name: <input type="text" name="user_name" /></p> <input type="submit" value="Submit" /> </form> '''
return render_template_string(page)
@app.route('/do_login', methods=['POST'])
def do_login():
name = request.form.get('user_name')
session['user_name'] = name
return 'success'
@app.route('/show')
def show():
return session['user_name']
@app.route('/logout')
def logout():
session.pop('user_name', None)
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(port=5000, debug=True)
app.secret_key
For giving session encryption .
stay /login
A form will be presented to the user , Ask for a name ,submit After that, the data is displayed in post To pass on to /do_login
,/do_login
Put your name in session in .
If the user logs in successfully , visit /show
The user's name will be displayed . here , open firebug Etc , choice session panel , There will be one cookie For the name of the session
.
/logout
Used to log out , By way of session
Medium user_name
Field pop that will do .Flask Medium session Implement based on dictionary type , call pop Method will return pop The value corresponding to the key of ; If you want to pop The key does not exist , So the return value is pop()
Second parameter of .
in addition , Use redirect()
When redirecting , Be sure to add return
.
Get into http://127.0.0.1:5000/login
, Input name, Click on submit:
Get into http://127.0.0.1:5000/show
see session Stored in the name:
The following code is from Is there an easy way to make sessions timeout in flask?:
from datetime import timedelta
from flask import session, app
session.permanent = True
app.permanent_session_lifetime = timedelta(minutes=5)
This code will session The effective time of is set to 5 minute .
Cookie Is the data stored in the client to record the status of visitors . Specific principle , Please see http://zh.wikipedia.org/wiki/Cookie . Commonly used to record user login status session Mostly based on cookie Realized .
cookie Can use flask.Response
To achieve . Here's an example .
Follow the command below to create Flask project HelloWorld:
mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
modify HelloWorld/server.py
:
from flask import Flask, request, Response, make_response
import time
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'hello world'
@app.route('/add')
def login():
res = Response('add cookies')
res.set_cookie(key='name', value='letian', expires=time.time()+6*60)
return res
@app.route('/show')
def show():
return request.cookies.__str__()
@app.route('/del')
def del_cookie():
res = Response('delete cookies')
res.set_cookie('name', '', expires=0)
return res
if __name__ == '__main__':
app.run(port=5000, debug=True)
You can see from above that , have access to Response.set_cookie
Add and remove cookie.expires
Parameter to set cookie Valid time , Its value can be datetime
Object or unix Time stamp , I used unix Time stamp .
res.set_cookie(key='name', value='letian', expires=time.time()+6*60)
above expire The value of the parameter indicates cookie From now on 6 It works for minutes .
To delete cookie, take expire The value of the parameter is set to 0 that will do :
res.set_cookie('name', '', expires=0)
set_cookie()
The prototype of the function is as follows :
set_cookie(key, value=’’, max_age=None, expires=None, path=’/‘, domain=None, secure=None, httponly=False)
Sets a cookie. The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data, too.
Parameters:
key – the key (name) of the cookie to be set.
value – the value of the cookie.
max_age – should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session.
expires – should be a datetime object or UNIX timestamp.
domain – if you want to set a cross-domain cookie. For example, domain=”.example.com” will set a cookie that is readable by the domain www.example.com, foo.example.com etc. Otherwise, a cookie will only be readable by the domain that set it.
path – limits the cookie to a given path, per default it will span the whole domain.
function HelloWorld/server.py
:
$ python3 HelloWorld/server.py
Open with browser http://127.0.0.1:5000/add
, The browser interface will show
add cookies
Let's take a look cookie, If you use firefox browser , It can be used firebug Plug in view . open firebug, choice Cookies
Options , Refresh the page , You can see it's called name
Of cookie, Its value is letian
.
stay “ The Internet ” In the options , You can view the settings similar to the following in the response header cookie Of HTTP「 Instructions 」:
Set-Cookie: name=letian; Expires=Sun, 29-Jun-2014 05:16:27 GMT; Path=/
stay cookie Period of validity , Use browser access http://127.0.0.1:5000/show
, You can see :
{
'name': 'letian'}
Flask Flash memory system (flashing system) Used to provide feedback to users , This feedback information is generally the feedback of the user's last operation . The feedback information is stored on the server side , When the server returns feedback information to the client , These feedback information will be deleted by the server .
Here's an example .
Follow the command below to create Flask project HelloWorld:
mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py
The contents are as follows :
from flask import Flask, flash, get_flashed_messages
import time
app = Flask(__name__)
app.secret_key = 'some_secret'
@app.route('/')
def index():
return 'hi'
@app.route('/gen')
def gen():
info = 'access at '+ time.time().__str__()
flash(info)
return info
@app.route('/show1')
def show1():
return get_flashed_messages().__str__()
@app.route('/show2')
def show2():
return get_flashed_messages().__str__()
if __name__ == "__main__":
app.run(port=5000, debug=True)
Run the server :
$ python3 HelloWorld/server.py
Open the browser , visit http://127.0.0.1:5000/gen
, The browser interface shows ( Be careful , Timestamps are generated dynamically , Every time will be different , Unless parallel access ):
access at 1404020982.83
Check out the browser's cookie, You can see session
, The corresponding content is :
.eJyrVopPy0kszkgtVrKKrlZSKIFQSUpWSknhYVXJRm55UYG2tkq1OlDRyHC_rKgIvypPdzcDTxdXA1-XwHLfLEdTfxfPUn8XX6DKWCAEAJKBGq8.BpE6dg.F1VURZa7VqU9bvbC4XIBO9-3Y4Y
Visit again http://127.0.0.1:5000/gen
, The browser interface shows :
access at 1404021130.32
cookie in session
There is a change , The new content is :
.eJyrVopPy0kszkgtVrKKrlZSKIFQSUpWSknhYVXJRm55UYG2tkq1OlDRyHC_rKgIvypPdzcDTxdXA1-XwHLfLEdTfxfPUn8XX6DKWLBaMg1yrfCtciz1rfIEGxRbCwAhGjC5.BpE7Cg.Cb_B_k2otqczhknGnpNjQ5u4dqw
Then use a browser to access http://127.0.0.1:5000/show1
, The browser interface shows :
['access at 1404020982.83', 'access at 1404021130.32']
The contents of this list are the above two visits http://127.0.0.1:5000/gen
What you get . here ,cookie No more session
了 .
If you use a browser to access http://127.0.0.1:5000/show1
perhaps http://127.0.0.1:5000/show2
, Only get :
[]
flash The system also supports flash The contents are classified . modify HelloWorld/server.py
Content :
from flask import Flask, flash, get_flashed_messages
import time
app = Flask(__name__)
app.secret_key = 'some_secret'
@app.route('/')
def index():
return 'hi'
@app.route('/gen')
def gen():
info = 'access at '+ time.time().__str__()
flash('show1 '+info, category='show1')
flash('show2 '+info, category='show2')
return info
@app.route('/show1')
def show1():
return get_flashed_messages(category_filter='show1').__str__()
@app.route('/show2')
def show2():
return get_flashed_messages(category_filter='show2').__str__()
if __name__ == "__main__":
app.run(port=5000, debug=True)
At some point , Browser access http://127.0.0.1:5000/gen
, The browser interface shows :
access at 1404022326.39
however , From the above code, we can know , At this point, two flash Information , But classification (category) Different .
Use browser access http://127.0.0.1:5000/show1
, Get the following :
['1 access at 1404022326.39']
And continue to visit http://127.0.0.1:5000/show2
, The obtained content is empty :
[]
stay Flask in ,get_flashed_messages()
The default has been integrated into Jinja2
In the template engine , Easy to use . Here is an example from the official :