当前位置:网站首页>First meet flask
First meet flask
2022-07-28 06:06:00 【Ke Yulong】
Flask Introduce
flask It's a short, compact 、 Highly scalable one Web frame .
Flask It's based on Python Develop and rely on jinja2 Templates and Werkzeug WSGI A micro framework for services , about Werkzeug The essence is Socket Server side , It is used to receive http Request and preprocess the request , Then the trigger Flask frame , Developers based on Flask The framework provides the function to process the request accordingly , And return to the user , If you want to return complex content to users , Need help jinja2 Template to achieve the template processing , namely : Render templates and data , Return the rendered string to the user's browser .
werkzeug
werkzeug It's the realization of WSGI A module of

from werkzeug.wrappers import Request, Response
@Request.application
def hello(request):
return Response('Hello World!')
if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple('localhost', 4000, hello)werkzeug
Flask Easy to use
from flask import Flask
app=Flask(__name__)
@app.route('/index')
def index():
return 'hello world'
if __name__ == '__main__':
app.run()The configuration file
flask The configuration file in is a flask.config.Config object ( Inherit Dictionary ), Default configuration is :
{
'DEBUG': get_debug_flag(default=False), Open or not Debug Pattern
'TESTING': False, Whether to turn on the test mode
'PROPAGATE_EXCEPTIONS': None,
'PRESERVE_CONTEXT_ON_EXCEPTION': None,
'SECRET_KEY': None,
'PERMANENT_SESSION_LIFETIME': timedelta(days=31),
'USE_X_SENDFILE': False,
'LOGGER_NAME': None,
'LOGGER_HANDLER_POLICY': 'always',
'SERVER_NAME': None,
'APPLICATION_ROOT': None,
'SESSION_COOKIE_NAME': 'session',
'SESSION_COOKIE_DOMAIN': None,
'SESSION_COOKIE_PATH': None,
'SESSION_COOKIE_HTTPONLY': True,
'SESSION_COOKIE_SECURE': False,
'SESSION_REFRESH_EACH_REQUEST': True,
'MAX_CONTENT_LENGTH': None,
'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),
'TRAP_BAD_REQUEST_ERRORS': False,
'TRAP_HTTP_EXCEPTIONS': False,
'EXPLAIN_TEMPLATE_LOADING': False,
'PREFERRED_URL_SCHEME': 'http',
'JSON_AS_ASCII': True,
'JSON_SORT_KEYS': True,
'JSONIFY_PRETTYPRINT_REGULAR': True,
'JSONIFY_MIMETYPE': 'application/json',
'TEMPLATES_AUTO_RELOAD': None,
}Configure through classes
app.config.from_object("settings.DevelopmentConfig")
settings.py:
class Config(object):
DEBUG = False
TESTING = False
DATABASE_URI = 'sqlite://:memory:'
class ProductionConfig(Config):
DATABASE_URI = 'mysql://[email protected]/foo'
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
TESTING = Trueimport_name,
static_url_path=None, Set up static files url
static_folder='static', Default static file path
static_host=None,
host_matching=False,
subdomain_matching=False,
template_folder='templates', The default template road strength
instance_path=None,
instance_relative_config=False,
root_path=NoneRouting system
- @app.route('/user/<username>')
- @app.route('/post/<int:post_id>')
- @app.route('/post/<float:post_id>')
- @app.route('/post/<path:path>')
- @app.route('/login', methods=['GET', 'POST'])
Routing system parameters :
@app.route and app.add_url_rule Parameters :
rule, URL The rules
view_func, View function name
defaults=None, The default value is , When URL No parameters in , When the function needs parameters , Use defaults={'k':'v'} Give the function parameters
endpoint=None, name , For reverse generation URL, namely : url_for(' name ')
methods=None, Allowed request mode , Such as :["GET","POST"]
strict_slashes=None, Yes URL final / Is the symbol strictly required ,
Such as :
@app.route('/index',strict_slashes=False),
visit http://www.xx.com/index/ or http://www.xx.com/index All possible
@app.route('/index',strict_slashes=True)
Just visit http://www.xx.com/index
redirect_to=None, Redirect to the specified address
Such as :
@app.route('/index/<int:nid>', redirect_to='/home/<nid>')
or
def func(adapter, nid):
return "/home/888"
@app.route('/index/<int:nid>', redirect_to=func)
subdomain=None, Subdomain access
from flask import Flask, views, url_for
app = Flask(import_name=__name__)
app.config['SERVER_NAME'] = 'wupeiqi.com:5000'
@app.route("/", subdomain="admin")
def static_index():
"""Flask supports static subdomains
This is available at static.your-domain.tld"""
return "static.your-domain.tld"
@app.route("/dynamic", subdomain="<username>")
def username_index(username):
"""Dynamic subdomains are also supported
Try going to user1.your-domain.tld/dynamic"""
return username + ".your-domain.tld"
if __name__ == '__main__':
app.run()
Reverse generation url
- endpoint, Reverse generation URL, Default function name
@app.route('/index/',methods=['GET'],endpoint='n1')
def hello():
url=url_for('n1')
# No definition endpoint
url=url_for('hello')
- Dynamic routing :
@app.route('/index/<int:nid>',methods=['GET','POST'])
def index(nid):
print(nid)
# Dynamic route reverse generation :url_for("index",nid=777)
return "Index" Use of routing system :
FBV
def auth(func):
def inner(*args, **kwargs):
print('before')
result = func(*args, **kwargs)
print('after')
return result
return inner
@app.route('/index.html',methods=['GET','POST'],endpoint='index')
@auth
def index():
return 'Index'
or
def index():
return "Index"
self.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET","POST"])
or
app.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET","POST"])
app.view_functions['index'] = indexCBV
def auth(func):
def inner(*args, **kwargs):
print('before')
result = func(*args, **kwargs)
print('after')
return result
return inner
class IndexView(views.View):
methods = ['GET']
decorators = [auth, ]
def dispatch_request(self):
print('Index')
return 'Index!'
app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint
or
class IndexView(views.MethodView):
methods = ['GET']
decorators = [auth, ]
def get(self):
return 'Index.GET'
def post(self):
return 'Index.POST'
app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpointCustom regular
from flask import Flask,url_for
app = Flask(__name__)
# Step one : Custom class
from werkzeug.routing import BaseConverter
class RegexConverter(BaseConverter):
"""
Customize URL Match regular expression
"""
def __init__(self, map, regex):
super(RegexConverter, self).__init__(map)
self.regex = regex
def to_python(self, value):
"""
When routing matches , After the match is successful, pass the value of the parameter in the view function
:param value:
:return:
"""
return int(value)
def to_url(self, value):
"""
Use url_for Reverse generation URL when , The parameters passed are processed by this method , The value returned is used to generate URL Parameters in
:param value:
:return:
"""
val = super(RegexConverter, self).to_url(value)
return val
# Step two : Add to Converter
app.url_map.converters['reg'] = RegexConverter
"""
1. User sends request
2. flask Regular matching inside
3. call to_python( The result of regular matching ) Method
4. to_python The return value of the method is given to the parameter of the view function
"""
# Step three : Use custom regular
@app.route('/index/<reg("\d+"):nid>')
def index(nid):
print(nid,type(nid))
print(url_for('index',nid=987))
return "index"
if __name__ == '__main__':
app.run()request
from flask import Flask
from flask import request
from flask import render_template
from flask import redirect
from flask import make_response
app = Flask(__name__)
@app.route('/login.html', methods=['GET', "POST"])
def login():
# Request relevant information
# request.method Get request method
# request.args obtain get Method parameters
# request.form obtain form Data submitted by form
# request.values
# request.cookies
# request.headers
# request.path
# request.full_path
# request.script_root
# request.url
# request.base_url
# request.url_root
# request.host_url
# request.host
# request.files
# obj = request.files['the_file_name']
# obj.save('/var/www/uploads/' + secure_filename(f.filename))
return " Content "
if __name__ == '__main__':
app.run() Respond to
# Respond to relevant information
return " character string "
return render_template('html Template path ',**{})
return redirect('/index')
# Customized response head
response = make_response(render_template('index.html'))
response yes flask.wrappers.Response type
response.delete_cookie('key')
response.set_cookie('key', 'value')
response.headers['X-Something'] = 'A value'
return responseTemplates
Basic data type
Basic data type : It can be executed python grammar , Such as :
# Dictionaries
{
{values.get('name')}}
{
{values['name']}}
# list
{
{values[0]}}
# function
{
{func( Transmissible parameters )}}
# loop
{%for item in xxx%}
{%endfor%}
Passing in functions
- django, Automatic execution
- flask, Not automatically Define functions globally
@app.template_global()
def sb(a1, a2):
# {
{sb(1,9)}}
return a1 + a2
@app.template_filter()
def db(a1, a2, a3):
# {
{ 1|db(2,3) }}
return a1 + a2 + a3Templates ( Inherit 、 block 、 Security 、 Macro definition )
Inheritance and block
- Template inheritance
layout.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1> Templates </h1>
{% block content %}{% endblock %}
</body>
</html>
tpl.html
{% extends "layout.html"%}
{% block content %}
{
{users.0}}
{% endblock %} include
include
{% include "form.html" %}
form.html
<form>
asdfasdf
asdfasdf
asdf
asdf
</form>Macro definition
It is equivalent to defining a function ,
It can be called globally
{% macro ccccc(name, type='text', value='') %}
<h1> macro </h1>
<input type="{
{ type }}" name="{
{ name }}" value="{
{ value }}">
<input type="submit" value=" Submit ">
{% endmacro %}
{
{ ccccc('n1') }}
{
{ ccccc('n2') }}Security
Security
- front end : {
{u|safe}}
- Back end : MarkUp("<a></a>")Session
When the request comes :flask Read cookie in session Corresponding value :eyJrMiI6NDU2LCJ1c2VyIjoib2xkYm95,
Decrypt and deserialize the value into a dictionary , Put it in memory for the view function to use .
The view function :
@app.route('/ses')
def ses():
session['k1'] = 123
session['k2'] = 456
del session['k1']
return "Session"
session['xxx'] = 123When the request ends ,flask Will read the value of the dictionary in memory , serialize + encryption , Write to user cookie in .
flash
flash , stay session Store a data in , Read through pop Remove data .
from flask import Flask,flash,get_flashed_messages
@app.route('/page1')
def page1():
flash(' Temporary data storage ','error')
flash('sdfsdf234234','error')
flash('adasdfasdf','info')
return "Session"
@app.route('/page2')
def page2():
print(get_flashed_messages(category_filter=['error']))
return "Session"middleware
call Method when to start ?
- When a user initiates a request , To perform .
Mission : In execution call Before method , Do an operation ,call After the method is executed, do an operation .
class Middleware(object):
def __init__(self,old):
self.old = old
def __call__(self, *args, **kwargs):
ret = self.old(*args, **kwargs)
return ret
if __name__ == '__main__':
app.wsgi_app = Middleware(app.wsgi_app)
app.run()Special ornaments
@before_request
# Before executing the view function ,requset Have to go through (before_request)
@after_request(response)
must :return response
# After executing the view function ,requset Have to go through (after_request)
@after_request/@before_request example
@app.before_request
def x1():
print('before:x1')
return ' roll '
@app.before_request
def xx1():
print('before:xx1')
@app.after_request
def x2(response):
print('after:x2')
return response
@app.after_request
def xx2(response):
print('after:xx2')
return response
@app.route('/index')
def index():
print('index')
return "Index" Uploading … Re upload cancel
@template_global
There are usage methods in the template
@template_filter
There are usage methods in the template
@errorhandler
When something goes wrong , Customize the returned content
@app.errorhandler(404)
def not_found(arg):
#arg error message
print(arg)
return " Did not find "The blueprint
The goal is : Provide a directory structure for developers
1. Create a folder with the same name as the project

2. Create... Under this file __init__.py
from flask import Flask
def create_app():
app = Flask(__name__)
return app3. Create in a directory at the same level as the file manage.py
from crm import create_app
app=create_app()
if __name__ == '__main__':
app.run()4. Create static files and templates for the project

5. The creation of blueprint relationships
user.py
from flask import Blueprint
us =Blueprint('us',__name__)
@us.route('/login')
def login():
return 'login'
@us.route('/logout')
def logout():
return 'logout'__init__.py
from flask import Flask
from .views.user import us
def create_app():
app = Flask(__name__)
app.register_blueprint(us)
return app6. Blueprint prefix +before Method
You can prefix each blueprint , such as 127.0.0.1/admin/xxx/xxx
127.0.0.1/web/xxx/xxx
Add the prefix :
stay __init__.py In the document :
from flask import Flask
from .views.user import us
from .views.account import ac
def create_app():
app = Flask(__name__)
app.register_blueprint(us,url_prefix='/admin')
app.register_blueprint(ac,url_prefix='/web')
return app- stay __init__.py Inside plus @before_request Method all requests will go through
- Add @before_request Then it means that only all requests of the blue drive pass
Example
Session+Flask Implement user login
from flask import Flask,render_template,request,session,redirect
app=Flask(__name__)
#session If you need to use session Need salt .
# In essence, he put cookies in , It's not like django Put it in the database
app.secret_key ='213fdasfa123df'
@app.route('/login',methods=['GET','POST'])
def Login():
if request.method =='GET':
return render_template('login.html')
user=request.form.get('user')
pwd=request.form.get('pwd')
if user=='ming' and pwd=='123':
session['user_info']={'username':user}
return redirect('/index')
return render_template('login.html',error=' Wrong user name or password ')
# return render_template('login.html',**{'error':' Wrong username or password '})
@app.route('/index')
def index():
user_info=session.get('user_info')
if user_info:
return render_template('index.html')
return redirect('/login')
if __name__ == '__main__':
app.run()Student management
@app.route('/index')
def index():
if not session.get('user'):
return redirect(url_for('login'))
return render_template('index.html',stu_dic=STUDENT_DICT)
# Version 2 :
import functools
def auth(func):
@functools.wraps(func)
def inner(*args,**kwargs):
if not session.get('user'):
return redirect(url_for('login'))
ret = func(*args,**kwargs)
return ret
return inner
@app.route('/index')
@auth
def index():
return render_template('index.html',stu_dic=STUDENT_DICT)
# Application scenarios : Few functions need additional functions .
# Version 3 :before_request
@app.before_request
def xxxxxx():
if request.path == '/login':
return None
if session.get('user'):
return None
return redirect('/login')Reproduced in :https://www.cnblogs.com/chenxuming/p/9414731.html
边栏推荐
猜你喜欢

分布式集群架构场景优化解决方案:Session共享问题

At the moment of the epidemic, online and offline travelers are trapped. Can the digital collection be released?

Manually create a simple RPC (< - < -)

高端大气的小程序开发设计有哪些注意点?

幂等性组件

【四】redis持久化(RDB与AOF)

小程序商城制作一个需要多少钱?一般包括哪些费用?

字节Android岗4轮面试,收到 50k*18 Offer,裁员风口下成功破局

Distributed cluster architecture scenario optimization solution: session sharing problem

1:开启慢查询日志 与 找到慢SQL
随机推荐
DataX安装及使用
Chapter 8 aggregate function
数据处理之增删改;约束
Bert的使用方法
mysql多表查询
分布式集群架构场景优化解决方案:分布式调度问题
Kotlin语言现在怎么不火了?你怎么看?
Use Python to encapsulate a tool class that sends mail regularly
Flume installation and use
Spark中的Structured Streaming
Svn incoming content cannot be updated, and submission error: svn: e155015: aborting commit: XXX remains in conflict
XML parsing entity tool class
第七章 单行函数
Record the problems encountered in online capacity expansion server nochange: partition 1 is size 419428319. It cannot be grown
变量,流程控制与游标
Distributed lock redis implementation
微服务架构认知、服务治理-Eureka
MySQL练习题50道+答案
Mysql的两种覆盖表中重复记录的方法
raise RuntimeError(‘DataLoader worker (pid(s) {}) exited unexpectedly‘.format(pids_str))RuntimeErro