Flask first day ---- Quick Start

Foreword

This is a blog off the ground, talking about some of the relevant basic knowledge as well as give some small examples described in detail the various parts of the framework to be followed by a guide. As for how installation configuration environment, how to build a virtual environment-related issues can go search for other blog, I'm not here too much into details.

Here are some of what I intend to write this column
Here Insert Picture Description

Start now

First, according to the above chart, the first article I want to say is simply part of the foundation
Here Insert Picture Description

1. About Flask

Flask framework written in python is a lightweight web application framework, which is used to support dynamic web sites, web applications and web services development. What are the benefits framework is it? Most web development common functions has helped us achieve, we just need to use the framework provided enough time to develop their own. There are many other web framework written in python, such as Django, Tornado ...... but why would I choose to write about Flask, because I fancy it's lightweight . What does that mean, to get Django contrast, the two are very different, Django to a variety of features are included in the inside, resulting in very heavy (some often do not have access), and Flask only contains the core functionality. For Tornado does it have a good asynchronous processing capabilities, it is a high-performance, but it is not based WSGI protocol, but based http server, talking about after this part of the process the form mentioned werkzeug this one will be more specific to talk about.

Flask want to self, then it also has many books: wolf books, dog books ...... former combat bias point, which I personally feel that talk is not so good, long look but will also lead to some boring could not stand. There is a need, then you can go online to look for search pdf

2.Flask的hello world

First of all Flask program you must first have an instance of an object, which is instantiated Flask class, usually with app name.

from flask import Flask
app=Flask(__name__)

We can also see what kind of source Flask
Here Insert Picture Description
closer look at this comment, not only will you find the next instance method under ordinary circumstances, the following are examples of other methods of treatment in a folder is usually __name__ __main__

Then use route () decorator to specify access by following what url function, i.e. the function corresponding to the formation url mapping relationship that is routed. Now let simple hello world output line

@app.route('/')
def hello_world():
    return 'Hello World!'

I write here hello_world () function is actually a view function, and then we will talk about specific view function, just know that now view function must have a return value can be a string, can also be a html page, and so on.
Finally, it is to start a web service

if __name__ == '__main__':
    app.run(debug=True,host='localhost',port=8888)

In the main function, with app.run () to start the service, can no intermediate parameter, the parameter may be added according to their need. Such as debug = True, the model is set to debug the program error will output an error message on the console; port is the port number is specified, the default is 5000, but in case the local port has been occupied by a port needs to be replaced, this time need designated port.

The complete code and operating results

from flask import Flask

app=Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run(debug=True,host='localhost',port=8888)

Here Insert Picture Description
Only seven lines of code implements a simple web service, is not very simple.

3.url mass participation, as well as reverse jump redirect page

Flask want to pass in a parameter or variable, generally using a form or url passed. We will go to the form specifically in data exchange among today look url parameter passing

Syntax:
URL syntax parameter passing () disposed decorator route '/ <require parameters passed to> /', of course, consistent with the view below the parameter name in the function passed to herein parameter name.
For example look at

from flask import Flask

app=Flask(__name__)

@app.route('/')
def hello_world():
    return '这是url传参演示'

@app.route('/user/<name>')
def list_user(name):
    return "接收到的名字为:{}".format(name)

if __name__ == '__main__':
    app.run(debug=True,host='localhost',port=8888)

Here Insert Picture Description
Here Insert Picture Description

Once you understand mass participation since we can look url reversed in order to achieve the jump of the redirect page. What does that mean, I can give a simple common example, some sites such as your home page to open it, then he will automatically jump to the login screen, this is the page jump, which is necessary to use redirection.

Let's look url reverse
when we need to use to redirect url view function defined, then we have to get the name of the view function pointed to the url according to, this is the url reversal. (In fact, reflects the relationship mapping function) may start to listen to a relatively ignorant, look at an example of it

from flask import Flask,url_for

app=Flask(__name__)

@app.route('/')
def index():
    url1=(url_for('news',id='10086'))
    return "URL反转的内容为:%s"%url1

@app.route('/news/<id>')
def news(id):
    return "请求的参数是为:{}".format(id)

if __name__ == '__main__':
    app.run(debug=True,host='localhost',port=8888)

Here Insert Picture Description
Here Insert Picture Description
To analyze the code, we first define two view function index and news, and then we returned in the news is the id url parameter. Now we would like to set the id value in index, then we need to url reversing url_for function. url_for first parameter is the view of the function you want to set, then the latter parameters with the situation.

After the realization of this part of the page jump since you can look up
how to make a start we set to open web pages but not index the other pages, such as login does. We must first introduce the redirect () function redirects , its function is simply to jump to a specific url, now it is very simple to implement

from flask import Flask,url_for,redirect

app=Flask(__name__)

@app.route('/')
def index():
    print("首先访问index()视图函数")
    url1=(url_for('user_login'))
    return redirect(url1)

@app.route('/user_login')
def user_login():
    return "这是用户首页,需要先登录!"

if __name__ == '__main__':
    app.run(debug=True,host='localhost',port=8888)

Analysis: We first define the url1 index view function, the result is url1 user_login inverted view function corresponding url: '/ user_login', and then we use the redirect to redirect to achieve url1 page jump.
Here Insert Picture Description
As a start we see is not the index but user_login.

to sum up

This is the first major content Overall framework like routing, view, redirect ...... have talked about (except that a database), and then the next piece of content on Jinja2 template engine requires a Diudiu html knowledge, left most is to learn and remember at Jinja2 template rendering mechanism, the next update should wait for some time.

Published 85 original articles · won praise 55 · views 20000 +

Guess you like

Origin blog.csdn.net/shelgi/article/details/104409565