|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 maxliu06 于 2022-3-9 14:56 编辑
代码如下: 然后通过apipost 请求接口时, user 永远都是为空的 ,这是为什么??
- from flask import Flask, g, request, flash, redirect, url_for, make_response, jsonify
- from flask_httpauth import HTTPBasicAuth
- app = Flask(__name__)
- app.config['SECRET_KEY'] = 'secret key'
- app.debug = True
- auth = HTTPBasicAuth()
- from werkzeug.security import generate_password_hash, check_password_hash
- # 模拟数据库
- books = ['The Name of the Rose', 'The Historian', 'Rebecca']
- users = [
- {'username': 'ethan', 'password': generate_password_hash('6666')},
- {'username': 'peter', 'password': generate_password_hash('4567')}
- ]
- # 回调函数
- @auth.verify_password
- def verify_password(username, password):
- user = filter(lambda user: user['username'] == username, users)
- user = list(user)
- print(user)
- if user and check_password_hash(user[0]['password'], password):
- g.user = username
- return True
- return False
- @app.route('/', methods=['POST'])
- @auth.login_required
- def add_book():
- _form = request.form
- print(_form)
- title = _form["title"]
- if not title:
- return '<h1>invalid request</h1>'
- books.append(title)
- flash("add book successfully!")
- return redirect(url_for('index'))
- @auth.error_handler
- def unauthorized():
- return make_response(jsonify({'error': 'Unauthorized access'}), 401)
- if __name__ == '__main__':
- app.run()
复制代码
本帖最后由 isdkz 于 2022-3-10 12:49 编辑
因为 HTTPBasicAuth 的认证方式不是通过 post 参数,
而是通过请求头字段Authorization,
规范为 Authorization: basic ("用户名:密码" 的 base64编码),
例如 ethan:6666 的 base64 编码为 ZXRoYW46NjY2Ng==,
你应该在postman的 Header 而不是 Body 加上 Authorization,值为 basic ZXRoYW46NjY2Ng==,
你可以看一下这篇文章的第七点:
https://blog.csdn.net/qq285679784/article/details/102891070
|
-
-
|