当前位置:网站首页>Initial flask and simple application
Initial flask and simple application
2022-07-25 14:07:00 【Ride Hago to travel】

Yes , You're not mistaken , The above figure represents Flask. that Flask Why are the gods ?
Flask It's a use Python Written lightweight Web Application framework . Its WSGI The tool box uses Werkzeug , The template engine uses Jinja2 .Flask Use BSD to grant authorization .
Compared with similar frameworks ,Flask The frame looks more flexible , Light , Safe and easy to use !
One , Configure environment variables before starting
Windows Users can directly access the dos Window or pycharm Below Terminal Enter the following command :
pip install flask
Two , An example shows Flask ‘ light ’ Where ?
notes : It is suggested to build a new python project
from flask import Flask
app = Flask(__name__) # Create a Flask object
@app.route('/study') # Use route() Decorator to tell Flask Trigger function URL
def study():
return "<h1>Hello Word!</h1>"
app.run() # Start the service
pycharm Right click directly in run Can run 

notes : It can be seen from the running results in the above figure Flask The default port is 5000, and Django The default port is 8000, Tornado The default port is 8888;
Just six lines of code , You can run , Dare you say it doesn't ‘ light ’?
3、 ... and , Simply start a user management system
Actually , If you are right Django I know something about the framework , To learn Flask Will appear very calm .
1, Realize simple user login
from flask import Flask, request, render_template
app = Flask(__name__) # Create a Flask object
@app.route('/login', methods=['GET', 'POST', ]) # mothods=['GET', 'POST', ] Indicates that you can send GET request , It can also be sent POST request
def login():
if request.method == "GET": # If it's sending GET request
return render_template('login.html') # Use render_template() Method to render templates , amount to Django Medium render()
else:
user = request.form.get('username') # request.form.get() Said by post Method to get the value
pwd = request.form.get('password')
if user == 'hpl' and pwd == '123456':
return "<h1> Congratulations on your successful login !</h1>"
else:
return render_template('login.html', error=' Wrong user name or password !')
app.run(debug=True) # Start the service debug=True Said to start debug mode
Create a file named... In the root directory templates Folder , Users place templates ( and Django It's similar to ); And create a login.html file , The contents are as follows :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Welcome to the landing page </title>
</head>
<body>
<h1> Sign in </h1>
<form action="" method="post">
<p>
<label for=""> user name :</label>
<input type="text" name="username">
</p>
<p>
<label for=""> password :</label>
<input type="password" name="password">
<span style="color:red;">{
{ error }}</span>
</p>
<button> Submit </button>
</form>
</body>
</html>
run once , The result is :
When the user name or password is wrong :
When the user name and password are correct :
2, Put the user's login information into session in
from flask import Flask, request, render_template, session
app = Flask(__name__) # Create a Flask object
app.secret_key = 'jkdfgd' # Equivalent to adding salt ( I'm not sure what's in it )
@app.route('/login', methods=['GET', 'POST', ]) # mothods=['GET', 'POST', ] Indicates that you can send GET request , It can also be sent POST request
def login():
if request.method == "GET": # If it's sending GET request
return render_template('login.html') # Use render_template() Method to render templates , amount to Django Medium render()
else:
user = request.form.get('username') # request.form.get() Said by post Method to get the value
pwd = request.form.get('password')
# Put user information in session
session['user_information'] = user
if user == 'hpl' and pwd == '123456':
return "<h1> Congratulations on your successful login !</h1>"
else:
return render_template('login.html', error=' Wrong user name or password !')
app.run(debug=True) # Start the service debug=True Said to start debug mode
After logging in again , Here's the picture 
3, Display basic user information and detailed information
from flask import Flask, request, render_template, session, redirect
USER_DICT = {
'1': {
'name': ' Bald head strength ', 'age': 30, 'sex': ' male ', 'address': ' Tuanjietun '},
'2': {
'name': ' Big marmoset ', 'age': 25, 'sex': ' male ', 'address': ' Unknown '},
'3': {
'name': ' Er Gouzi ', 'age': 26, 'sex': ' male ', 'address': ' Unknown '},
'4': {
'name': ' Boss Li ', 'age': 42, 'sex': ' male ', 'address': ' Metropolis '},
'5': {
'name': ' Cui Hua ', 'age': 18, 'sex': ' Woman ', 'address': ' The forest '},
}
app = Flask(__name__) # Create a Flask object
app.secret_key = 'jkdfgd' # Equivalent to adding salt ( I'm not sure what's in it )
@app.route('/login', methods=['GET', 'POST', ]) # mothods=['GET', 'POST', ] Indicates that you can send GET request , It can also be sent POST request
def login():
if request.method == "GET": # If it's sending GET request
return render_template('login.html') # Use render_template() Method to render templates , amount to Django Medium render()
else:
user = request.form.get('username') # request.form.get() Said by post Method to get the value
pwd = request.form.get('password')
# Put user information in session
session['user_information'] = user
if user == 'hpl' and pwd == '123456':
return redirect('/index') # Redirect ( and Django It's similar to )
else:
return render_template('login.html', error=' Wrong user name or password !')
@app.route('/index', methods=['GET', ], endpoint='index') # Same as Django Medium name, For reverse parsing
def index():
user_info = session.get('user_information')
if not user_info:
return redirect('/login')
return render_template('index.html', user_dict=USER_DICT)
@app.route('/detail', methods=['GET', ], endpoint='detail')
def detail():
user_info = session.get('user_information')
if not user_info:
return redirect('/login')
user_id = request.args.get('user_id')
info = USER_DICT.get(user_id)
return render_template('detail.html', info=info)
app.run(debug=True) # Start the service debug=True Said to start debug mode
stay templates Create under folder index.html Document and detail.html file
index.html in
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> User information </title>
</head>
<body>
<h2> User information </h2>
<table border="1px" cellspacing="0" cellpadding="5px">
<thead>
<tr>
<th> full name </th>
<th> operation </th>
</tr>
</thead>
<tbody>
{
% for k,v in user_dict.items() %}
<tr>
<td>{
{
v.name }}</td>
<td><a href="/detail?user_id={
{ k }}"> Check the details </a></td>
</tr>
{
% endfor %}
</tbody>
</table>
</body>
</html>
detail.html in
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Information details display page </title>
</head>
<body>
<h1> Details </h1>
<table border="1px" cellpadding="5px" cellspacing="0">
<thead>
<tr>
<th> full name </th>
<th> Age </th>
<th> Gender </th>
<th> address </th>
</tr>
</thead>
<tbody>
<tr>
<td>{
{
info.name }}</td>
<td>{
{
info.age }}</td>
<td>{
{
info.sex }}</td>
<td>{
{
info.address }}</td>
</tr>
</tbody>
</table>
</body>
</html>
The result is 

4, Log out
from flask import Flask, request, render_template, session, redirect
USER_DICT = {
'1': {
'name': ' Bald head strength ', 'age': 30, 'sex': ' male ', 'address': ' Tuanjietun '},
'2': {
'name': ' Big marmoset ', 'age': 25, 'sex': ' male ', 'address': ' Unknown '},
'3': {
'name': ' Er Gouzi ', 'age': 26, 'sex': ' male ', 'address': ' Unknown '},
'4': {
'name': ' Boss Li ', 'age': 42, 'sex': ' male ', 'address': ' Metropolis '},
'5': {
'name': ' Cui Hua ', 'age': 18, 'sex': ' Woman ', 'address': ' The forest '},
}
app = Flask(__name__) # Create a Flask object
app.secret_key = 'jkdfgd' # Equivalent to adding salt ( I'm not sure what's in it )
@app.route('/login', methods=['GET', 'POST', ]) # mothods=['GET', 'POST', ] Indicates that you can send GET request , It can also be sent POST request
def login():
if request.method == "GET": # If it's sending GET request
return render_template('login.html') # Use render_template() Method to render templates , amount to Django Medium render()
else:
user = request.form.get('username') # request.form.get() Said by post Method to get the value
pwd = request.form.get('password')
# Put user information in session
session['user_information'] = user
if user == 'hpl' and pwd == '123456':
return redirect('/index')
else:
return render_template('login.html', error=' Wrong user name or password !')
@app.route('/index', methods=['GET', ], endpoint='index')
def index():
user_info = session.get('user_information')
if not user_info:
return redirect('/login')
return render_template('index.html', user_dict=USER_DICT)
@app.route('/detail', methods=['GET', ], endpoint='detail')
def detail():
user_info = session.get('user_information')
if not user_info:
return redirect('/login')
user_id = request.args.get('user_id')
info = USER_DICT.get(user_id)
return render_template('detail.html', info=info)
@app.route('/logout', methods=['GET', ])
def logout():
del session['user_information'] # Delete session You can log out
return redirect('/login')
app.run(debug=True) # Start the service debug=True Said to start debug mode
More details , see Flask Developing documents :https://dormousehole.readthedocs.io/en/latest/
边栏推荐
- Goldfish rhca memoirs: cl210 managing storage -- managing shared file systems
- 职场「数字人」不吃不睡007工作制,你「卷」得过它们吗?
- Arduino code of key state machine for realizing single, double click, long press and other functions with esp32 timed interrupt
- Problems and extensions of the monocular depth estimation model featdepth in practice
- 基于redis的keys、scan删除ttl为-1的key
- From fish eye to look around to multi task King bombing -- a review of Valeo's classic articles on visual depth estimation (from fisheyedistancenet to omnidet) (Part I)
- 手把手教学Yolov7的搭建及实践
- ~4.1 sword finger offer 05. replace spaces
- leetcode202---快乐数
- From fish eye to look around to multi task King bombing -- a review of Valeo's classic articles on visual depth estimation (from fisheyedistancenet to omnidet) (Part 2)
猜你喜欢

Comprehensive sorting and summary of maskrcnn code structure process of target detection and segmentation

Okaleido生态核心权益OKA,尽在聚变Mining模式

科隆新能源IPO被终止:拟募资6亿 先进制造与战新基金是股东

IDEA设置提交SVN时忽略文件配置

Emergency science | put away this summer safety guide and let children spend the summer vacation safely!
![[原创]九点标定工具之机械手头部相机标定](/img/de/5ea86a01f1a714462b52496e2869d6.png)
[原创]九点标定工具之机械手头部相机标定

Brush questions - Luogu -p1150 Peter's smoke

Multidimensional pivoting analysis of CDA level1 knowledge points summary

Brush questions - Luogu -p1046 Tao Tao picking apples

应急科普|收好这份暑期安全指南,让孩子安全过暑假!
随机推荐
Alibaba mqtt IOT platform "cloud product circulation" practice - the two esp32 achieve remote interoperability through the IOT platform
opencv视频跟踪「建议收藏」
Pytest.mark.parameterize and mock use
2271. Maximum number of white bricks covered by blanket ●●
飞盘局有多快乐?2022年轻人新潮运动报告
Working mode and sleep mode of nlm5 series wireless vibrating wire sensor acquisition instrument
OKA通证权益解析,参与Okaleido生态建设的不二之选
新唐NUC980设置DHCP或者静态IP
苹果手机端同步不成功,退出登录,结果再也登录不了了
【目录爆破工具】信息收集阶段:robots.txt、御剑、dirsearch、Dirb、Gobuster
手把手教学Yolov7的搭建及实践
Leetcode1 -- sum of two numbers
Okaleido生态核心权益OKA,尽在聚变Mining模式
~5 new solution of CCF 2021-12-2 sequence query
Brush questions - Luogu -p1047 trees outside the school gate
Introducing mlops interpretation (I)
CSV文本文件导入excel的四种方法
Practice of online problem feedback module (13): realize multi parameter paging query list
2271. 毯子覆盖的最多白色砖块数 ●●
Typora无法打开提示安装新版本解决办法