这篇文章主要介绍“怎么用Python Flask实现登录功能”,在日常操作中,相信很多人在怎么用Python Flask实现登录功能问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么用Python Flask实现登录功能”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
from flask import Flask
app = Flask(__name__) # flask对象实例化
@app.route('/index') #定义首页
@app.route('/') #设置默认index
def index():
return 'hello world!'
@app.route('/home/<string:username>') # 生成home路由,单一传参
def home(username):
print(username)
return '<h2>欢迎回家</h2>'
@app.route('/main/<string:username>/<string:password>') #多个参数传递
def main(username,password):
print(username)
print(password)
return '<h2>welcome</h2>'
def about():
return 'about page'
app.add_url_rule(rule='/about',view_func=about) #另一种添加路由的方式
if __name__ == '__main__':
app.debug = True #开启debug模式
app.run()
#app.py
#app.py
from flask import Flask,render_template #倒入模版
app = Flask(__name__) #声明模版文件夹
@app.route(('/index'))
def index():
return render_template('index.html') #返回模版
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>hello hello</h2>
<img src="https://atts.yisu.com/attachments/1.png">
</body>
</html>
from flask import Flask,jsonify
app = Flask(__name__)
@app.route('/')
def index():
user = {'name':'李三','password':'123'}
return jsonify(user)
if __name__ == '__main__':
app.run(debug=True)
from flask import Flask, redirect #导入跳转模块
app = Flask(__name__)
@app.route('/index')
def index():
return redirect('https://www.baidu.com') #指定跳转路径,访问/index目录即跳到百度首页
@app.route('/home')
def home():
return 'home page'
if __name__ == '__main__':
app.run(debug=True)
from flask import Flask,url_for #导入模块
app = Flask(__name__)
@app.route('/index')
def index():
return 'test'
@app.route('/home')
def home():
print(url_for('index')) 打印 index路由
return 'home page'
if __name__ == '__main__':
app.run(debug=True)
# 访问home,将name带入index并显示在页面
from flask import Flask,url_for,redirect #导入模块
app = Flask(__name__)
@app.route('/index<string:name>')
def index(name):
return 'test %s' % name
@app.route('/home')
def home():
return redirect(url_for('index',name='admin'))
if __name__ == '__main__':
app.run(debug=True)
from flask import Flask,render_template #倒入模版
app = Flask(__name__) #声明模版文件夹
@app.route(('/index'))
def index():
user = 'admin'
data = ['111',2,'李三']
userinfo = {'username':'lisan','password':'12333'}
return render_template('index.html',user=user,data=data,userinfo=userinfo) #返回模版,传入数据
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>11111</h2>
{{user}}
{{data}} #直接传入
{% if user == 'admin'%} #简单逻辑判断
<h2 >管理员</h2>
{% else %}
<h2 >普通用户</h2>
{% endif %}
<hr>
{% for item in data %} # for循环
<li>{{item}}</li>
{% endfor %}
<hr>
{{ userinfo['username'] }}
{{ userinfo['password'] }}
<hr>
{{ user | upper }} #字母大写(更多可查阅jinjia2过滤器)
</body>
</html>
目的是为了更好的细分功能模块
├── admin
│ └── admin.py
└── app.py
#admin.py
from flask import Blueprint 导入蓝图模块
admin = Blueprint('admin',__name__,url_prefix='/admin') #对象实例化,url_prefix添加路由前缀,表示若想访问本页相关路由,只能通过形如 xxx/admin/login 访问,不能 xxx/login访问
@admin.route('/register')
def register():
return '欢迎注册'
@admin.route('/login')
def login():
return '欢迎登录'
#app.py
from flask import Flask
from admin.admin import admin as admin_blueprint # 导入蓝图
app = Flask(__name__) #声明模版文件夹
app.register_blueprint(admin_blueprint) #注册蓝图
@app.route(('/index'))
def index():
return 'index page'
if __name__ == '__main__':
app.run(debug=True)
#web.py
from flask import Flask,render_template,request,redirect,flash,url_for,session
from os import urandom
app = Flask(__name__)
app.config['SECRET_KEY'] = urandom(50)
@app.route('/index')
def index():
if not session.get('user'):
flash('请登录后操作','warning')
return redirect(url_for('login'))
return render_template('index.html')
@app.route('/login',methods=['GET','POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
elif request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
if username == 'admin' and password == '888888':
flash('登录成功','success')
session['user'] = 'admin'
return redirect(url_for('index'))
else:
flash('登录失败','danger')
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(debug=True)
# index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://atts.yisu.com/attachments/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
</head>
<body>
<h2>欢迎你,管理员</h2>
{% for color, message in get_flashed_messages(with_categories=True) %}
<div class="alert alert-{{color}} alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<p>{{message}}</p>
</div>
{% endfor %}
</body>
</html>
#login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://atts.yisu.com/attachments/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
</head>
<body>
<form action="/login" method="post">
<div class='form-group'>
<input type="text" name="username" placeholder="请输入用户名" class="form-control">
</div>
<div class='form-group'>
<input type="password" name="password" placeholder="请输入密码" class="form-control">
</div>
<div class="form-group">
<input type="submit" value= "submit" class="btn btn-primary">
</div>
</form>
{% for color, message in get_flashed_messages(with_categories=True) %}
<div class="alert alert-{{color}} alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<p>{{message}}</p>
</div>
{% endfor %}
</body>
</html>
到此,关于“怎么用Python Flask实现登录功能”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。