当前位置:网站首页>First experience of flask
First experience of flask
2022-07-24 23:45:00 【Clean night mortal dust】
flask First experience
preparation
Creating a virtual environment
mkdir myproject
cd myproject
python3 -m venv venv
Activate the virtual environment
. venv/bin/activate
install Flask
pip3 install Flask
One of the simplest applications
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return '<p>Hello World!</p>'
if __name__ == '__main__':
''' :param host: Specify listening host , The default is 127.0.0.1(localhost), Set up 0.0.0.0 Run any network access :param port: Specify exposure port , Default usage port 5000 :param debug: The default is false. If set to true, Provides debugging information :param options: To forward to the bottom Werkzeug The server . '''
app.run(debug=True)
route
modern web Applications use meaningful URL , This helps users remember , Web pages will be more favored by users , Improve the return rate .
Use route() Decorator to bind functions to URL:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello, World'
Variable rule
Flask Variable rule
Through the URL Part of the is marked as <variable_name> You can go to URL Add variables to .
Of the tag Part will be passed to the function as a keyword parameter .
By using converter:variable_name , Sure Selectively add a converter , Specify rules for variables
from markupsafe import escape
from flask import Flask
app = Flask(__name__)
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return f'User {
escape(username)}'
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return f'Post {
post_id}'
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
# show the subpath after /path/
return f'Subpath {
escape(subpath)}'
Converter type
| type | describe |
|---|---|
| string | ( The default value ) Accept any text without slashes |
| int | Accept positive integers |
| float | Accept a positive floating point number |
| path | similar string, But it can contain slashes |
| uuid | Accept UUID character string |
HTML escape
When to return to HTML ( Flask The default response type in ) when , To prevent injection attacks , All users The value supplied must be escaped before output rendering . Use Jinja Rendered HTML The template will do this automatically .
Manual escape
from markupsafe import escape
from flask import Flask
app = Flask(__name__)
@app.route("/<name>")
def hello(name):
return f"Hello, {
escape(name)}!"
Flask URL structure
url_for() Functions are important for building specific functions dynamically URL Very useful .
url_for() The function takes the name of the function as the first argument , And one or more keyword parameters , Each parameter corresponds to URL The variable part of
from flask import Flask, redirect, url_for
app = Flask(__name__)
# Use redirect and url_for To jump
@app.route('/admin')
def hello_admin():
return 'Hello admin'
@app.route('/guset/<guset>')
def hello_guset(guset):
return f'Hello {
guset} as Guset'
@app.route('/user/<name>')
def show_name(name):
if name == 'admin':
return redirect(url_for('hello_admin'))
else:
return redirect(url_for('hello_guset', guset=name))
if __name__ == '__main__':
app.run(debug=True)
show_name Function to check whether the received parameter is consistent with 'admin’ Match , If matching url_for() Redirect the app to hello_admin() Go to , Otherwise, the part parameter is taken as guset Pass to hello_guset() function .
FLASK HTTP Method
- Http Protocol is the basis of data communication in the world wide web . Defined in the protocol from the specified URL Different ways to retrieve data .
Method describe GET Send data to the server in an unencrypted form . The most common method . HEAD and GET In the same way , But there's no responder . POST Is used to HTML The form data is sent to the server .POST Method is not cached by the server . PUT Replace all current representations of the target resource with the uploaded content . DELETE Delete from URL All current representations of the given target resource . Create one under the path login.html
<html> <head> <meta charset="utf-8"/> <title>Flask HTTP Request method processing </title> </head> <body> <form action = "http://localhost:5000/login" method = "post"> <p> Enter a name :</p> <p><input type = "text" name = "name" value=""/></p> <p><input type = "submit" value = " Submit " /></p> </form> </body> </html>python Enter the following script
from flask import Flask, redirect, url_for, request app = Flask(__name__) @app.route('/success/<name>') def success(name): return 'welcome %s' % name @app.route('/login', methods=['POST', 'GET']) def login(): if request.method == 'POST': user = request.form['name'] return redirect(url_for('success', name=user)) else: user = request.args.get('name') return redirect(url_for('success', name=user)) if __name__ == '__main__': app.run(debug=True)start-up flask service , take login.html Drag and drop into the browser to open , Input and submit , You will see that you are transferred to flask success() Function

The above is the use of Flask A simple record of
边栏推荐
- codeforces round #797 ABCDEFG
- Cross entropy loss
- Transmission download list, download file migration machine guide
- Financial products can reach 6%. I want to open an account to buy financial products
- Answers to some problems encountered in the process of Xperia XZ (f8332) brushing and root
- Piziheng embedded: the method of making source code into lib Library under MCU Xpress IDE and its difference with IAR and MDK
- How to put long links into Excel
- 云计算三类巨头:IaaS、PaaS、SaaS,分别是什么意思,应用场景是什么?
- Network Security Learning (V) DHCP
- Modify the existing annotator name in the word document
猜你喜欢

Notes of Teacher Li Hongyi's 2020 in-depth learning series 4

With screen and nohup running, there is no need to worry about deep learning code anymore | exiting the terminal will not affect the operation of server program code

Live broadcast preview | online seminar on open source security governance models and tools

Add a little surprise to life and be a prototype designer of creative life -- sharing with X contestants in the programming challenge

Effect evaluation of generative countermeasure network

基于TensorFlow和Keras的卷积神经网络实现猫狗数据集分类实验

Opengauss kernel analysis: query rewriting

Vite3.0 has been released, can you still roll it (list of new features)

Notes of Teacher Li Hongyi's 2020 in-depth learning series 9

Implementation of cat and dog data set classification experiment based on tensorflow and keras convolutional neural network
随机推荐
Network Security Learning (V) DHCP
基于Verilog HDL的数字秒表
Notes of Teacher Li Hongyi's 2020 in-depth learning series 9
Understanding complexity and simple sorting operation
Modify the existing annotator name in the word document
买收益百分之6的理财产品,需要开户吗?
Solve the problem that JSP cannot use session.getattribute()
Add a little surprise to life and be a prototype designer of creative life -- sharing with X contestants in the programming challenge
The new version of SSM video tutorial in shangsilicon valley was released
Video chat source code - one-to-one live broadcast system source code
Upgrade the jdbc driver to version 8.0.28 and connect to the pit record of MySQL
codeforces round #797 ABCDEFG
From the big guy baptism! 2022 headline first hand play MySQL advanced notes, and it is expected to penetrate P7
把字符串转换成整数与不要二
Google Earth engine - the use of the neighborhood tobands function
In pgplsql: = and=
Use and partial explanation of QDIR class
Excel file processing tool class (based on easyexcel)
Use SQLite provided by the system
.net redis client newlife.redis.core library usage