├── .gitignore ├── Flask-02 └── run.py ├── Flask-03-route ├── run1.py ├── run2.py ├── run3.py └── run4.py ├── Flask-04-templates ├── 1 │ ├── run.py │ └── templates │ │ └── index.html └── 2 │ ├── run.py │ └── templates │ └── index.html ├── Flask-05-get-post ├── get │ ├── run.py │ └── templates │ │ └── index.html └── post │ ├── run.py │ └── templates │ └── index.html ├── Flask-06-cookie-session ├── cookie │ └── run.py └── session │ ├── run.py │ └── templates │ └── getvalue.html ├── Flask-07-upload ├── run.py └── templates │ ├── index.html │ └── success.html ├── Flask-08-redirect ├── run.py └── templates │ └── login.html ├── Flask-09-flash ├── run.py └── templates │ ├── index.html │ └── login.html ├── Flask-10-wtf ├── run.py └── templates │ └── register.html ├── Flask-11-sqlalchemy ├── run.py └── templates │ └── register.html ├── Flask-12-deployment └── README.md ├── Flask-13-structure └── README.md ├── Flask-14-blueprint ├── README.md ├── app │ ├── __init__.py │ ├── config.py │ └── views │ │ └── index.py ├── manage.py └── requirements.txt ├── Flask-15-logging ├── manage.py └── requirements.txt ├── Flask-16-restful ├── manage.py └── requirements.txt ├── Flask-17-cors ├── manage.py └── requirements.txt ├── Flask-18-jwt-extended ├── app │ ├── __init__.py │ ├── config.py │ ├── controller.py │ ├── models.py │ └── routes.py ├── manage.py ├── requirements.txt └── scripts │ └── dbInitialize.py ├── Flask-19-socketio ├── run.py └── templates │ └── index.html ├── Flask-20-apscheduler ├── run.py ├── run1.py └── run2.py ├── Flask-21-favicon ├── app.py ├── static │ └── favicon.ico └── templates │ └── index.html ├── Flask-22-opencv-rtsp-streaming ├── app.py └── templates │ └── index.html ├── Flask-23-ThreadPoolExecutor └── app.py ├── Flask-24-转发请求 └── app.py ├── Flask-25-接收多文件 └── app.py ├── Flask-26-executor └── app.py ├── Flask-27-接收和发送json ├── app.py └── request.py ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /Flask-02/run.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | # 创建Flask对象 4 | app = Flask(__name__) 5 | 6 | 7 | @app.route('/') 8 | def index(): 9 | return "Hello, flask!" 10 | 11 | 12 | if __name__ == '__main__': 13 | app.run(debug=True) -------------------------------------------------------------------------------- /Flask-03-route/run1.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | 5 | 6 | @app.route('/home') 7 | def index(): 8 | return "Welcome to home!" 9 | 10 | 11 | if __name__ == '__main__': 12 | app.run(debug=True) -------------------------------------------------------------------------------- /Flask-03-route/run2.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | 5 | 6 | @app.route('/home/') 7 | def index(name): 8 | return f"Welcome to home!{name}" 9 | 10 | 11 | if __name__ == '__main__': 12 | app.run(debug=True) -------------------------------------------------------------------------------- /Flask-03-route/run3.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | 5 | 6 | @app.route('/home/') 7 | def index(age): 8 | return 'Age={}'.format(age) 9 | 10 | 11 | if __name__ == '__main__': 12 | app.run(debug=True) -------------------------------------------------------------------------------- /Flask-03-route/run4.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | 4 | app = Flask(__name__) 5 | 6 | 7 | def index(): 8 | return 'Hello flask!' 9 | 10 | app.add_url_rule('/', "index", index) 11 | 12 | 13 | if __name__ == '__main__': 14 | app.run(debug=True) -------------------------------------------------------------------------------- /Flask-04-templates/1/run.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template 2 | 3 | app = Flask(__name__) 4 | 5 | 6 | @app.route('/') 7 | def index(): 8 | return render_template('index.html') 9 | 10 | 11 | if __name__ == '__main__': 12 | app.run(debug=True) -------------------------------------------------------------------------------- /Flask-04-templates/1/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Index 6 | 7 | 8 |

Hello flask!

9 | 10 | -------------------------------------------------------------------------------- /Flask-04-templates/2/run.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template 2 | 3 | app = Flask(__name__) 4 | 5 | 6 | @app.route('/') 7 | def index(name): 8 | return render_template('index.html', name=name) 9 | 10 | 11 | if __name__ == '__main__': 12 | app.run(debug=True) -------------------------------------------------------------------------------- /Flask-04-templates/2/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Index 6 | 7 | 8 |

Hello {{ name }}!

9 | 10 | -------------------------------------------------------------------------------- /Flask-05-get-post/get/run.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request 2 | 3 | app = Flask(__name__) 4 | 5 | 6 | @app.route('/', methods=['GET']) 7 | def index(): 8 | username = request.args.get('username') 9 | password = request.args.get('password') 10 | if username == "xugaoxiang" and password == "xugaoxiang": 11 | return f"Welcome {username}" 12 | else: 13 | return f"Welcome!" 14 | 15 | 16 | if __name__ == '__main__': 17 | app.run(debug=True) -------------------------------------------------------------------------------- /Flask-05-get-post/get/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | GET and POST 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 |
Name
Password
22 |
23 | 24 | -------------------------------------------------------------------------------- /Flask-05-get-post/post/run.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request 2 | 3 | app = Flask(__name__) 4 | 5 | 6 | @app.route('/', methods=['POST']) 7 | def index(): 8 | username = request.form['username'] 9 | password = request.form['password'] 10 | if username == "xugaoxiang" and password == "xugaoxiang": 11 | return f"Welcome {username}" 12 | else: 13 | return f"Welcome!" 14 | 15 | 16 | if __name__ == '__main__': 17 | app.run(debug=True) -------------------------------------------------------------------------------- /Flask-05-get-post/post/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | GET and POST 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 |
Name
Password
22 |
23 | 24 | -------------------------------------------------------------------------------- /Flask-06-cookie-session/cookie/run.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, make_response 2 | 3 | app = Flask(__name__) 4 | 5 | 6 | @app.route('/cookie', methods=['GET']) 7 | def cookie(): 8 | 9 | resp = make_response("Cookie") 10 | resp.set_cookie('name', 'xugaoxiang') 11 | return resp 12 | 13 | 14 | if __name__ == '__main__': 15 | app.run(debug=True) -------------------------------------------------------------------------------- /Flask-06-cookie-session/session/run.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, make_response, session 2 | 3 | app = Flask(__name__) 4 | app.secret_key = "test" 5 | 6 | 7 | @app.route('/session', methods=['GET']) 8 | def sess(): 9 | 10 | resp = make_response("Session.Get Value") 11 | session['name'] = 'xugaoxiang' 12 | return resp 13 | 14 | 15 | @app.route('/getValue') 16 | def getValue(): 17 | if 'name' in session: 18 | name = session['name'] 19 | return render_template('getvalue.html', name=name) 20 | 21 | 22 | if __name__ == '__main__': 23 | app.run(debug=True) -------------------------------------------------------------------------------- /Flask-06-cookie-session/session/templates/getvalue.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | GetValue 6 | 7 | 8 |

Session value: {{ name }}

9 | 10 | -------------------------------------------------------------------------------- /Flask-07-upload/run.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, request 2 | 3 | app = Flask(__name__) 4 | 5 | 6 | @app.route('/') 7 | def index(): 8 | return render_template('index.html') 9 | 10 | 11 | @app.route('/success', methods=['POST']) 12 | def success(): 13 | if request.method == 'POST': 14 | f = request.files['file'] 15 | f.save(f.filename) 16 | return render_template('success.html', name=f.filename) 17 | 18 | 19 | if __name__ == '__main__': 20 | app.run(debug=True) -------------------------------------------------------------------------------- /Flask-07-upload/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | upload 6 | 7 | 8 |
9 | 10 | 11 |
12 | 13 | -------------------------------------------------------------------------------- /Flask-07-upload/templates/success.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Success 6 | 7 | 8 |

File uploaded successfully!

9 |

File Name: {{name}}

10 | 11 | -------------------------------------------------------------------------------- /Flask-08-redirect/run.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, request, redirect, url_for 2 | 3 | app = Flask(__name__) 4 | 5 | 6 | @app.route('/login') 7 | def login(): 8 | return render_template('login.html') 9 | 10 | 11 | @app.route('/validate', methods=['POST']) 12 | def validate(): 13 | if request.method == 'POST' and request.form['email'] == 'test@gmail.com' and request.form['password'] == 'test': 14 | return redirect(url_for('success')) 15 | 16 | return redirect(url_for('login')) 17 | 18 | 19 | @app.route('/success') 20 | def success(): 21 | return 'Logged in successfully.' 22 | 23 | 24 | if __name__ == '__main__': 25 | app.run(debug=True) -------------------------------------------------------------------------------- /Flask-08-redirect/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Login 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 |
Email
Password
22 |
23 | 24 | -------------------------------------------------------------------------------- /Flask-09-flash/run.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, request, redirect, url_for, flash 2 | 3 | app = Flask(__name__) 4 | app.secret_key = "xxx" 5 | 6 | 7 | @app.route('/') 8 | def index(): 9 | return render_template('index.html') 10 | 11 | 12 | @app.route('/login', methods=['GET', 'POST']) 13 | def login(): 14 | error = None 15 | if request.method == "POST": 16 | if request.form['email'] != 'test@gmail.com' or request.form['password'] != 'test': 17 | error = "Invalid account." 18 | else: 19 | flash("Login successfully") 20 | return redirect(url_for('index')) 21 | 22 | return render_template('login.html', error=error) 23 | 24 | 25 | if __name__ == '__main__': 26 | app.run(debug=True) -------------------------------------------------------------------------------- /Flask-09-flash/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Index 6 | 7 | 8 | {% with messages = get_flashed_messages() %} 9 | {% if messages %} 10 | {% for message in messages %} 11 |

{{ message }}

12 | {% endfor %} 13 | {% endif %} 14 | {% endwith %} 15 | 16 |

Welcome!

17 | login 18 | 19 | -------------------------------------------------------------------------------- /Flask-09-flash/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Login 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 |
Email
Password
22 |
23 | 24 | {% if error %} 25 |

Error: {{ error }}

26 | {% endif %} 27 | 28 | -------------------------------------------------------------------------------- /Flask-10-wtf/run.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, request 2 | from flask_wtf import FlaskForm 3 | from wtforms import SubmitField, StringField, PasswordField 4 | from wtforms.validators import DataRequired, EqualTo, Length, Email 5 | 6 | app = Flask(__name__) 7 | app.secret_key = "xxx" 8 | 9 | 10 | # 使用WTF实现表单,自定义一个表单类 11 | class RegisterForm(FlaskForm): 12 | username = StringField(label='用户名: ', validators=[DataRequired()]) 13 | email = StringField(label='邮箱: ', validators=[DataRequired(), Email(message='邮箱格式错误')]) 14 | password = PasswordField(label='密码: ', validators=[DataRequired(), Length(6, 16, message='密码格式错误')]) 15 | password2 = PasswordField(label='确认密码: ', validators=[DataRequired(), Length(6, 16, message='密码格式错误'), 16 | EqualTo('password', message='密码不一致')]) 17 | submit = SubmitField(label='注册') 18 | 19 | 20 | @app.route('/', methods=['GEt', 'POST']) 21 | def register(): 22 | 23 | register_form = RegisterForm() 24 | 25 | if request.method == 'POST': 26 | if register_form.validate_on_submit(): 27 | username = request.form.get('username') 28 | email = request.form.get('email') 29 | password = request.form.get('password') 30 | password2 = request.form.get('password2') 31 | 32 | if username == 'xgx' and email == 'test@gmail.com': 33 | # 进入这里就表示表单验证成功 34 | return 'Register success, username: {}, email: {}, password: {}'.format(username, email, password) 35 | else: 36 | return 'Error' 37 | else: 38 | return 'Invalid' 39 | 40 | # 把实例化后的register_form传入到页面register.html中 41 | return render_template('register.html', form=register_form) 42 | 43 | 44 | if __name__ == '__main__': 45 | app.run(debug=True) 46 | -------------------------------------------------------------------------------- /Flask-10-wtf/templates/register.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Register 6 | 7 | 8 | 9 |
10 | {{ form.csrf_token() }} 11 | {{ form.username.label }} {{ form.username }}
12 | {{ form.email.label }} {{ form.email }}
13 | {{ form.password.label }} {{ form.password }}
14 | {{ form.password2.label }} {{ form.password2 }}
15 | {{ form.submit }} 16 |
17 | 18 | 19 | -------------------------------------------------------------------------------- /Flask-11-sqlalchemy/run.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, request 2 | from flask_wtf import FlaskForm 3 | from wtforms import SubmitField, StringField, PasswordField 4 | from wtforms.validators import DataRequired, EqualTo, Length, Email 5 | from flask_sqlalchemy import SQLAlchemy 6 | 7 | app = Flask(__name__) 8 | app.secret_key = "xxx" 9 | # 设置数据库URI 10 | app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///member.sqlite3' 11 | app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True 12 | 13 | 14 | # 使用app作为参数实例化一个SQLAlchemy类的对象 15 | db = SQLAlchemy(app) 16 | 17 | # 创建会员模型 18 | class Member(db.Model): 19 | id = db.Column('id', db.Integer, primary_key=True, autoincrement=True) 20 | username = db.Column(db.String(45), unique=True) 21 | email = db.Column(db.String(45)) 22 | password = db.Column(db.String(128)) 23 | 24 | def __init__(self, username, email, password): 25 | self.username = username 26 | self.email = email 27 | self.password = password 28 | 29 | 30 | # 创建数据表 31 | db.create_all() 32 | 33 | 34 | # 使用WTF实现表单,自定义一个表单类 35 | class RegisterForm(FlaskForm): 36 | username = StringField(label='用户名: ', validators=[DataRequired()]) 37 | email = StringField(label='邮箱: ', validators=[DataRequired(), Email(message='邮箱格式错误')]) 38 | password = PasswordField(label='密码: ', validators=[DataRequired(), Length(6, 16, message='密码格式错误')]) 39 | password2 = PasswordField(label='确认密码: ', validators=[DataRequired(), Length(6, 16, message='密码格式错误'), EqualTo('password', message='密码不一致')]) 40 | submit = SubmitField(label='注册') 41 | 42 | 43 | @app.route('/', methods=['GEt', 'POST']) 44 | def register(): 45 | register_form = RegisterForm() 46 | 47 | if request.method == 'POST': 48 | if register_form.validate_on_submit(): 49 | username = request.form.get('username') 50 | email = request.form.get('email') 51 | password = request.form.get('password') 52 | 53 | # 判断数据库中是否已经存在相同的用户名 54 | if Member.query.filter_by(username=username).all(): 55 | return 'Invalid username' 56 | 57 | # 构建数据库记录并写入数据库 58 | member = Member(username=username, email=email, password=password) 59 | db.session.add(member) 60 | db.session.commit() 61 | 62 | return 'Register success.' 63 | 64 | else: 65 | return 'Invalid' 66 | 67 | # 把实例化后的register_form传入到页面register.html中 68 | return render_template('register.html', form=register_form) 69 | 70 | 71 | if __name__ == '__main__': 72 | app.run(debug=True) 73 | -------------------------------------------------------------------------------- /Flask-11-sqlalchemy/templates/register.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Register 6 | 7 | 8 | 9 |
10 | {{ form.csrf_token() }} 11 | {{ form.username.label }} {{ form.username }}
12 | {{ form.email.label }} {{ form.email }}
13 | {{ form.password.label }} {{ form.password }}
14 | {{ form.password2.label }} {{ form.password2 }}
15 | {{ form.submit }} 16 |
17 | 18 | 19 | -------------------------------------------------------------------------------- /Flask-12-deployment/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xugaoxiang/FlaskTutorial/16fa445ff2c6631cdb5e9206bd4f95a9aa2cfc5a/Flask-12-deployment/README.md -------------------------------------------------------------------------------- /Flask-13-structure/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xugaoxiang/FlaskTutorial/16fa445ff2c6631cdb5e9206bd4f95a9aa2cfc5a/Flask-13-structure/README.md -------------------------------------------------------------------------------- /Flask-14-blueprint/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xugaoxiang/FlaskTutorial/16fa445ff2c6631cdb5e9206bd4f95a9aa2cfc5a/Flask-14-blueprint/README.md -------------------------------------------------------------------------------- /Flask-14-blueprint/app/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from .views.index import index_blueprint 3 | from . import config 4 | 5 | 6 | def create_app(): 7 | app = Flask(__name__) 8 | app.config.from_object(config) 9 | app.register_blueprint(index_blueprint) 10 | 11 | return app -------------------------------------------------------------------------------- /Flask-14-blueprint/app/config.py: -------------------------------------------------------------------------------- 1 | DEBUG = False -------------------------------------------------------------------------------- /Flask-14-blueprint/app/views/index.py: -------------------------------------------------------------------------------- 1 | from flask import Blueprint 2 | 3 | index_blueprint = Blueprint('index', __name__) 4 | 5 | @index_blueprint.route('/') 6 | def index(): 7 | return "Hello blueprint." -------------------------------------------------------------------------------- /Flask-14-blueprint/manage.py: -------------------------------------------------------------------------------- 1 | from app import create_app 2 | 3 | if __name__ == '__main__': 4 | app = create_app() 5 | app.run(use_reloader=True, port=5000) -------------------------------------------------------------------------------- /Flask-14-blueprint/requirements.txt: -------------------------------------------------------------------------------- 1 | flask -------------------------------------------------------------------------------- /Flask-15-logging/manage.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, jsonify 2 | 3 | app = Flask(__name__) 4 | 5 | @app.route('/login', methods=['POST']) 6 | def login(): 7 | app.logger.debug(f'login success.') 8 | return jsonify( 9 | { 10 | "code": 200 11 | } 12 | ) 13 | 14 | if __name__ == '__main__': 15 | app.run(debug=True, port=5000) -------------------------------------------------------------------------------- /Flask-15-logging/requirements.txt: -------------------------------------------------------------------------------- 1 | flask -------------------------------------------------------------------------------- /Flask-16-restful/manage.py: -------------------------------------------------------------------------------- 1 | import logging.config 2 | from flask import Flask, jsonify 3 | from flask_restful import Api, Resource, reqparse 4 | 5 | logging.config.dictConfig( 6 | { 7 | "version": 1, 8 | "disable_existing_loggers": False, 9 | "formatters": { 10 | "simple": {"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"} 11 | }, 12 | "handlers": { 13 | "console": { 14 | "class": "logging.StreamHandler", 15 | "level": "DEBUG", 16 | "formatter": "simple", 17 | "stream": "ext://sys.stdout", 18 | }, 19 | "info_file_handler": { 20 | "class": "logging.handlers.RotatingFileHandler", 21 | "level": "INFO", 22 | "formatter": "simple", 23 | "filename": "info.log", 24 | "maxBytes": 10485760, 25 | "backupCount": 50, 26 | "encoding": "utf8", 27 | }, 28 | "error_file_handler": { 29 | "class": "logging.handlers.RotatingFileHandler", 30 | "level": "ERROR", 31 | "formatter": "simple", 32 | "filename": "errors.log", 33 | "maxBytes": 10485760, 34 | "backupCount": 20, 35 | "encoding": "utf8", 36 | }, 37 | "debug_file_handler": { 38 | "class": "logging.handlers.RotatingFileHandler", 39 | "level": "DEBUG", 40 | "formatter": "simple", 41 | "filename": "debug.log", 42 | "maxBytes": 10485760, 43 | "backupCount": 50, 44 | "encoding": "utf8", 45 | }, 46 | }, 47 | "loggers": { 48 | "my_module": {"level": "ERROR", "handlers": ["console"], "propagate": "no"} 49 | }, 50 | "root": { 51 | "level": "DEBUG", 52 | "handlers": ["error_file_handler", "debug_file_handler"], 53 | }, 54 | } 55 | ) 56 | 57 | USERS = [ 58 | {"name": "zhangsan"}, 59 | {"name": "lisi"}, 60 | {"name": "wangwu"}, 61 | {"name": "zhaoliu"} 62 | ] 63 | 64 | class Users(Resource): 65 | def __init__(self, **kwargs): 66 | self.logger = kwargs.get('logger') 67 | 68 | def get(self): 69 | return jsonify(USERS) 70 | 71 | def post(self): 72 | args = reqparse.RequestParser() \ 73 | .add_argument('name', type=str, location='json', required=True, help="名字不能为空") \ 74 | .parse_args() 75 | 76 | self.logger.debug(args) 77 | 78 | if args['name'] not in USERS: 79 | USERS.append({"name": args['name']}) 80 | 81 | return jsonify(USERS) 82 | 83 | def delete(self): 84 | USERS = [] 85 | return jsonify(USERS) 86 | 87 | 88 | class UserId(Resource): 89 | def __init__(self, **kwargs): 90 | self.logger = kwargs.get("logger") 91 | 92 | def get(self, userid): 93 | return jsonify( 94 | {"name": USERS[int(userid)].get("name")} 95 | ) 96 | 97 | 98 | app = Flask(__name__) 99 | api = Api(app, default_mediatype="application/json") 100 | 101 | api.add_resource(Users, '/users', resource_class_kwargs={ 102 | "logger": logging.getLogger('/Users') 103 | }) 104 | 105 | api.add_resource(UserId, '/user/', resource_class_kwargs={ 106 | "logger": logging.getLogger('/UserId') 107 | }) 108 | 109 | app.run(host='0.0.0.0', port=5001, use_reloader=True, debug=True) -------------------------------------------------------------------------------- /Flask-16-restful/requirements.txt: -------------------------------------------------------------------------------- 1 | flask 2 | flask-restful -------------------------------------------------------------------------------- /Flask-17-cors/manage.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, jsonify 2 | from flask_restful import Api, Resource, reqparse 3 | from flask_cors import CORS 4 | 5 | USERS = [ 6 | {"name": "zhangsan"}, 7 | {"name": "lisi"}, 8 | {"name": "wangwu"}, 9 | {"name": "zhaoliu"} 10 | ] 11 | 12 | class Users(Resource): 13 | def get(self): 14 | return jsonify(USERS) 15 | 16 | def post(self): 17 | args = reqparse.RequestParser() \ 18 | .add_argument('name', type=str, location='json', required=True, help="名字不能为空") \ 19 | .parse_args() 20 | 21 | self.logger.debug(args) 22 | 23 | if args['name'] not in USERS: 24 | USERS.append({"name": args['name']}) 25 | 26 | return jsonify(USERS) 27 | 28 | 29 | app = Flask(__name__) 30 | CORS(app) 31 | api = Api(app, default_mediatype="application/json") 32 | 33 | api.add_resource(Users, '/users') 34 | 35 | app.run(host='0.0.0.0', port=5001, use_reloader=True, debug=True) -------------------------------------------------------------------------------- /Flask-17-cors/requirements.txt: -------------------------------------------------------------------------------- 1 | flask 2 | flask-cors 3 | flask-restful -------------------------------------------------------------------------------- /Flask-18-jwt-extended/app/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask_sqlalchemy import SQLAlchemy 3 | from flask_jwt_extended import JWTManager 4 | from flask_restful import Api 5 | from flask_cors import CORS 6 | from app.config import Config 7 | 8 | db = SQLAlchemy() 9 | jwt = JWTManager() 10 | api = Api(default_mediatype="application/json") 11 | 12 | 13 | def create_app(config=Config): 14 | app = Flask(__name__) 15 | app.config.from_object(config) 16 | db.init_app(app) 17 | jwt.init_app(app) 18 | from app import routes 19 | api.init_app(app) 20 | CORS(app) 21 | 22 | return app 23 | -------------------------------------------------------------------------------- /Flask-18-jwt-extended/app/config.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | class Config: 5 | # flask 6 | DEBUG = os.environ.get('FLASK_DEBUG') or True 7 | 8 | # database 9 | SQLALCHEMY_DATABASE_URI = os.environ.get('SQLALCHEMY_DATABASE_URI') or 'mysql+pymysql://root:toor@localhost/flask' 10 | SQLALCHEMY_TRACK_MODIFICATIONS = True 11 | 12 | # jwt 13 | JWT_SECRET_KEY = os.environ.get('JWT_SECRET_KEY') or 'jwt-key' 14 | JWT_COOKIE_CSRF_PROTECT = True 15 | JWT_CSRF_CHECK_FORM = True 16 | JWT_ACCESS_TOKEN_EXPIRES = os.environ.get('JWT_ACCESS_TOKEN_EXPIRES') or 3600 17 | PROPAGATE_EXCEPTIONS = True 18 | -------------------------------------------------------------------------------- /Flask-18-jwt-extended/app/controller.py: -------------------------------------------------------------------------------- 1 | from flask import jsonify 2 | from flask_restful import Resource, reqparse 3 | from flask_jwt_extended import create_access_token, jwt_required 4 | from app.models import User 5 | from app import jwt 6 | 7 | 8 | @jwt.expired_token_loader 9 | def expired_token_callback(): 10 | return jsonify({ 11 | 'code': 201, 12 | 'message': "token expired" 13 | }) 14 | 15 | 16 | class Login(Resource): 17 | def __init__(self, **kwargs): 18 | self.logger = kwargs.get('logger') 19 | 20 | def post(self): 21 | code = None 22 | message = None 23 | token = None 24 | userid = None 25 | 26 | args = reqparse.RequestParser() \ 27 | .add_argument('username', type=str, location='json', required=True, help="用户名不能为空") \ 28 | .add_argument("password", type=str, location='json', required=True, help="密码不能为空") \ 29 | .parse_args() 30 | 31 | flag_user_exist, flag_password_correct, user = User.authenticate(args['username'], args['password']) 32 | if not flag_user_exist: 33 | code = 201 34 | message = "user not exist" 35 | elif not flag_password_correct: 36 | code = 202 37 | message = "wrong password" 38 | else: 39 | code = 200 40 | message = "success" 41 | token = create_access_token(identity=user.username) 42 | userid = user.id 43 | 44 | return jsonify({ 45 | "code": code, 46 | "message": message, 47 | "token": token, 48 | "userid": userid 49 | }) 50 | 51 | 52 | class Users(Resource): 53 | def __init__(self, **kwargs): 54 | self.logger = kwargs.get('logger') 55 | 56 | @jwt_required 57 | def get(self): 58 | users_list = [] 59 | users = User.get_users() 60 | 61 | for user in users: 62 | users_list.append({"userid": user.id, "username": user.username}) 63 | 64 | return jsonify({ 65 | "code": 200, 66 | "message": "success", 67 | "users": users_list 68 | }) 69 | -------------------------------------------------------------------------------- /Flask-18-jwt-extended/app/models.py: -------------------------------------------------------------------------------- 1 | from app import db 2 | 3 | 4 | class User(db.Model): 5 | id = db.Column(db.Integer, primary_key=True, autoincrement=True) 6 | username = db.Column(db.String(45), nullable=False, unique=True) 7 | password = db.Column(db.String(128), nullable=False) 8 | active = db.Column(db.Boolean, default=True, nullable=False) 9 | 10 | def __init__(self, username=None, password=None, active=True): 11 | self.username = username 12 | self.password = password 13 | self.active = active 14 | 15 | @staticmethod 16 | def is_user_exist(username): 17 | return User.query.filter(User.username == username).first() 18 | 19 | @staticmethod 20 | def authenticate(username, password): 21 | flag_user_exist = True 22 | flag_password_correct = True 23 | 24 | user = User.query.filter(User.username == username).first() 25 | if user and user.active == 1: 26 | if not user.password == password: 27 | flag_password_correct = False 28 | else: 29 | flag_user_exist = False 30 | 31 | return flag_user_exist, flag_password_correct, user 32 | 33 | @staticmethod 34 | def get_users(): 35 | return User.query.filter(User.active == 1).all() 36 | 37 | @staticmethod 38 | def insert_user(user): 39 | db.session.add(user) 40 | db.session.commit() 41 | 42 | @staticmethod 43 | def update_user(): 44 | db.session.commit() 45 | 46 | @staticmethod 47 | def deactivate_user(): 48 | db.session.commit() 49 | -------------------------------------------------------------------------------- /Flask-18-jwt-extended/app/routes.py: -------------------------------------------------------------------------------- 1 | import logging.config 2 | from app import api 3 | from app.controller import Login, Users 4 | 5 | logging.config.dictConfig( 6 | { 7 | "version": 1, 8 | "disable_existing_loggers": False, 9 | "formatters": { 10 | "simple": {"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"} 11 | }, 12 | "handlers": { 13 | "console": { 14 | "class": "logging.StreamHandler", 15 | "level": "DEBUG", 16 | "formatter": "simple", 17 | "stream": "ext://sys.stdout", 18 | }, 19 | "info_file_handler": { 20 | "class": "logging.handlers.RotatingFileHandler", 21 | "level": "INFO", 22 | "formatter": "simple", 23 | "filename": "info.log", 24 | "maxBytes": 10485760, 25 | "backupCount": 50, 26 | "encoding": "utf8", 27 | }, 28 | "error_file_handler": { 29 | "class": "logging.handlers.RotatingFileHandler", 30 | "level": "ERROR", 31 | "formatter": "simple", 32 | "filename": "errors.log", 33 | "maxBytes": 10485760, 34 | "backupCount": 20, 35 | "encoding": "utf8", 36 | }, 37 | "debug_file_handler": { 38 | "class": "logging.handlers.RotatingFileHandler", 39 | "level": "DEBUG", 40 | "formatter": "simple", 41 | "filename": "debug.log", 42 | "maxBytes": 10485760, 43 | "backupCount": 50, 44 | "encoding": "utf8", 45 | }, 46 | }, 47 | "loggers": { 48 | "my_module": {"level": "ERROR", "handlers": ["console"], "propagate": "no"} 49 | }, 50 | "root": { 51 | "level": "DEBUG", 52 | "handlers": ["error_file_handler", "debug_file_handler"], 53 | }, 54 | } 55 | ) 56 | 57 | api.add_resource(Login, '/login', resource_class_kwargs={ 58 | 'logger': logging.getLogger('/login') 59 | }) 60 | 61 | api.add_resource(Users, '/users', resource_class_kwargs={ 62 | 'logger': logging.getLogger('/users') 63 | }) 64 | -------------------------------------------------------------------------------- /Flask-18-jwt-extended/manage.py: -------------------------------------------------------------------------------- 1 | from app import create_app 2 | 3 | app = create_app() 4 | 5 | if __name__ == '__main__': 6 | app.run(host="0.0.0.0", port=5000) 7 | -------------------------------------------------------------------------------- /Flask-18-jwt-extended/requirements.txt: -------------------------------------------------------------------------------- 1 | flask 2 | flask-restful 3 | flask-jwt-extended 4 | flask_sqlalchemy 5 | flask_cors 6 | pymysql -------------------------------------------------------------------------------- /Flask-18-jwt-extended/scripts/dbInitialize.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | from flask import Flask 3 | from flask_sqlalchemy import SQLAlchemy 4 | 5 | app = Flask(__name__) 6 | app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:toor@localhost/flask' 7 | app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True 8 | db = SQLAlchemy(app) 9 | 10 | 11 | class User(db.Model): 12 | id = db.Column(db.Integer, primary_key=True, autoincrement=True) 13 | username = db.Column(db.String(45), nullable=False, unique=True) 14 | password = db.Column(db.String(128), nullable=False) 15 | active = db.Column(db.Boolean, default=True, nullable=False) 16 | 17 | def __init__(self, username=None, password=None, active=True): 18 | self.username = username 19 | self.password = password 20 | self.active = True 21 | 22 | 23 | try: 24 | db.create_all() 25 | 26 | hash_password = hashlib.sha256(b"123456").hexdigest() 27 | user = User(username="admin@gmail.com", password=hash_password) 28 | db.session.add(user) 29 | db.session.commit() 30 | except: 31 | pass 32 | 33 | db.session.close() -------------------------------------------------------------------------------- /Flask-19-socketio/run.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template 2 | from flask_socketio import SocketIO, emit 3 | 4 | 5 | app = Flask(__name__) 6 | app.config['SECRET_KEY'] = 'secret_key' 7 | 8 | socketio = SocketIO() 9 | socketio.init_app(app, cors_allowed_origins='*') 10 | 11 | name_space = '/dcenter' 12 | 13 | 14 | @app.route('/') 15 | def index(): 16 | return render_template('index.html') 17 | 18 | 19 | @app.route('/push') 20 | def push_once(): 21 | event_name = 'dcenter' 22 | broadcasted_data = {'data': "test message!"} 23 | socketio.emit(event_name, broadcasted_data, broadcast=False, namespace=name_space) 24 | return 'done!' 25 | 26 | 27 | @socketio.on('connect', namespace=name_space) 28 | def connected_msg(): 29 | print('client connected.') 30 | 31 | 32 | @socketio.on('disconnect', namespace=name_space) 33 | def disconnect_msg(): 34 | print('client disconnected.') 35 | 36 | 37 | @socketio.on('my_event', namespace=name_space) 38 | def mtest_message(message): 39 | print(message) 40 | emit('my_response', 41 | {'data': message['data'], 'count': 1}) 42 | 43 | 44 | if __name__ == '__main__': 45 | 46 | socketio.run(app, host='0.0.0.0', port=5000, debug=True) -------------------------------------------------------------------------------- /Flask-19-socketio/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SocketIO Demo 6 | 7 | 8 | 9 | 10 | 11 |

Demo of SocketIO

12 |
13 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Flask-20-apscheduler/run.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask_apscheduler import APScheduler 3 | 4 | 5 | class Config(object): 6 | JOBS = [ 7 | { 8 | 'id': 'job1', 9 | 'func': 'run:add', 10 | 'args': (1, 2), 11 | 'trigger': 'interval', 12 | 'seconds': 3 13 | } 14 | ] 15 | 16 | SCHEDULER_API_ENABLED = True 17 | 18 | 19 | def add(a, b): 20 | print(a+b) 21 | 22 | 23 | if __name__ == '__main__': 24 | app = Flask(__name__) 25 | app.config.from_object(Config()) 26 | 27 | scheduler = APScheduler() 28 | scheduler.init_app(app) 29 | scheduler.start() 30 | 31 | app.run() -------------------------------------------------------------------------------- /Flask-20-apscheduler/run1.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask_apscheduler import APScheduler 3 | 4 | 5 | class Config(object): 6 | SCHEDULER_API_ENABLED = True 7 | 8 | 9 | scheduler = APScheduler() 10 | 11 | 12 | @scheduler.task('interval', id='do_job_1', seconds=30) 13 | def job1(): 14 | print('Job 1 executed') 15 | 16 | 17 | # cron examples 18 | @scheduler.task('cron', id='do_job_2', minute='*') 19 | def job2(): 20 | print('Job 2 executed') 21 | 22 | 23 | @scheduler.task('cron', id='do_job_3', week='*', day_of_week='sun') 24 | def job3(): 25 | print('Job 3 executed') 26 | 27 | 28 | if __name__ == '__main__': 29 | app = Flask(__name__) 30 | app.config.from_object(Config()) 31 | 32 | scheduler.init_app(app) 33 | scheduler.start() 34 | 35 | app.run() -------------------------------------------------------------------------------- /Flask-20-apscheduler/run2.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask_apscheduler import APScheduler 3 | from flask_apscheduler.auth import HTTPBasicAuth 4 | 5 | 6 | class Config(object): 7 | JOBS = [ 8 | { 9 | 'id': 'job1', 10 | 'func': 'run2:add', 11 | 'args': (1, 2), 12 | 'trigger': 'interval', 13 | 'seconds': 3 14 | } 15 | ] 16 | 17 | SCHEDULER_API_ENABLED = True 18 | SCHEDULER_AUTH = HTTPBasicAuth() 19 | 20 | 21 | def add(a, b): 22 | print(a+b) 23 | 24 | 25 | if __name__ == '__main__': 26 | app = Flask(__name__) 27 | app.config.from_object(Config()) 28 | 29 | scheduler = APScheduler() 30 | # it is also possible to set the authentication directly 31 | # scheduler.auth = HTTPBasicAuth() 32 | scheduler.init_app(app) 33 | scheduler.start() 34 | 35 | @scheduler.authenticate 36 | def authenticate(auth): 37 | return auth['username'] == 'guest' and auth['password'] == 'guest' 38 | 39 | app.run() 40 | -------------------------------------------------------------------------------- /Flask-21-favicon/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template 2 | 3 | app = Flask(__name__) 4 | 5 | 6 | @app.route('/') 7 | def index(): 8 | return render_template('index.html') 9 | 10 | 11 | if __name__ == '__main__': 12 | app.run() 13 | -------------------------------------------------------------------------------- /Flask-21-favicon/static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xugaoxiang/FlaskTutorial/16fa445ff2c6631cdb5e9206bd4f95a9aa2cfc5a/Flask-21-favicon/static/favicon.ico -------------------------------------------------------------------------------- /Flask-21-favicon/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Favicon 7 | 8 | 9 |

Hello favicon

10 | 11 | -------------------------------------------------------------------------------- /Flask-22-opencv-rtsp-streaming/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, Response 2 | import cv2 3 | 4 | app = Flask(__name__) 5 | 6 | # camera = cv2.VideoCapture('rtsp://admin:admin@172.21.182.12:554/cam/realmonitor?channel=1&subtype=1') 7 | # camera = cv2.VideoCapture('test.mp4') 8 | camera = cv2.VideoCapture(0) 9 | 10 | 11 | def gen_frames(): 12 | while True: 13 | success, frame = camera.read() 14 | if not success: 15 | break 16 | else: 17 | ret, buffer = cv2.imencode('.jpg', frame) 18 | frame = buffer.tobytes() 19 | yield (b'--frame\r\n' 20 | b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') # concat frame one by one and show result 21 | 22 | 23 | @app.route('/video_start') 24 | def video_start(): 25 | return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame') 26 | 27 | 28 | @app.route('/') 29 | def index(): 30 | return render_template('index.html') 31 | 32 | 33 | if __name__ == '__main__': 34 | app.run(host='0.0.0.0', debug=True) 35 | -------------------------------------------------------------------------------- /Flask-22-opencv-rtsp-streaming/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | 10 | Live Streaming 11 | 12 | 13 |
14 |
15 |
16 |

Live Streaming

17 | 18 |
19 |
20 |
21 | 22 | -------------------------------------------------------------------------------- /Flask-23-ThreadPoolExecutor/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | import time 3 | from concurrent.futures import ThreadPoolExecutor 4 | 5 | executor = ThreadPoolExecutor(2) 6 | 7 | app = Flask(__name__) 8 | 9 | 10 | @app.route('/tasks') 11 | def run_background_tasks(): 12 | # 提交2个任务,一个带参、一个不带参 13 | executor.submit(background_task1) 14 | executor.submit(background_task2, 'hello', 'future') 15 | return 'tasks started in background!' 16 | 17 | 18 | def background_task1(): 19 | print("background_task1 started!") 20 | time.sleep(10) 21 | print("background_task1 done!") 22 | 23 | 24 | def background_task2(arg1, arg2): 25 | print(f"background_task2 started with args: {arg1} {arg2}!") 26 | time.sleep(5) 27 | print("background_task2 done!") 28 | 29 | 30 | if __name__ == '__main__': 31 | app.run(host='0.0.0.0', port=5000, debug=True) -------------------------------------------------------------------------------- /Flask-24-转发请求/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | import requests 3 | 4 | app = Flask(__name__) 5 | 6 | 7 | @app.route('/') 8 | def index(): 9 | req = requests.get('http://127.0.0.1:5000/proxy') 10 | return req.text 11 | 12 | 13 | @app.route('/proxy') 14 | def proxy(): 15 | return "Hello Flask." 16 | 17 | 18 | if __name__ == '__main__': 19 | app.run('0.0.0.0', debug=True) 20 | -------------------------------------------------------------------------------- /Flask-25-接收多文件/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, jsonify 2 | 3 | app = Flask(__name__) 4 | 5 | 6 | @app.route('/upload', methods=['POST']) 7 | def index(): 8 | image_files = request.files.getlist('image') 9 | video_files = request.files.getlist('video') 10 | 11 | if not image_files and not video_files: 12 | return jsonify({ 13 | "code": -1, 14 | "message": "No upload images or videos." 15 | }) 16 | 17 | for image_file in image_files: 18 | image_file.save(image_file.filename) 19 | 20 | for video_file in video_files: 21 | video_file.save(video_file.filename) 22 | 23 | return jsonify({ 24 | "code": 0, 25 | "message": "upload images and videos success." 26 | }) 27 | 28 | 29 | if __name__ == '__main__': 30 | app.run('0.0.0.0', debug=True, port=5000) 31 | -------------------------------------------------------------------------------- /Flask-26-executor/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask_executor import Executor 3 | 4 | app = Flask(__name__) 5 | 6 | executor = Executor(app) 7 | 8 | 9 | def send_email(recipient, subject, body): 10 | # 模拟邮件发送动作 11 | print('send mail.') 12 | return True 13 | 14 | 15 | def callback(future): 16 | print('callback') 17 | 18 | 19 | @app.route('/signup') 20 | def signup(): 21 | executor.add_default_done_callback(callback) 22 | executor.submit(send_email, "test@gmail.com", "subject", "body") 23 | return "signup done." 24 | 25 | 26 | if __name__ == '__main__': 27 | app.run('0.0.0.0', debug=True, port=5000) 28 | -------------------------------------------------------------------------------- /Flask-27-接收和发送json/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, jsonify, request 2 | 3 | app = Flask(__name__) 4 | 5 | @app.route('/', methods=['POST']) 6 | def post(): 7 | 8 | # 获取请求的json数据 9 | req_json = request.get_json() 10 | print(req_json) 11 | 12 | # 对接收到的数据进行简单处理 13 | if req_json["operatorID"] != "0001": 14 | return jsonify({"error": "error."}) 15 | 16 | dict_ret = {} 17 | dict_ret["responseType"] = 2 18 | dict_ret["status"] = 1000 19 | dict_ret["num"] = 1 20 | dict_ret["MD5"] = "4F3D2A1E" 21 | 22 | return jsonify(dict_ret) 23 | 24 | 25 | if __name__ == '__main__': 26 | 27 | # 启动服务 28 | app.run(host='0.0.0.0', port=80, debug=True) -------------------------------------------------------------------------------- /Flask-27-接收和发送json/request.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | r_json = { 4 | "name": "xgx", 5 | "operatorID":"0001", 6 | "requestType":1, 7 | "num":1 8 | } 9 | 10 | r_headers = {"Content-type": "application/json"} 11 | 12 | r = requests.post('http://127.0.0.1', json=r_json, headers=r_headers) 13 | print(r.status_code) 14 | print(r.json()) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Xu GaoXiang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FlaskTutorial 2 | 3 | 1. [开发环境搭建](https://xugaoxiang.com/2020/03/12/flask-1-intro/) 4 | 2. [第一个Flask应用程序](https://xugaoxiang.com/2020/03/12/flask-2-first-app/) 5 | 3. [路由](https://xugaoxiang.com/2020/03/13/flask-3-routing/) 6 | 4. [模板](https://xugaoxiang.com/2020/03/13/flask-4-template/) 7 | 5. [GET和POST](https://xugaoxiang.com/2020/03/18/flask-5-get-post/) 8 | 6. [Cookie和Session](https://xugaoxiang.com/2020/03/19/flask-6-cookie-session/) 9 | 7. [文件上传](https://xugaoxiang.com/2020/03/20/flask-7-file-upload/) 10 | 8. [重定向](https://xugaoxiang.com/2020/03/23/flask-8-redirect/) 11 | 9. [闪现消息](https://xugaoxiang.com/2020/03/25/flask-9-flash/) 12 | 10. [表单处理](https://xugaoxiang.com/2020/07/09/flask-10-wtf/) 13 | 11. [数据库操作flask-sqlalchemy](https://xugaoxiang.com/2020/07/14/flask-11-sqlalchemy/) 14 | 12. [项目部署](https://xugaoxiang.com/2020/07/21/flask-12-deployment/) 15 | 13. [常用项目结构](https://xugaoxiang.com/2020/08/19/flask-13-project-struture/) 16 | 14. [蓝图](https://xugaoxiang.com/2020/08/24/flask-14-blueprint/) 17 | 15. [日志](https://xugaoxiang.com/2020/08/25/flask-15-logging/) 18 | 16. [RESTful-API](https://xugaoxiang.com/2020/08/26/flask-16-restful-api/) 19 | 17. [flask-cors](https://xugaoxiang.com/2020/08/26/flask-17-cors/) 20 | 18. [flask-jwt-extended](https://xugaoxiang.com/2020/09/01/flask-18-jwt-extended/) 21 | 19. [flask-socketio](https://xugaoxiang.com/2020/10/08/flask-19-socketio/) 22 | 20. [flask-apscheduler](https://xugaoxiang.com/2020/10/08/flask-20-apscheduler/) 23 | 21. [添加favicon](https://xugaoxiang.com/2020/11/11/flask-21-favicon/) 24 | 22. [在浏览器中播放rtsp实时流](https://xugaoxiang.com/2020/11/12/flask-22-opencv-rtsp/) 25 | 23. [简单异步任务](https://xugaoxiang.com/2020/11/16/flask-23-threadpoolexecutor/) 26 | 24. [http请求转发](https://xugaoxiang.com/2020/11/24/flask-24-http-proxy/) 27 | 25. [接收多文件](https://xugaoxiang.com/2021/05/20/flask-25-receive-multiple-files/) 28 | 26. [flask-executor](https://xugaoxiang.com/2021/12/27/flask-26-flask-executor/) 29 | 27. [接收和发送json](https://xugaoxiang.com/2022/12/05/flask-27-json/) --------------------------------------------------------------------------------