Flask is easy to use

0. Preface

FlaskIt is the use of a Pythonlightweight written Webapplication framework.

1. Installation

pip install flask -i https://pypi.douban.com/simple

1.1 The simplest case

from flask import Flask
app = Flask(__name__) # __main__

@app.route('/') # rule 参数表示与该函数的URL绑定。
def hello_world():
   return 'Hello World'

if __name__ == '__main__':
   app.run() # app.run(host, port, debug, options)

Insert picture description here

2. Simple to use

2.1 Routing

@app.route('/hello/<name>') # http:// localhost:5000/hello/w3cschool
def hello_name(name):
   return 'Hello %s!' % name
   
@app.route('/blog/<int:postID>')  # http://localhost:5000/blog/11
def show_blog(postID):
   return 'Blog Number %d' % postID

@app.route('/rev/<float:revNo>') # http://localhost:5000/rev/1.1
def revision(revNo):
   return 'Revision Number %f' % revNo

2.2 url_for()Function

Dynamically build specific functions URL, such as:

@app.route('/admin')
def hello_admin():
   return 'Hello Admin'


@app.route('/guest/<guest>')

def hello_guest(guest):
   return 'Hello %s as Guest' % guest


@app.route('/user/<name>')
def hello_user(name):
   if name =='admin':
      return redirect(url_for('hello_admin'))
   else:
      return redirect(url_for('hello_guest',guest = name))

2.3 method specification

<form action = "http://localhost:5000/login" method = "post">
	<p>Enter Name:</p>
	<p><input type = "text" name = "nm" /></p>
	<p><input type = "submit" value = "submit" /></p>
</form>
@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      user = request.form['nm']
      return redirect(url_for('success',name = user))
   else:
      user = request.args.get('nm')
      return redirect(url_for('success',name = user))

POSTThrough request.form['nm']acquisition, GETthrough request.args.get('nm')acquisition.

2.4 Using templates

Create a new templatesfolder, and then create a new hello.htmltemplate file below .
Insert picture description here
Then, template_folder="templates"specify the template folder in use, and then use the template file as follows:

from flask import Flask, render_template
app = Flask(__name__, template_folder="templates") # __main__

@app.route('/')
def hello_world():
   return render_template("hello.html")

if __name__ == '__main__':
   app.run() # app.run(host, port, debug, options)

Insert picture description here

2.5 template variables

In the template, springbootit is theamleafsimilar to the template in. You can use variables, pass in values, that is, template variables.
In htmluse { { my_str }}in use in render_templatethe Incoming my_str:
htmltemplate files:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    Hello {
   
   { username }}
</body>
</html>

Server program:

from flask import Flask, render_template
app = Flask(__name__, template_folder="templates") # __main__

@app.route('/<username>')
def hello_world(username):
   return render_template("hello.html", username=username)

if __name__ == '__main__':
   app.run() # app.run(host, port, debug, options)

Insert picture description here

2.6 Static files

2.6.1 Take cssfile as an example

Common css, js, imgsfiles and so is we need a static resource files. Similarly, you can use

app = Flask(__name__, template_folder="templates", static_folder="static") 

To specify the path of the static resource.
Add a new staticfolder, then add a new cssfolder under it, and create a index.cssfile.
Insert picture description here
index.cssThe content of the file is as follows:

*,body{
    
    
    background-color: #333;
}

.test{
    
    
    color: red;
    font-size: 30px;
}

In the corresponding htmltemplate file, use the following:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link type="text/css" rel="styleSheet"  href="{
     
     { url_for('static', filename = 'css/index.css') }}"/>
    <title>Title</title>
</head>
<body>
    <p class="test">Hello {
   
   { username }}</p>
</body>
</html>

Then the server program is as follows:

from flask import Flask, render_template
app = Flask(__name__, template_folder="templates", static_folder="static")

@app.route('/<username>')
def hello_world(username):
   return render_template("hello.html", username=username)

if __name__ == '__main__':
   app.run() # app.run(host, port, debug, options)

Effect:
Insert picture description here
Then, through a simple page analysis, index.cssthe access path that can be obtained is:

http://127.0.0.1:5000/static/css/index.css

Insert picture description here

2.6.2 Static image resources

Similarly, we can use image resources in the template, create a new static/img/tu.pngfile in the same way , and then we can reference it like this:

<img src="{
     
     { url_for('static',filename='img/tu.png')}}" />

2.6.3 Note

[Note] The above static resource files can be directly referenced by absolute paths, such as /static/css/index.css.

2.7 Request object

RequestThe important attributes of the object are listed below:

  • Form-It is a dictionary object that contains key and value pairs for form parameters and their values. Namely: POSTrequest.
  • args-Parse the content of the query string, which is URLthe part after the question mark . Namely: GETrequest.
  • CookiesCookie-A dictionary object that holds names and values.
  • files -Data related to uploaded files.
  • method -Current request method.

Guess you like

Origin blog.csdn.net/qq_26460841/article/details/113724988