Flask framework-(understand the Flask framework and project configuration)

Flask framework-(understand the Flask framework and project configuration)

1. Introduction to the Flask Framework

Flask is a very popular Python web framework. It came out in 2010. The author is ArminRonacher. Originally, this project was just a joke made by the author on April's Day. Later, due to its popularity, it became a A formal project.
Since the first version of flask was released in 2010, it has been very popular and loved by developers, and has been used in many companies. The reasons why flask is so popular can be divided into the following points:

  • Micro-framework, conciseness, and only do what he needs to do, which provides developers with great scalability.
  • Flask and the corresponding plug-ins are very well written and very cool to use.
  • The development efficiency is very high, such as using SQLAlchemy's ORM to operate the database can save developers a lot of time writing SQL

Flask is very flexible. It won't help you make too many decisions. You can make changes according to your
wishes.

  • When using Flask to develop a database, whether to use SQLAlchemy or MongoEngine, the choice is completely in your hands. Different from Django, Django has built-in very complete and rich functions, and if you want to replace it with what you want, either it is not supported or it is very troublesome.
  • It is very easy to replace the default Jinija2 template engine with other template engines.

Introduction to Flask catalog:
Catalog Introduction

2. The first Flask program

 # 从flask框架中导⼊Flask类
from flask import Flask

# 传⼊__name__初始化⼀个Flask实例
app = Flask(__name__)


# app.route装饰器映射URL和执⾏的函数。这个设置将根URL映射到了hello_world函数上
@app.route('/')
def hello_world():
	return 'Hello World!'


if __name__ == '__main__':
# 运⾏本项⽬,host=0.0.0.0可以让其他电脑也能访问到该⽹站,port指定访问的端⼝。
默认的host是127.0.0.1,port为5000
app.run(host='0.0.0.0', port=9000)

Then click Run and enter http://127.0.0.1:9000 in the browser to see hello world. One thing to note is that app.run is only suitable for development. If it is in a production environment, it should be started with Gunicorn or uWSGI. If it is running on the terminal, you can press ctrl+c to stop the service.

3. Project configuration

3-1. Set to DEBUG mode

Why set up DEBUG mode?

  • When there is an error in the code, it will appear directly on the html to facilitate developers to find the error
  • After the debug mode is turned on, flask will automatically reload the code every time the code is saved
  • Flask does not enable debug mode by default

Note: The DEBUG mode can only be turned on in the development environment, because the DEBUG mode will bring serious security risks.

After the DEBUG mode is turned on, when the program enters the error stack mode with an exception, and you click on a stack for the first time and want to view the variable value, a dialog box will pop up for you to enter the PIN value. The PIN value will appear when you start it. For example, the PIN value in the item just started is 294-745-044. After you enter this value, Werkzeug will save the PIN value as a part of the cookie. , And expire at 8 hours, no need to enter the PIN value within 8 hours. The purpose of this is for more security, making it more difficult for attackers in debugging mode to attack this site.

3-2. Four ways to open DEBUG mode

3-2-1. Set directly on the application object

Code example:

app.debug = True
app.run()

3-2-2. When executing the run method, pass parameters in

Code example:

app.run(debug=True)

3-2-3. Set in the config attribute

Code example:

app.config.update(DEBUG=True)

If everything is normal, the following information will be printed in the terminal:

 * Restarting with stat
* Debugger is active!
* Debugger pin code: 294-745-044
* Running on http://0.0.0.0:9000/ (Press CTRL+C to quit)

3-2-4. Setting in Pycharm Professional Edition

In Pycharm Professional Edition (not used in Community Edition), app.run()changes in Pycharm are invalid, and the project configuration needs to be edited.
Configuration screenshot

3-3. Configuration file

Introduction: The configuration of the Flask item is configured through the app.config object. If you want to configure an item to be in DEBUG mode, you can use app.config['DEBUG] = True to set it, and then the Flask item will run in DEBUG mode. In the Flask item, there are four ways to configure the item.

3-3-1. Hard coding

Code example:

app = Flask(__name__)
app.config['DEBUG'] = True

3-3-2. Passing updatemethod

Because app.config is an instance of flask.config.Config, and the Config class inherits from dict, all updatemethods can be used .

Code example:

app.config.update(
	DEBUG=True,
	SECRET_KEY='...'
)

3-3-3. app.config.from_object()Load custom module by method

If you have a lot of configuration items, you can put all the configuration items in a module, and then configure it by loading the module. Assuming that there is a settings.pymodule dedicated to storing configuration items, this You can app.config.from_object()load it through the method, and the method can receive the string name of the module or the module object.

Code example:

# 1. 通过模块字符串
app.config.from_object('settings')
# 2. 通过模块对象
import settings
app.config.from_object(settings)

3-3-4. By app.config.from_pyfile()loading custom modules

This method passes a file name, usually .pythe file at the end, but it is not limited to files that only use a .pysuffix.

Code example:

app.config.from_pyfile('settings.py',silent=True)

4. URL and View

4-1. URL and function mapping

Introduction: From the previous helloworld.py file, we have seen that a URL needs to be mapped with the execution function, and a @app.routedecorator is used. @app.routeIn the decorator, you can specify URL rules for more detailed mapping. For example, if you want to map a URL for the details of the chapter, the URL for the details of the chapter is /article/id/, and the id may be 1, 2, 3..., then you can Through the following formula.

  • string: The default data type, accepts a string without any slashes /.
  • int: plastic surgery.
  • float: Floating point type.
  • path: Similar to string, but you can pass a slash /.
  • uuid: a string of uuid type.
  • any: multiple paths can be specified
  • Code example:
@app.route('/<any(article,blog):url_path>/')
def item(url_path):
	return url_path

If you don't want to customize the subpath to pass parameters, you can also pass the parameters in the traditional form of ?=, for example: /article?id=xxx, in this case, you can use request.args.get('id')to get the value of id. If it is a post method, you can request.form.get('id')get it through come.

4-2. Construct URL

Introduction: Generally, we can execute a certain function through a URL. If the other way around, we know a function, how do we get this URL? The url_for function can help us achieve this function. The url_for() function receives two or more parameters. It receives the function name as the first parameter, and receives the named parameter corresponding to the URL rule. If there are other parameters, they will be added to the back of the URL as query parameters.

url_for(函数名)The advantages:

  1. If only the URL is modified, but the function name corresponding to the URL is not modified, there is no need to replace the URL everywhere.
  2. url_for()The function will escape some special characters and unicode strings, and url_for will automatically help us handle these things.
    Code example:
from flask import Flask,url_for
app = Flask(__name__)

@app.route('/article/<id>/')
def article(id):
	return '%s article detail' % id


@app.route('/')
def index():
	print(url_for("article",id=1))
	return "⾸⻚"

4-3. Specify the slash at the end of the URL

Some URLs have a slash at the end, and some URLs have no slash at the end. These are actually two different URLs.

 @app.route('/article/')
 def articles():
 	return '⽂章列表⻚'

In the above example, when you visit a URL without a slash at the end: /article, you will be redirected to the URL with a slash: /article/. But when we define the url of the article, if there is no slash at the end, but a slash is added when accessing, then a 404 error page will be thrown:

@app.route("/article")
def articles(request):
	return "⽂章列表⻚⾯"

The above does not add a slash at the end, so when accessing /article/, a 404 error will be thrown.

4-4. Designated HTTP method

In @app.route()the START ⼀ keywords can pass parameters to specify the methods of the present Remedies ⽀ support of HTTP Remedies, by default, Use only the GET request.

Code example:

@app.route('/login/',methods=['GET','POST'])
def login():
	return 'login'

Note: When specified methods, only the specified method is valid, the default GET will be invalid, and multiple request methods can be specified at the same time.

4-5. Page Jump and Redirect

Introduction: Redirection is divided into permanent redirection and temporary redirection. The operation reflected on the page is that the browser will automatically jump from one page to the other. For example, the user has accessed a page that requires permission, but the user is not currently logged in, so we should redirect him to the login page.

  • Permanent redirection: 301It is mostly used when the old website is abandoned and needs to be transferred to a new
    website to ensure user access. The most classic is the Jingdong website. When you enter www.jingdong.com, it will Redirected to www.jd.com, because the address jingdong.com has been abandoned and changed to jd.com, so permanent redirection should be used in this case.
  • Temporary redirection:, 302indicates a temporary redirection of the page. Rather than accessing an
    address that requires permission, if the current user is not logged in, it should be redirected to the login page. In this case, temporary redirection should be used.

How to specify redirection in Flask?

In flask, redirection is achieved through flask.redirect(location,code=302)this function, which locationmeans that the URL to be redirected to should be used in conjunction with the url_for() function mentioned earlier. The code indicates which redirection to use, and the default is 302, which is temporary Redirection can be modified 301to achieve permanent redirection.

Code example:

from flask import Flask,url_for,redirect

app = Flask(__name__)
app.debug = True


@app.route('/login/',methods=['GET','POST'])
def login():
	return 'login page'


@app.route('/profile/',methods=['GET','POST'])
def profile():
	name = request.args.get('name')
	if not name:
		return redirect(url_for('login'))
	else:
		return name

4-6. Response ( Response)

Values ​​that can be returned:

  • Response object .
  • String . In fact, Flask recreates an werkzeug.wrappers.Responseobject based on the returned string type. Response takes the string as the body, the status code is 200, and the MIME type is text/html, and then returns the Response object.
  • Tuple . The format in the tuple is (response, status, headers). Response is a string, the status value is the status code, and headers are some response headers.
  • If it is not the above three types. Then Flask will be
    Response.force_type(rv,request.environ)converted into a request object .

Code sample 1: Create directly using Response

# 需要额外导入Rexponse
from werkzeug.wrappers import Response

@app.route('/about/')
def about():
	resp = Response(response='about page',status=200,content_type='text/html;c
harset=utf-8')
	return resp

Code sample 2: make_responseFunction creation

# 需要额外导入make_response
from flask import make_response

@app.route('/about/')
def about():
	return make_response('about page')

Code sample 3: Return the form of tuple

 @app.errorhandler(404)
def not_found():
	return 'not found',404

Guess you like

Origin blog.csdn.net/weixin_45550881/article/details/105463897