python可以在使用curl发送请求时处理会话吗?

2024-04-20 07:17:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我的iOS移动应用程序构建一组API。在

我使用Flask-RESTful' to build RESTful type of interfaces andFlask login`帮助我处理用户登录问题。在

但是,我发现,当我使用curl登录时,服务器确实会返回成功消息,而我则会发送一个请求来获取只有登录的用户才能看到和获取的“受保护”页面

{ "message": "The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn't understand how to supply the credentials required." }

如果curl不发送一些“用户凭据”,这是否意味着当我的iOS应用程序发送请求时,后端仍然无法识别该用户?在

我不太明白Flask是如何处理“session”的,而且我是web开发新手。有什么解决办法吗?在

这是我的代码:

api.py

# -*- coding: utf-8 -*-

import flask_login, json
from flask import request
from flask_restful import Resource, reqparse
from models import users, User

parser = reqparse.RequestParser()


def request_parser():
    parser.add_argument('data', action='append')
    return parser.parse_args()['data'][0]


class Login(Resource):
    def get(self):
        return

    def post(self):
        # data = request_parser()
        data = request.json['data']
        email = data['email']
        test = users[email]
        if data['pw'] == users[email]['pw']:
            user = User()
            user.id = email
            flask_login.login_user(user)
            return 'login success'

        return 'Bad login'



class Protected(Resource):
    @flask_login.login_required
    def get(self):
        return 'Logged in as: ' + flask_login.current_user.id

models.py

^{pr2}$

__init__.py

# -*- coding: utf-8 -*-

from flask import Flask
from flask_restful import Resource, Api
from flask_sqlalchemy import SQLAlchemy

import flask_login
import config

app = Flask(__name__)
app.config.from_object("config")
app.secret_key = 'yangjinglei'

api = Api(app)

login_manager = flask_login.LoginManager()
login_manager.init_app(app)

db = SQLAlchemy(app, use_native_unicode="utf8")

run.py

# -*- coding: utf-8 -*-

from app import app, api
from app.api import *


api.add_resource(Login, '/login')
api.add_resource(Protected, '/protected')

if __name__ == '__main__':
    app.run(debug=True)

Tags: 用户frompyimportapiappparserflask
1条回答
网友
1楼 · 发布于 2024-04-20 07:17:30

默认情况下,Flask使用cookies管理会话。引用Sessions documentation

This is implemented on top of cookies for you and signs the cookies cryptographically. What this means is that the user could look at the contents of your cookie but not modify it, unless they know the secret key used for signing.

您可以从curl cli管理cookies。参考this answer

要写入cookie文件并启动引擎并使用cookie,可以使用: curl -c /path/to/cookiefile http://yourhost/

从中读取cookie并启动cookie引擎,或者如果它不是一个文件,它将传递给定的字符串。 curl -b /path/to/cookiefile http//yourhost/

另一个可以遵循的模式是server side sessions。在

相关问题 更多 >