In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article to share with you is about how to understand Python full stack Flask, Xiaobian feel quite practical, so share to everyone to learn, I hope you can read this article after some gains, not much to say, follow Xiaobian to see it.
preface
Django is a comprehensive Python Web framework that provides a one-stop solution that integrates MVT (Model-View-Template) and ORM, as well as background management. But the shortcomings are also obvious, it is biased. It's like a decorated house, it provides what you need, and you can use it directly.
Flask is a lightweight Web framework compared to Django. Unlike Django, Flask is lightweight, simple, and customizable through third-party extensions.
Customizability, adding functionality by extension, is Flask's most important feature. Flask's two main core applications are Werkzeug and Jinja, the template engine.
WSGI
The Web Server Gateway Interface (WSGI) has been adopted as the standard for Python Web application development. WSGI is a specification for a common interface between Web servers and Web applications.
Werkzeug
It is a WSGI toolkit that implements requests, response objects, and utility functions. This enables web frameworks to be built on top of it. The Flask framework uses Werkzeug as one of its foundations.
jinja2
Jinja2 is a popular template engine for Python. Web templating systems combine templates with specific data sources to render dynamic web pages.
Flask is often referred to as a microframework. It is designed to keep the core of the application simple and extensible. Flask does not have a built-in abstraction layer for database processing, nor does it form validation support. Instead, Flask supports extensions to add such functionality to your application. Some popular Flask extensions are discussed later in this tutorial.
Flask
Flask Extension Pack:
Flask-SQLAlchemy: Working with databases
Flask-migrate: Manage migrated databases
Flask-Mail: Mail
Flask-WTF: Forms
Flask-script: insert script
Flask-Login: authenticate user status
Flask-RESTful: A tool for developing REST APIs
Flask-Bootstrap: Integrated front-end Twitter Bootstrap framework
Flask-Moment: Localized date and time
New flask project:
Run as follows:
The Flask module must be imported into the project. One object of the Flask class is our WSGI application.
The Flask constructor takes the name of the current module (__name __) as an argument.
The following parameters can be filled in to instantiate a Flask object, and their default values:
template_folder: the name of the folder where the template is located, the default is templates
root_path: You don't need to fill it in, it will be found automatically. The current execution file, the directory address is in return render_template. When the above two are spliced, the corresponding template address will be found.
static_folder: The name of the file where the static file is located. The default is static. You can leave it blank.
static_url_path: Address prefix of static file, what to write, when accessing static file, add this in front
instance_path and instance_relative_config are used together. These two parameters are used to find the configuration file. They are used when importing the configuration file using app.config.from_pyfile ('settings.py').
instance_relative_config: Default is False, when set to True, from_pyfile looks for files from the location specified by instance_path.
instsnce_path: Specify the path of the query file from_pyfile. If it is not set, it will look for the instance folder under the same level directory of the execution file of app.run() by default. If instance_path is configured (note that it needs to be an absolute path), it will be from the file under the specified address.
The route() function of the Flask class is a decorator that tells the application which URL should call the related function.
app.route(rule, options)
The rule parameter indicates the URL binding to the function.
options is a list of parameters to forward to the underlying Rule object.
In the example above, the '/ ' URL is bound to the hello_world() function. Therefore, when the web server's home page is opened in a browser, the output of this function is rendered.
The add_url_rule() function of the application object can also be used to bind URLs to functions, as follows:
def hello_world(): return 'hello world'app.add_url_rule('/', 'hello',hello_world)
Finally, the Flask class's run() method runs the application on the local development server.
app.run(host, port, debug, options)
host: Host name of the listener
post: Host port to listen to, default 5000
debug: debug mode, default false, set to flue to display debug information
options: To forward to the underlying werkzeng server
Examples of routing parameters:
from flask importFlaskapp = Flask(__name__)@app.route('/id/')def hello_world(idn): return 'HelloWorld! %d' %idnif __name__ == '__main__': app.run()
The parameters passed by route are handled as string by default, int is specified here, float, path is also supported, and the content after colon in angle brackets is dynamic.
Example of return status code:
Abort function:
If an unexpected error occurs during the execution of a view function, we can immediately terminate the execution of the view function using the abort function. With the abort function, you can return an error status code that exists in the http standard to the front end, indicating the error message that occurred.
Using abort to throw a custom status code that does not exist in the http standard has no practical meaning. If the abort function is triggered, the statements that follow it will not be executed. It is similar to Python's raise.
from flask importFlask,abortapp = Flask(__name__)@app.route('/id/')def hello_world(idn): abort(403) return 'HelloWorld! %d' %idn, 888if __name__ == '__main__': app.run()
In Flask, exceptions are caught by decorators, and errorhandler() receives an exception status code as an argument. The argument to the view function returns an error message.
Example of redirect:
from flask importFlask,redirectapp = Flask(__name__)@app.route('/')def hello_world(): return redirect('https://www.baidu.com')if __name__ == '__main__': app.run()
The effects are as follows:
url_for() function is useful for dynamically constructing URLs for specific functions. This function accepts the name of the function as a first argument, and one or more keyword arguments, each corresponding to a variable portion of the URL.
As follows:
@app.route('/user/')def hello_user(name): if name=='admin': return redirect(url_for('hello_admin')) else: return redirect(url_for('hello_guest',guest =name))
HTTP method:
Http protocol is the basis of data communication in the World Wide Web. Different methods for retrieving data from specified URLs are defined in the protocol.
Method Description:
GET: Send data to the server in unencrypted form to get the response content
POST: Used to upload HTML form data to the server
PUT: Replace the target resource's data with uploaded content
Delete: Delete the data of the target resource given by URL
HEAD: Same method as GET, but no response body
By default, Flask routes responses to GET requests. However, you can change this preference by providing method parameters for the route() decorator.
To demonstrate the POST method in URL routing, first let's create an HTML form and send the form data to the URL using the POST method.
login.html
Title
Enter Name:
loginok.html
Titlehello { { name }}
WC_public_flask.py
from flask importFlask, render_template, requestapp = Flask(__name__, template_folder='templates')@app.route('/')def login(): return render_template('login.html')@app.route('/login',methods = ['POST', 'GET'])def loginok(): if request.method== 'POST': user = request.form['nm'] return render_template('loginok.html',name =user) else: user = request.args.get('nm') return render_template('loginok.html',name =user)if __name__ == '__main__': app.run (debug = True) The above is how to understand Flask in Python full stack, Xiaobian believes that some knowledge points may be seen or used in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.