Flask Basic Four

Source: Internet
Author: User
Tags file url

Content review:

1.flask-session
From Flask Import session
From flask_session Import session

app.config["Sesstion_tpye"] = "Redis"
app.config["Sesstion_redis"] = REDIS ("IP", port,db=1)
# select 1-----[1]

Session (APP)

session["key"] = "value"
session["Key"]

2.Flask CBV
Class Index (views. Methodview):
methods = ["GET"]
decorators = [A,b,c]
Def get ():
Return "File"


App.add_url_rule ("/", endpoint= "index", View_func=index.as_view (name= "index"))

If 1:endpoint = None = name = "Index"
Elif 2:endpoint= "index"! = name= "index123"

3.Flask wtforms
From wtforms import form,validators,widgets
From Wtforms.fields Import Simple
Class Lgoinform (Form):
Username = simple. Stringfield (
label = "User Name",
validators=[
Validators. DataRequired (message= "User name cannot be empty"),
],
Widget = Widgets. TextInput (),
RENDER_KW = {"Class": "Jinwangba"}
)

Def a ():
"GET":
Return Render_template ("a.html", fm = Lgoinform ())
"POST":
Request.Form
LFM = Lgoinform (Request.Form)
Lfm.validate () True False

{{Fm.username.label}} {{Fm.username}} {{fm.username.errors.0}}

Flask Review:

# 1. Route @app.route ('/', methods=["GET", "POST"],endpoint= "HelloWorld", Strict_slashes=true)
# dynamic route parameter/<arg> def viewfunc (ARG)
# url_for
# 2. Three the base:
# HttpResponse return ' Hello world! '
# Render Retrun render_template ("index.html")
# REDIRECT Retrun redirect ("/login")

# 3.request
# Store Data:
# request.form # data obtained from the form FormData
# Request.args # data obtained when URL parameter is passed
# Request.json # Content-type:application/json Get Data
# request.data # B "" Content-type:xiaowangba Get Data
# of Request Properties
# Request.method = "GET"/"POST"
# Request.path = "/index"
# Request.url = "Http://127.0.0.1:5000/index"
# Pit
# request.values.to_dict () the same name is overridden by get (args)

# 4.session:flask-session
# App.secret_key = "Encrypted string"
# The serialized session stored in the browser cookie
# session["key"] = "value"
# session["Key"]
# session Default 31-day life cycle

# 5.Blueprint
# Blueprint objects can be understood as a flask object that cannot be started
# BP = Blueprint ("Bluename", __name__,template_folder= "Temp_blue")
# @bp. Route ("/blue")
# App.register_blueprint (BLUEPRINT.BP)

# 6.Flask Configuration
# 1.Flask Object instance Configuration
# class OBJ (object):
# DEBUG = True
# Session_type = "Redis"
# Session_redis = REDIS (db=5)
# App.config.from_object (OBJ)

# 2.Flask Initialization Configuration
# template_folder = Template file storage path
# static_folder = "Static file storage Path"
# Static_url_path = "/static file URL Access address" default is Static_folder


# 7.Flask JINJA2
# {{}} when referencing variables and executing functions, non-logical references
# {%} If for logical code reference
# obj.name Obj.get ("name") obj["name"] Obj_list.1 obj_list[1]
# Markup | Safe
# @app. Template_global ()
# @app. Template_filter ()

# 8.before_request After_request ErrorHandler (404,500)
# @app. before_request multiple before_request executed sequentially
# def BE1 ():
# return None

# @app. after_request multiple after_request, reverse order execution
# def AF1 (response)
# return response

# Normal Condition: BE1-BE2-AF2-AF1
# exception Condition: BE1-AF2-AF1
# @app. ErrorHandler (404) Redefining error messages

# 9.flash
# Flash ("BE_FR1")
# get_flashed_messages ()


# 10.send_file Jsonify
# send_file ("file path") to open and return file contents
# jsonify ({k:v}) serializes the dictionary JSON, packaging a content-type:application/json back to the client

# 11.Flask CBV
# class Index (views. Methodview):
# methods = ["GET"]
# decorators = [A,b,c]
# def get ():
# return "File"
#
#
# App.add_url_rule ("/", endpoint= "index", View_func=index.as_view (name= "index"))
#
# if 1:endpoint = None = name = "Index"
# elif 2:endpoint= "index"! = name= "index123"

1.DBUtils Database Connection Pool

First download the plugin pip install dbutils or python3-m pip install Dbutils,

Then run the MySQL database, create a new database in MySQL, and create a new table to enter the data.

ImportPymysql fromDbutils.pooleddbImportPooleddbpool=Pooleddb (creator=pymysql,#modules that use linked databasesMaxconnections=6,#the maximum number of connections allowed for a connection pool, 0 and none means no limit on the number of connectionsmincached=2,#at least 0 of the free links created in the link pool are not created when initializingMaxcached=5,#most idle links in the link pool, 0 and none are not limitedMaxshared=3,#The maximum number of links shared in a linked pool, 0 and none means sharing all. PS: Useless, because Pymysql and mysqldb modules such as threadsafety are 1, all values regardless of set to how much, _maxcached forever is 0, so forever is all links are shared. Blocking=true,#If there are no available connections in the connection pool, wait is blocked. True, wait, False, not wait and then errorMaxusage=none,#the maximum number of times a link is reused, none means unlimitedSetsession=[],#a list of commands to execute before starting the session. such as: ["Set Datestyle to ...", "Set time zone ..."]ping=0,#Ping the MySQL server to check if the service is available.     #such as: 0 = None = Never,    #1 = default = Whenever it is requested,    #2 = When a cursor is created,    #4 = When a query is executed,    #7 = alwayshost='127.0.0.1', # Host Port=3306, # Port user='Root', # User password="', # Password database='s12day113', # The name of the database created CharSet='UTF8')

You can also query a single message:

You can also insert a single piece of data:

2.Flask request Context, Application context

Flask Basic Four

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.