python Programming Flask Framework Simple Use Tutorial

  • 2021-12-12 04:51:45
  • OfStack

Flask Common Extension Package Basic Format Extension return Redirection Take URL Parameter content-typecookie\ sessionflask Route request Attribute Context Registration Route

Basic knowledge

Advantages of using a framework

Strong stability and scalability
It can reduce the development difficulty and improve the development efficiency

Born in 2010, Flask is a lightweight Web development framework written by Armin ronacher in Python language based on Werkzeug toolbox
Flask itself is equivalent to a kernel, and almost all other functions need extensions (mail extension Flask-Mail, user authentication Flask-Login, database Flask-SQL_Alchemy), all of which need to be implemented by third-party extensions.
The WSGI toolkit uses Werkzeug (routing module) and the module engine uses Jinja2, which are also the core of the Flask framework

Flask Common Extension Pack

Flask-SQLalchemy 操作数据库
Flask-script 插入脚本
Flask-migrate 管理迁移数据库
Flask-Session Session存储方式指定
Flask-WTF 表单
Flask-Mail 邮件
Flask-Bable 提供国际化和本地化支持,翻译;
Flask-Login 认证用户状态;
Flask-OpenID 认证;
Flask-RESTful 开发REST API的工具;
Flask-Bootstrap 集成前端Twitter Bootstrap框架
Flask-Moment 本地化日期和时间
Flask-Admin 简单而可扩展的管理接口的框架

Extended list: http://shouce. ofstack. com/flask0.10/extensions. html

1. Chinese document (http://shouce.ofstack.com/flask0.10/index.html)
2. English document (http://flask.pocoo.org/docs/0. 11/)

Basic format


from flask import Flask
app=Flask(__name__)
@app.route('/')
def a():
    return 'aa'
app.run()

Open the Google URL for your ip address and add: Plus the default port number 5000 page to show for aa


app.run(host='0.0.0.0',port=80,debug=True)

host: When it is set to '0.0. 0.0', it can be accessed by ip of other computers in the same LAN. If this parameter is not set, only its own ip can be accessed
port: It is the default port number. When it is 80, there is no need to add: the port number you set after the URL.
debug: When the value of debug is True after modifying the value of return in the code, the content can be refreshed by refreshing the web page without re-executing the program

Expand


from flask import Flask
app=Flask(__name__)
@app.route('/<orders_id>')    # Add a <>  <> The contents written in are parameters 
def a(orders_id):
    return '%s'%orders_id
app.run()

Enter your ip in Google and add/what you want to write. The content displayed on the webpage is what you want to write
If the limit can only be numbers <int:orders_id> <float:orders_id>

return

return can only return strings and render_template
Convert to json type if you want to return a dictionary or something like that


import json
json.dumps()

from flask import Flask,jsonify

return {'a':'b'}  # Report an error 
return str({'a':'b'})  # Plain text, no data type, that is, no key-value pair 
return json.dumps({'a':'v'})  # Text form, but key-value pairs are preserved 
return jsonify({'a':'v'})  #json Type    Key-value pair 

app.conifg['JSON_AS_ASCII']=False   # The Chinese characters that will be returned will not be used ASCII Formal return 

app.config.from_pyfile('settings.ini')  #  You can create a new settings.ini   Write the configuration here  

Redirect


from flask import Flask,redirect,url_for
app=Flask(__name__)
@app.route('/')
def a():
    return 'a'
@app.route('/five')
def five():
    return redirect(url_for('a'))   # When you enter the URL for your ip+/+five  Hour   The content of this webpage actually jumps to a() The content returned in the method 

# Redirect to Dark Horse official website 
@app.route('/demo5')
def demo5():
    return redirect('http://www.itheima.com')

# Redirect to your own view function 
# You can fill in yourself directly url Path 
# You can also use the url_for Generates the corresponding of the specified view function url

@app.route('/demo1')
def demo1():
    return 'demo1'

# Redirect 
@app.route('/demo5')
def demo5():
    return redirect(url_for('demo1'))

# Redirect to a view function with arguments 
# In  url_for  Parameters are passed into the function 

#  Routing delivery parameters 
@app.route('/user/<int:user_id>')
def user_info(user_id):
    return 'hello %d' % user_id

#  Redirect 
@app.route('/demo5')
def demo5():
    #  Use  url_for  Generates the corresponding of the specified view function  url
    return redirect(url_for('user_info', user_id=100))



Take URL parameters


from flask import Flask,request,jsonify
app=Flask(__name__)
@app.route('/<id>')
def a(id):
    return '%s'%id

# When you enter the URL for your ip + / +  What you want to show,    Page content is what you want to show 

@app.route('/')
def b():
    name=request.args.get('name')
    id=request.args.get('id')
    return jsonify({'name':name,'id':id})

# When you enter the URL for your ip + /? +name= Xiao Ming &id=7   The content displayed is {'name': Xiao Ming ,'id':7}

content-type

json Type: 'content-type': 'application/json'
String type: 'content-type': 'text/plain'
Resolution type: 'content-type': 'text/html'

cookie\session

Get cookie request. get. cookie ('')
Get session session. get ('')

cookie: Data (usually encrypted) stored locally by some Web sites for session tracking purposes
Complex form Cookies
cookie is generated by the server and sent to the client browser. The browser will save the Key/value of Cookie, and send the cookie to the server when the same website is requested next time (provided that the browser is set to enable cookie)
Key/value of cookie can be defined by the server itself

Cookie is a piece of plain text information stored in the browser. It is not recommended to store sensitive information such as passwords, because the browser on the computer may be used by others
Cookie is based on domain name security, and Cookie with different domain names cannot be accessed to each other
If Cookie information is written to the browser when accessing itcast. cn, Cookie information written by itcast. cn cannot be accessed when accessing baidu. com using the same browser
Homologous strategy of browser
When a browser requests a website, it will submit all Cookie information under the website to the server, so Cookie information can be read in request


# Settings cookie
from flask import Flask,Response
@app.route('/cookie')
    def set_cookie():
        resp=Response("this is to set cookie")
        resp.set_cookie('username','itcast')
        return resp

 Set expiration time 
@app.route('/cookie')
def set_cookie():
    response=Response('hello world')
    response.set_cookie('username','itheima',3600)    # In seconds 
    return response

 Get cookie
from flask import Flask,request
# Get cookie
@app.route('/request')
def resp_cookie():
    resp=request.cookies.get('username')
    return resp

Session
 For sensitive and important information, it is recommended to store it on the server side. The scheme of state maintenance on the server side is session
session Depend on cookie
session Data acquisition 
session: Request context object for handling http In the request 1 Some data content 
@app.route('/index1')
def index1():
    session['username']='itcast'
    return reddirect(url_for('index'))
@app.route('/')
def index():
    return session.get('username')
 Remember to set secretz-key='itcast'   The values in this can be set at will 

 Delete session
session.pop('')

app.config['PERMANENT_SESSION_LIFETIME']=20  # Settings session Limitation of 



flask routing


 Specify the routing address 
# Specify the access path as demo1
@app.route('/demo')
def demo1():
    return 'demo1'

 Pass parameters to routes  
 Sometimes we need to make the same 1 Class URL Map to the same 1 View function processing, such as: using the same as 1 View functions to display personal information of different users 

# Routing delivery parameters 
@app.route('/user/<user_id>')
def user_info(user_id):
    return 'hello %s'%user_id

 What is added to the URL suffix entered   What is displayed on the web page , The following function must be the above parameter in parentheses 
 The parameters passed by the route default as string You can also specify the type of the parameter 

# Routing delivery parameters 
@app.route('user/<int:user_id>')
def user_info(user_id):
    return 'hello %d'%user_id

 Here you specify int, The contents of angle brackets are dynamic. It can be understood here for the time being as acceptance int The value of type, actually int Represents the use of IntergeConverter To deal with url Parameters passed in 

 Specify the request method 
 In Flask Medium. Definition 1 The default request method is: 
GET
OPTIONS( Bring your own )
HEAD  (Bring your own) 

 If you want to add a request, 
@app.route('/demo2',methods=['GET','POST'])
def demo2():
    # Get the request mode directly from the request and return it 
    return request.method

request Properties

request is the request object representing the current request in flask, with one request context variable in the period

(Understood as a global variable, you can get the current request by using it directly in the view function)
Attribute description type

data Record the requested data and convert it to the string *
form Record the form data in the request MultiDict
args Record the query parameter MultiDict in the request
cookies Record the cookie information Dict in the request
headers Record the header EnvironHeaders in the request
method  HTTP method used for recording requests GET/POST
url Record the requested URL address string
files Record the file requested to upload *
Request.Form Obtaining data submitted by POST (receiving data submitted by Form);
data0 Gets address bar parameters (data submitted as GET)
Request Includes the above two methods (get the data submitted by GET first), and it will search once in QueryString, Form and ServerVariable.

requests module has two methods to send requests, data and params, which carry parameters.

params is used in an get request, and data is used in an post request. params is a parameter added after url, which is the dictionary or object passed in by the POST request

Context

Context: Equivalent to a container, which holds some information during the running of Flask program
There are two contexts in Flask, request context and application context

Request Context (request context)
Thinking: How to get the relevant data of the current request in the attempt function? For example: Request address, request mode, cookie and so on
In flask, the object request can be directly used in the view function to obtain the relevant data, and request is the object of the request context, which stores the relevant data of the current request. The request context objects are: request, session

request:
Encapsulates the contents of an HTTP request for an http request. Example: user=request. args. get ('user'), which gets the parameters of the get request

session:
Used to record the information in the request session, aiming at the user information, for example: session ['name'] = user. id, which can record the user information and obtain the user information through session. get ['name']

The application context objects are: current_app, g
current_app
The application context is used to store variables in the application. You can print the name of the current app through current_app. name, or you can store a few variables in current_app, for example:
Which file is the startup script of the application and what parameters are specified at startup
Which configuration files were loaded and which configurations were imported
Connected to that database
What are the public tool classes, constants
The application runs on that machine, how much IP, how much memory
current_app.name
current_app.text_value='value'

g variable
As a temporary variable of flask program, g acts as an intermediate medium. We can transfer some data through it. g stores the global variable of the current request. Different requests will have different global variables, which are distinguished by different thread and id

g.name='abc'
Note: Different requests will have different global variables

The difference between the two:
Request context: Saves the data of client-server interaction
Application context: 1 configuration information saved during the running of flask application, such as program name, database connection, application information, etc.
Objects in the context can only be used in the specified context, and cannot be used outside the scope. The principle of request context and application context is implemented: http://shouce. ofstack. com/flask0.10/appcontext. html

Register route


@app.route('/')
def hello():
    # Will return status code
    #content-type  In http headers Li 
    #content-type=text/html  # Default value   As html Format to parse 
    # Encapsulates the returned results as 1 A Response Object 
    headers={
        # 'content-type':'text/plain',  # Parse it as an ordinary string 

        'content-type':'application/json'   # Return json Type 
    }
    # response=make_response('<html></html>',200)    #301 Is a redirect 
    # response.headers=headers
    # return response
    # return '<html></html>'
    return '<html></html>',200,headers

# app.add_url_rule('/hello',view_func=hello)   # You can also register the route in this way 

The above is python programming Flask framework simple use tutorial details, more about python tutorial Flask framework use of information please pay attention to other related articles on this site!


Related articles: