当前位置:网站首页>Flask Foundation
Flask Foundation
2022-07-03 06:57:00 【Wu Daxi】
One 、flask install and configure :
1、 Back end
The server +wsgi
+ Framework Program ,flask
Is a framework program
2、 front end
mobile phone APP、 browser 、 Program ( Reptiles )、urllib
、urllib2
、ajax
3、 The core of the framework
Implement routing and view ( Business logic processing );
4、 advantage
dingo It's a heavyweight framework , Many tools and components are provided , Not friendly to late expansion ;
5、flask At the heart of
werkzeug
and jinja2
(jinja2
It can be changed )
6、flask Expansion pack, :
Flask-SQLalchemy: Operating the database ;
Flask-migrate: Manage migration database ;
Flask-Mail: mail ;
Flask-WTF: Forms ;
Flask-script: Insert script ;
Flask-Login: Certified user status ;
Flask-RESTful: Development REST API Tools for ;
Flask-Bootstrap: Integrated front end Twitter Bootstrap frame ;
Flask-Moment: Localization date and time ;
7、 A virtual environment :
cd ~/ : Switch to home directory :
ls -l:
ls -a:
cd .virtualenv:
ls: All the virtual environments
cd flask_py2: Switch to a virtual environment
cd bin: Executable binary ;
cd ..: Return to parent directory ;
cd lib: All installation packages ;
cd site-packages: You can modify the source file in the third-party package
pip list : Check which packages are installed in the current virtual environment
mkvirtualenv shop -p python3: Creating a virtual environment shop, And designate python edition
install python Package time plus sudo, Install into the system environment , Not in a virtual environment ;
Two 、app Object initialization and configuration :
1、 Object initialization
__name__
Indicates the name of the current file , If this file is a startup file ,__name__
by__main__
app=Flask(__name__)
Indicates that the directory where the current file is located is the root directory ,flask
Take the directory where this module is located as the root directory , The default isstatic
As a static Directory , In the root directorytemplates
As a template directory , Ifflask
The parameter passed was not found , such asapp=Flask('idbbkdsbkjabs')
,flask
Will take the current file as the root directory- Flask() Is the initialization parameter of :
import_name:
static_url_path: The default name for accessing static resources , Access in the browser static replace (120.0.0.1:5000/static/index.html Switch to 120.0.0.1:5000/static1/index.html)
static_folder: Directory of static files , Default ‘static’
template_folder: Directory of template files , Default ‘templates’
2、app.run():
For simple test server
app.run(host='0.0.0.0',port=5000) # You can use local ip Address , It can be used again 127.0.0.1 visit , It can be transmitted debug
3、 The configuration file :
- Store value :
(1)app.config.from_pyfile( file name ) # Specify the file name , Find the file name under the current root directory
(2)app.config.from_object( Class name ) # Import from object , The configuration file is encapsulated into classes
(3)app.config['DEBUG']=True # Refers to direct operation config The dictionary object of
- Value
(1)app.config.get('')
(2)app.config['']
(3)current_app.config['']
3、 ... and 、 Routing of view functions :
1、 Routing rules for view functions :
app.url_map
: You can see the whole flask Routing information for
return Map([Rule'/'(HEAD,OPTIONS,GET)->index,...])
route Request mode View function name
- If two identical view functions are defined , The route is the same , Then the first one will kill the second
- A view function can add multiple routes
url_for
: Find the route through the view function name , The return is the routing address , namely url
2、url Chuanshen in Chinese :
(1) converter ( Dynamic routing ):127.0.0.1:5000/user/123
@apiBP.route('/user/<int:user_id>', methods=['POST'])
def login(user_id):
""" The user login """
print(user_id)
The default type :int/float/path( Similar to the default , But also accept slashes ), Without converter type , The default is string
(2) Custom converter :
- Define your own Converter :
class ReqexConverter(Werkzeuq.rounting.BaseConverter):
def __init__(self,url_map,regex):
# Call the initialization method of the parent class
super().init()
# Save the parameters of the regular expression you use to the properties of the object ,
flask Go back and use this attribute for regular matching of routes
self.regex=regex
def to_python(self,value):
''' Yes regex Value to do more complex operations , The value passed is normal after verification , Then return to return The value in The value in the path is converted to python In the program '''
return Processed data , That is, the final mobile_id
def to_url(self,value):
return '15812345678'
- Add a custom converter to flask Application
app.url_map.converters['re']=ReqexConverter
- Case study
@apiBP.route('/user/<re(r'1[34578]\d{
9}'):mobile_id>', methods=['POST'])
def login(mobile_id):
""" The user login """
print(mobile_id)
@apiBP.route('/index', methods=['POST'])
def login():
""" The user login """
url=url_for('send_sms',mobile='18611111111')
# amount to /send/15812345678
print(mobile_id)
Four 、request object :
1、 To obtain parameters :
request.form
: You can extract the data in form format in the request body :city=xxx&age=xxx&name=xxx
,form Parameters in the form ;request.data
: The data in the request body is not in form format , Such as json The string passed in ;request.files[' File field name ']
: The file object is returned
f=request.files['the_file']
f.save('/download/test001.txt') # flask File specific methods in
f.read()
f.write()
5、 ... and 、abort function 、 Custom error , The return value of the view function :
1、abort Use of functions :
(1) In the view function , have access to abort(), Terminate view function execution , And return the error message to the front end .
- Status code information can be transferred , Must be standard http Status code :
abort(404)
; - Pass on details ( Need to be Respoese object ):
abort(Respoese())
;
2、 Custom exception handling :
@app.errorhandler(404)
def error(e):
return ' The page you requested no longer exists , Please confirm and visit again !%s'%e
3、 Return value information :
(1) You can return a tuple , Such a tuple must be (response, status, headers
) In the form of , And contain at least one element . status
Value will override the status code , headers
It can be a list or a dictionary , As an additional message header value . If it's a list ,[(‘ Response head 1 The name of ’,‘ Response head 1 Value ’),(‘ Response head 2 The name of ’,‘ Response head 2 Value ’)];
(2) Use make_response
resp = make_response(' Response body ')
resp.headers[“sample”] = “value”
resp.status = “404 not found”
(3) return json
@apiBP.route('/index')
def index():
data={
'name':'wmz',
'age':18
}
# json_str=json.dumps(data)
# return json_str,200,{'Content-Type':'application/json'}
# jsonify Convert the dictionary to json Format data , And modify the response header to json
return jsonify(data)
return jsonify(city='shanghai',age=18)
6、 ... and 、cookie and session:
1、 Set up cookie
resp = make_response(' Response body ')
The default expiration date is temporary cookies
, When the browser is closed, it will fail ,max_age
For the period of validity , The unit is in seconds
(1)resp.set_cookies('Itcast','python',max_age=3600)
(2)resp.headers['Set-Cookies']='Itcast=python,Max-Age=3600'
2、 operation cookies
- obtain
cookies
:request.cookies.get('Itcast')
- Delete
cookies
: Set expiration date , Expire the validity
resp = make_response(' Delete cookies')
resp.delete_cookie('Itcast')
3、 Set up session data
flask in session
The secret key field that needs to be used
app.config['SECRET_KEY']='HAHAHHAHHAHAH'
session['name']='python'
session['age']=18
- Back end generation
sessionId
To the browser , The next time the browser visits ,cookie
Middle carrysessionId
; - flask hold
session
The data is saved incookie
in , Not saved in the back-end server ; - You can put
session
The data is stored in the database 、redis
、 file 、 Program memory ( Define a global variable ).
4、 operation session data
name=session.get['name']
7、 ... and 、flask Context and hook :
1、 Context
(1) Request context (request context
),reques
t and session
All belong to the request context object , Processing multiple requests ;
request={
' Threads A':{
'form':{
'name':'zhangsan'},args:{
}},
' Threads B':{
'form':{
'name':'lisi'},args:{
}}
}
(2) Application context (application context
), Deal with situations where there are multiple applications ;
current_app
andg
All belong to application context objects ;current_app
: Represents the program instance of the currently running program file ;g
: When processing a request , Objects for temporary storage , This variable is reset on every request . Within one request , You need to call multiple functions , You can use it g Variables to define variables .
@apiBP.route('/index')
def index():
data={
'name':'wmz',
'age':18
}
g.username='zhangsan'
say_hello()
def say_hello():
username=g.username
2、 hook
flask Support four kinds of hooks : have access to request Method :
before_first_request
: Run... Before processing the first request ;
@app.before_first_request
def handle_before_first_request():
print(' Run before the first request ')
before_request
: Run... Before each request ;after_request(response)
: If there is no unhandled exception thrown , Run... After each request ( If there is no exception in the view function , Must have return value );teardown_request(response)
: Run... After each request , Even if there are unhandled exceptions thrown ( No matter whether the view function has exceptions , It will be carried out , Must have return value ).
3、flask-script
from flask-script import Manager # Start the management class of the command
manager=Manager(app) # establish manager Management object of
manager.run() # start-up flask, When it's started , You can execute with commands
8、 ... and 、 Templates :
1、 Templates and custom filters
return render_template('index.html',name='python')
2、 Operations can be performed in the template
{
{
myList[0]+myList[1]}}
3、 The default filter
(1) String filters :
safe: Disable escape ;
<p>{
{
'<em>hello</em>' | safe }}</p>
capitalize: Capitalize variable values , Turn other letters to lowercase ;
<p>{
{
'hello' | capitalize }}</p>
lower: Change value to lowercase ;
<p>{
{
'HELLO' | lower }}</p>
upper: Capitalize value ;
<p>{
{
'hello' | upper }}</p>
title: Capitalize each word in the value ;
<p>{
{
'hello' | title }}</p>
trim: Remove the leading and trailing spaces from the value ;
<p>{
{
' hello world ' | trim }}</p>
reverse: String inversion ;
<p>{
{
'olleh' | reverse }}</p>
format: Format output ;
<p>{
{
'%s is %d' | format('name',17) }}</p>
striptags: Before rendering, all the HTML Delete all labels ;
<p>{
{
'<em>hello</em>' | striptags }}</p>
Support the use of chain filters :
<p>{
{
“ hello world “ | trim | upper }}</p>
(2) List Filter
first: Take the first element
<p>{
{
[1,2,3,4,5,6] | first }}</p>
last: Take the last element
<p>{
{
[1,2,3,4,5,6] | last }}</p>
length: Get list length
<p>{
{
[1,2,3,4,5,6] | length }}</p>
sum: Sum list
<p>{
{
[1,2,3,4,5,6] | sum }}</p>
sort: Sort the list
<p>{
{
[6,2,3,1,5,4] | sort }}</p>
4、 Custom filter
(1) adopt add_template_filter
( Filter function , The name of the filter used in the template )
def filter_double_sort(ls):
return ls[::2]
app.add_template_filter(filter_double_sort,'double_2')
(2) Through ornaments app.template_filter
( The name of the decorator used in the template )
@app.template_filter('db3')
def filter_double_sort(ls):
return ls[::-3]
5、 Process forms
# Set up csrf_token
{
{
form.csrf_token() }}
{
{
form.user_name.label }}
<p>{
{
form.user_name}}</p>
{
% for msg in form.user_name.errors %}
<p>{
{
msg}}</p>
{
% endfor %}
{
{
form.user_name.errors}} # A prompt will pop up when the verification fails
In the verifier :
user_name=StringField(label=u' user name ',validators=[DataRequired(' This is an error message !')])
submit Buttons also need to be drawn
6、 macro
(1) The content used many times in the template can be defined as macros ;
- With no arguments :
{
% macro input() %}
<input type="text"
name="username"
value=""
size="30"/>
{
% endmacro %}
Use :
{
{
input() }}
- With parameters :
{
% macro input2(type,value,size='30') %}
<input type="{
{type}}"
name="username"
value="{
{value}}"
size="{
{size}}"/>
{
% endmacro %}
Use :
{
{
input('password','name') }}
(2) External reference : The file name can be customized macro.html
;
{
% macro input() %}
<input type="text" name="username" placeholde="Username">
<input type="password" name="password" placeholde="Password">
<input type="submit">
{
% endmacro %}
Import... In other template files first , Call again
{
% import 'macro.html' as func %}
{
{
func.input()}}
7、 Inheritance of templates
- The parent template :
{
% block top %}
Top menu
{
% endblock top %}
{
% block content %}
{
% endblock content %}
{
% block bottom %}
Bottom
{
% endblock bottom %}
- Sub template :
{
% extends 'base.html' %}
{
% block content %}
What to fill in
{
% endblock content %}
Points for attention when using template inheritance :
- Multiple inheritance is not supported .
- For easy reading , Use in child templates extends when , Try to write it in the first line of the template .
- Cannot define more than one with the same name in a template file block label .
- When using multiple in a page block When labeling , Suggest a name for the end tag , When more than one block Nesting , Better reading .
Nine 、 Database expansion package :
1、 Create foreign keys :
class User(UserMixin,Base):
""" User information sheet """
__tablename__ = 'sp_user'
userid = Column(Integer, primary_key=True)
user_name = Column(String(24),unique=True, nullable=False) # User name
addresses=relationship('Address',backref='user')
class Address(Base):
""" Shipping address """
__tablename__ = 'sp_address'
addressId=Column(Integer, primary_key=True)
userId=Column(Integer, ForeignKey('sp_user.userid')) # founder id
provinceId=Column(Integer, nullable=False) # province ID
2、 Query data
Method 1: adopt SQLA... Mode query
db.session.query(Role).all()
Method 2: adopt flask-sqla... Mode query
Role.query.all()
3、 Conditions of the query
Role.query.filter(Role.name=' Administrators ').all()
Role.query.filter_by(name=' Administrators ').all()
4、 Relational query
user=User.query.get(1)
user.Address # Can return userID be equal to 1 All address information for
address=Address.query.get(1)
address.user # return addressID be equal to 1 Information of the personnel to which it belongs
5、 Let the query come out , The data display in the output information is more intuitive
class User(UserMixin,Base):
""" User information sheet """
__tablename__ = 'sp_user'
userid = Column(Integer, primary_key=True)
user_name = Column(String(24),unique=True, nullable=False) # User name
addresses=relationship('Address',backref='user')
def __repr__(self):
return 'User object name=%s' %self.user_name
6、 update operation
User.query_by(user_name ='zhou').update({
'addresses':' Shanghai '})
Ten 、 Database migration package , Mail expansion package :
pip install flask-migrate
#coding=utf-8
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate,MigrateCommand
from flask_script import Shell,Manager
app = Flask(__name__)
manager = Manager(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:[email protected]:3306/Flask_test'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
# The first parameter is Flask Example , The second parameter is Sqlalchemy Database instance
migrate = Migrate(app,db)
#manager yes Flask-Script Example , This statement is in flask-Script Add a db command
manager.add_command('db',MigrateCommand)
# Defining models Role
class Role(db.Model):
# Define table name
__tablename__ = 'roles'
# Define column objects
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
def __repr__(self):
return 'Role:'.format(self.name)
# Define users
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
def __repr__(self):
return 'User:'.format(self.username)
if __name__ == '__main__':
manager.run()
- establish migrations Folder , All migration files are in it .
python database.py db init
- Create an automatic migration script
python database.py db migrate -m 'initial migration'
- Update the database
python database.py db upgrade
- Check the specific version of the historical version
python database.py db history
- Copy the specific version number and execute rollback
python database.py db downgrade Version number
11、 ... and 、 The blueprint :
- When defining blueprints , There is no default static file directory , You need to define it manually ,
template_folder='templates'
; - Search order of template file : First define app When the template directory defined , Definition app The default template directory is
templates
If not found , Then go to the template directory defined when defining the blueprint .
Twelve 、flask Deploy :
Gunicorn
( Green Unicorn ) It's aPython WSGI
OfHTTP
The server ;WSGI
: The full name isWeb Server Gateway Interface
(web
Server gateway interface ), It's a norm , It isweb
The server andweb
Interfaces between applications . It works like a bridge , Connected to theweb
The server andweb
Between application frameworks ;uwsgi
: It's a transport protocol , Used to define the type of transmission information ;uWSGI
: Is to implement theuwsgi
agreementWSGI
Ofweb
The server .
gunicorn -w 4 -b 127.0.0.1:5000 -D --access-logfile ./ Logs/ Log main:app
-D: Background daemon
--access-logfile ./ Logs/ Log: Log files ( History of the visit )
nginx( It will ensure that forwarding is carried out in turn , Equal access to each service )
- Use
nginx
Deploy , To configurenginx.conf
file .
边栏推荐
- Shim and Polyfill in [concept collection]
- The pressure of large institutions in the bear market has doubled. Will the giant whales such as gray scale, tether and micro strategy become 'giant thunder'?
- File links cannot be opened or downloaded in Google browser
- Troubleshooting of high CPU load but low CPU usage
- Inno Setup 制作安装包
- Pytorch exercise items
- The 10000 hour rule won't make you a master programmer, but at least it's a good starting point
- 10000小时定律不会让你成为编程大师,但至少是个好的起点
- UTC time, GMT time, CST time
- DBNet:具有可微分二值化的实时场景文本检测
猜你喜欢
2022 cisp-pte (III) command execution
Software testing learning - the next day
[open source project recommendation colugomum] this group of undergraduates open source retail industry solutions based on the domestic deep learning framework paddlepadddle
Realize PDF to picture conversion with C #
熊市里的大机构压力倍增,灰度、Tether、微策略等巨鲸会不会成为'巨雷'?
[Fiddler actual operation] how to use Fiddler to capture packets on Apple Mobile Phones
EasyExcel
2022年华东师范大学计科考研复试机试题-详细题解
Sorting out the core ideas of the pyramid principle
【无标题】
随机推荐
C2338 Cannot format an argument. To make type T formattable provide a formatter<T> specialization:
Use the jvisualvm tool ----- tocmat to start JMX monitoring
Crontab scheduled task
【code】偶尔取值、判空、查表、验证等
golang操作redis:写入、读取hash类型数据
How can I split a string at the first occurrence of “-” (minus sign) into two $vars with PHP?
【无标题】
Reading notes of "learn to ask questions"
Jenkins
Pits encountered in the use of El checkbox group
php安装swoole扩展
golang操作redis:写入、读取kv数据
[classes and objects] explain classes and objects in simple terms
[attribute comparison] defer and async
IC_EDA_ALL虚拟机(丰富版):questasim、vivado、vcs、verdi、dc、pt、spyglass、icc2、synplify、INCISIVE、IC617、MMSIM、工艺库
2022-06-23 vgmp OSPF inter domain security policy NAT policy (under update)
What are the characteristics and functions of the scientific thinking mode of mechanical view and system view
Software testing assignment - day 3
Practice of enterprise ab/testing platform
机械观和系统观的科学思维方式各有什么特点和作用