index.html
example.py
## index.html
```index.html
test login by Leetao未点击
var load_msg = function () {
$.get('/hello?api_key=test_login',function(data){
$('#test_login')[0].innerText = data
})
}
example.py
from flask import Flask, request, jsonify, render_template
from flask_login import LoginManager, current_user, login_required
login_manager = LoginManager()
app = Flask(__name__)
login_manager.init_app(app)
class User:
def __init__(self,user_name):
self.id = 'test_id'
self.user_name = user_name
@property
def is_active(self):
return True
@property
def is_authenticated(self):
return True
@property
def is_anonymous(self):
return False
def get_id(self):
try:
return text_type(self.id)
except AttributeError:
raise NotImplementedError('No `id` attribute - override `get_id`')
user = User("leetao")
@login_manager.request_loader
def load_from_request(request):
api_key = request.args.get('api_key')
if api_key == 'test_login':
return user
return None
@app.route('/hello')
@login_required
def hello_world():
print(current_user.user_name)
return jsonify('Hello, World!')
@app.route("/")
def index():
return render_template("index.html")
结果
为了方便理解,我截了两张图,一张是 api_key 正确的情况下,一张是 错误的情况下
api_key 正确
api_key 错误
结尾
关注公众号,不迷路,回复 Python 即可领取 Python 大礼包